title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
std::mt19937 Class in C++
|
30 Mar, 2021
std::mt19937(since C++11) class is a very efficient pseudo-random number generator and is defined in a random header file. It produces 32-bit pseudo-random numbers using the well-known and popular algorithm named Mersenne twister algorithm. std::mt19937 class is basically a type of std::mersenne_twister_engine class.
typedef mersenne_twister_engine<uint_fast32_t,
32,624,397,31,0x9908b0df,11,0xffffffff,7,0x9d2c5680,15,0xefc60000,18,1812433253>
mt19937;
Syntax :
mt19937 mt1(seed_value);
Here mt1 is an instance of the mt19937 class and it takes a seed value to generate an entire sequence.
mt19937 stands for mersenne twister with a long period of 219937 β 1 which means mt19937 produces a sequence of 32-bit integers that only repeats itself after 219937 β 1 number have been generated.
The std::mt19937 does two things β
When an std::mt19937 object is instantiated, it takes an argument which is used to generate seed value(like srand()).
By using operator(), it generates a random number (like rand()).
Below is the example to demonstrate the similarities:
C++
// C++ program for demonstrating // similaritites#include <ctime>#include <iostream>#include <random>using namespace std; int main(){ // Initializing the sequence // with a seed value // similar to srand() mt19937 mt(time(nullptr)); // Printing a random number // similar to rand() cout << mt() << '\n'; return 0;}
3529725061
Being a type of std::mersenne_twister_engine class it has the same member functions which mersenne_twister_engine does. Here is the list of some important member functions β
1. (constructor): constructs the mt19937 object. It takes either a seed value of result type or a seed sequence object(Similar to srand() function).
Example :
C++
// C++ program to implement // the above concept // This header file is // for time#include <ctime> #include <iostream>#include <random>using namespace std; int main(){ // Using the constructor to // initialize with a seed value mt19937 mt(time(nullptr)); // Operator() is used to // generate random numbers cout << mt() << '\n'; return 0;}
3529725061
2. min(): returns the minimum value operator() can return (which is zero).
Example:
C++
// C++ program for the // min()#include <ctime>#include <iostream>#include <random>using namespace std; // Driver codeint main(){ // Initializing mt19937 // object mt19937 mt(time(nullptr)); // Prints the minimum value // which is 0 cout << "the minimum integer it can generate is " << mt.min() << endl; return 0;}
the minimum integer it can generate is 0
3. max(): returns maximum value operator() can return ( which is 232 β 1 = 4294967295 )
Example :
C++
// C++ program to demonstrate // max()#include <ctime>#include <iostream>#include <random>using namespace std; // Driver codeint main(){ // Initializing mt19937 // object mt19937 mt(time(nullptr)); // Prints the maximum value // which is 4294967295 cout << "mt19937 can generate random numbers upto " << mt.max() << endl; return 0;}
mt19937 can generate random numbers upto 4294967295
4. seed(): reinitializes the seed value of the object either by taking a seed value of result type or by taking a seed sequence object.
Example :
C++
// C++ program to demonstrate// seed()#include <iostream>#include <random>using namespace std; // Driver codeint main(){ // Defining the // mt19937 object mt19937 mt; // Initializing a random // sequence with a seed value mt.seed(45218965); cout << "some random numbers generated by mt19937 are:" << endl; for (int i = 5; i > 0; i--) { cout << mt() << ' '; } return 0;}
some random numbers generated by mt19937 are:
3334444225 240363925 3350157104 146869560 639267854
5. operator(): it generates pseudo-random integers.(similar to rand() function).
Example:
C++
// C++ program to demonstrate// operator()#include <ctime>#include <iostream>#include <random>using namespace std; // Driver codeint main(){ // Initializing mt19937 // object mt19937 mt(time(nullptr)); for (int i = 0; i < 5; i++) { // operator() is used to // generate random numbers cout << mt() << ' '; } return 0;}
3529725061 3019704141 2006641117 725527349 3631905871
There are also non-member functions overloaded to work with std::mt19937 object. These are β
operator<<() β This is overloaded so that we can directly print the value generated by the mt19937 object to the output stream.
operator>>() β it is used to extract seed value from input.
Here is a simple example to generate a pseudo-random number by taking a seed value from the user β
Using operator<<() and operator>>() :
Example :
C++
// C++ program to demonstrate // operator>>() and <<operator()#include <ctime>#include <iostream>#include <random>using namespace std; // Driver codeint main(){ mt19937 mt; cout << "enter a integer to begin" << endl; // operator>>() is used to get // a seed value from the user cin >> mt; // <<operator() is used to print // the random integer cout << "a random number " << mt() << " is generated"; return 0;}
enter a integer to begin
a random number 3499211612 is generated
Although the rand() function can be used in a small range, it is inefficient for generating real-world like random numbers. A careful person can observe the repetitions of the random numbers generated by rand() which is very risky. Whereas std::mt19937 has the following advantages β
It has a very long period compared to the rand(). It will take a longer time. If an implementation of the Mersenne twister could generate 1,000,000,000 (one billion) pseudo-random numbers every second, a program that generated pseudo-random numbers would need to run about 1.3684 Γ 105,985 years to repeat the random sequence. So it is safe to assume that an observer will never guess the number.Many random number generators can be initiated simultaneously with different seed values. Here is an example β
It has a very long period compared to the rand(). It will take a longer time. If an implementation of the Mersenne twister could generate 1,000,000,000 (one billion) pseudo-random numbers every second, a program that generated pseudo-random numbers would need to run about 1.3684 Γ 105,985 years to repeat the random sequence. So it is safe to assume that an observer will never guess the number.
Many random number generators can be initiated simultaneously with different seed values. Here is an example β
C++
// C++ program to demonstrate// above approach#include <iostream>#include <random>using namespace std; // Driver codeint main(){ mt19937 mt1(10000); mt19937 mt2(100000); cout << mt1() << endl; cout << mt2() << endl; return 0;}
2342776460
1235064505
cpp-class
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Mar, 2021"
},
{
"code": null,
"e": 373,
"s": 53,
"text": "std::mt19937(since C++11) class is a very efficient pseudo-random number generator and is defined in a random header file. It produces 32-bit pseudo-random numbers using the well-known and popular algorithm named Mersenne twister algorithm. std::mt19937 class is basically a type of std::mersenne_twister_engine class. "
},
{
"code": null,
"e": 512,
"s": 373,
"text": "typedef mersenne_twister_engine<uint_fast32_t,\n 32,624,397,31,0x9908b0df,11,0xffffffff,7,0x9d2c5680,15,0xefc60000,18,1812433253>\n mt19937;"
},
{
"code": null,
"e": 521,
"s": 512,
"text": "Syntax :"
},
{
"code": null,
"e": 546,
"s": 521,
"text": "mt19937 mt1(seed_value);"
},
{
"code": null,
"e": 649,
"s": 546,
"text": "Here mt1 is an instance of the mt19937 class and it takes a seed value to generate an entire sequence."
},
{
"code": null,
"e": 847,
"s": 649,
"text": "mt19937 stands for mersenne twister with a long period of 219937 β 1 which means mt19937 produces a sequence of 32-bit integers that only repeats itself after 219937 β 1 number have been generated."
},
{
"code": null,
"e": 882,
"s": 847,
"text": "The std::mt19937 does two things β"
},
{
"code": null,
"e": 1000,
"s": 882,
"text": "When an std::mt19937 object is instantiated, it takes an argument which is used to generate seed value(like srand())."
},
{
"code": null,
"e": 1065,
"s": 1000,
"text": "By using operator(), it generates a random number (like rand())."
},
{
"code": null,
"e": 1119,
"s": 1065,
"text": "Below is the example to demonstrate the similarities:"
},
{
"code": null,
"e": 1123,
"s": 1119,
"text": "C++"
},
{
"code": "// C++ program for demonstrating // similaritites#include <ctime>#include <iostream>#include <random>using namespace std; int main(){ // Initializing the sequence // with a seed value // similar to srand() mt19937 mt(time(nullptr)); // Printing a random number // similar to rand() cout << mt() << '\\n'; return 0;}",
"e": 1452,
"s": 1123,
"text": null
},
{
"code": null,
"e": 1464,
"s": 1452,
"text": "3529725061\n"
},
{
"code": null,
"e": 1638,
"s": 1464,
"text": "Being a type of std::mersenne_twister_engine class it has the same member functions which mersenne_twister_engine does. Here is the list of some important member functions β"
},
{
"code": null,
"e": 1787,
"s": 1638,
"text": "1. (constructor): constructs the mt19937 object. It takes either a seed value of result type or a seed sequence object(Similar to srand() function)."
},
{
"code": null,
"e": 1797,
"s": 1787,
"text": "Example :"
},
{
"code": null,
"e": 1801,
"s": 1797,
"text": "C++"
},
{
"code": "// C++ program to implement // the above concept // This header file is // for time#include <ctime> #include <iostream>#include <random>using namespace std; int main(){ // Using the constructor to // initialize with a seed value mt19937 mt(time(nullptr)); // Operator() is used to // generate random numbers cout << mt() << '\\n'; return 0;}",
"e": 2155,
"s": 1801,
"text": null
},
{
"code": null,
"e": 2166,
"s": 2155,
"text": "3529725061"
},
{
"code": null,
"e": 2241,
"s": 2166,
"text": "2. min(): returns the minimum value operator() can return (which is zero)."
},
{
"code": null,
"e": 2250,
"s": 2241,
"text": "Example:"
},
{
"code": null,
"e": 2254,
"s": 2250,
"text": "C++"
},
{
"code": "// C++ program for the // min()#include <ctime>#include <iostream>#include <random>using namespace std; // Driver codeint main(){ // Initializing mt19937 // object mt19937 mt(time(nullptr)); // Prints the minimum value // which is 0 cout << \"the minimum integer it can generate is \" << mt.min() << endl; return 0;}",
"e": 2592,
"s": 2254,
"text": null
},
{
"code": null,
"e": 2633,
"s": 2592,
"text": "the minimum integer it can generate is 0"
},
{
"code": null,
"e": 2722,
"s": 2633,
"text": "3. max(): returns maximum value operator() can return ( which is 232 β 1 = 4294967295 )"
},
{
"code": null,
"e": 2732,
"s": 2722,
"text": "Example :"
},
{
"code": null,
"e": 2736,
"s": 2732,
"text": "C++"
},
{
"code": "// C++ program to demonstrate // max()#include <ctime>#include <iostream>#include <random>using namespace std; // Driver codeint main(){ // Initializing mt19937 // object mt19937 mt(time(nullptr)); // Prints the maximum value // which is 4294967295 cout << \"mt19937 can generate random numbers upto \" << mt.max() << endl; return 0;}",
"e": 3094,
"s": 2736,
"text": null
},
{
"code": null,
"e": 3146,
"s": 3094,
"text": "mt19937 can generate random numbers upto 4294967295"
},
{
"code": null,
"e": 3282,
"s": 3146,
"text": "4. seed(): reinitializes the seed value of the object either by taking a seed value of result type or by taking a seed sequence object."
},
{
"code": null,
"e": 3292,
"s": 3282,
"text": "Example :"
},
{
"code": null,
"e": 3296,
"s": 3292,
"text": "C++"
},
{
"code": "// C++ program to demonstrate// seed()#include <iostream>#include <random>using namespace std; // Driver codeint main(){ // Defining the // mt19937 object mt19937 mt; // Initializing a random // sequence with a seed value mt.seed(45218965); cout << \"some random numbers generated by mt19937 are:\" << endl; for (int i = 5; i > 0; i--) { cout << mt() << ' '; } return 0;}",
"e": 3709,
"s": 3296,
"text": null
},
{
"code": null,
"e": 3807,
"s": 3709,
"text": "some random numbers generated by mt19937 are:\n3334444225 240363925 3350157104 146869560 639267854"
},
{
"code": null,
"e": 3888,
"s": 3807,
"text": "5. operator(): it generates pseudo-random integers.(similar to rand() function)."
},
{
"code": null,
"e": 3897,
"s": 3888,
"text": "Example:"
},
{
"code": null,
"e": 3901,
"s": 3897,
"text": "C++"
},
{
"code": "// C++ program to demonstrate// operator()#include <ctime>#include <iostream>#include <random>using namespace std; // Driver codeint main(){ // Initializing mt19937 // object mt19937 mt(time(nullptr)); for (int i = 0; i < 5; i++) { // operator() is used to // generate random numbers cout << mt() << ' '; } return 0;}",
"e": 4242,
"s": 3901,
"text": null
},
{
"code": null,
"e": 4296,
"s": 4242,
"text": "3529725061 3019704141 2006641117 725527349 3631905871"
},
{
"code": null,
"e": 4390,
"s": 4296,
"text": "There are also non-member functions overloaded to work with std::mt19937 object. These are β "
},
{
"code": null,
"e": 4518,
"s": 4390,
"text": "operator<<() β This is overloaded so that we can directly print the value generated by the mt19937 object to the output stream."
},
{
"code": null,
"e": 4578,
"s": 4518,
"text": "operator>>() β it is used to extract seed value from input."
},
{
"code": null,
"e": 4678,
"s": 4578,
"text": "Here is a simple example to generate a pseudo-random number by taking a seed value from the user β "
},
{
"code": null,
"e": 4716,
"s": 4678,
"text": "Using operator<<() and operator>>() :"
},
{
"code": null,
"e": 4726,
"s": 4716,
"text": "Example :"
},
{
"code": null,
"e": 4730,
"s": 4726,
"text": "C++"
},
{
"code": "// C++ program to demonstrate // operator>>() and <<operator()#include <ctime>#include <iostream>#include <random>using namespace std; // Driver codeint main(){ mt19937 mt; cout << \"enter a integer to begin\" << endl; // operator>>() is used to get // a seed value from the user cin >> mt; // <<operator() is used to print // the random integer cout << \"a random number \" << mt() << \" is generated\"; return 0;}",
"e": 5187,
"s": 4730,
"text": null
},
{
"code": null,
"e": 5252,
"s": 5187,
"text": "enter a integer to begin\na random number 3499211612 is generated"
},
{
"code": null,
"e": 5537,
"s": 5252,
"text": "Although the rand() function can be used in a small range, it is inefficient for generating real-world like random numbers. A careful person can observe the repetitions of the random numbers generated by rand() which is very risky. Whereas std::mt19937 has the following advantages β "
},
{
"code": null,
"e": 6044,
"s": 5537,
"text": "It has a very long period compared to the rand(). It will take a longer time. If an implementation of the Mersenne twister could generate 1,000,000,000 (one billion) pseudo-random numbers every second, a program that generated pseudo-random numbers would need to run about 1.3684 Γ 105,985 years to repeat the random sequence. So it is safe to assume that an observer will never guess the number.Many random number generators can be initiated simultaneously with different seed values. Here is an example β"
},
{
"code": null,
"e": 6441,
"s": 6044,
"text": "It has a very long period compared to the rand(). It will take a longer time. If an implementation of the Mersenne twister could generate 1,000,000,000 (one billion) pseudo-random numbers every second, a program that generated pseudo-random numbers would need to run about 1.3684 Γ 105,985 years to repeat the random sequence. So it is safe to assume that an observer will never guess the number."
},
{
"code": null,
"e": 6552,
"s": 6441,
"text": "Many random number generators can be initiated simultaneously with different seed values. Here is an example β"
},
{
"code": null,
"e": 6556,
"s": 6552,
"text": "C++"
},
{
"code": "// C++ program to demonstrate// above approach#include <iostream>#include <random>using namespace std; // Driver codeint main(){ mt19937 mt1(10000); mt19937 mt2(100000); cout << mt1() << endl; cout << mt2() << endl; return 0;}",
"e": 6791,
"s": 6556,
"text": null
},
{
"code": null,
"e": 6814,
"s": 6791,
"text": "2342776460\n1235064505\n"
},
{
"code": null,
"e": 6824,
"s": 6814,
"text": "cpp-class"
},
{
"code": null,
"e": 6828,
"s": 6824,
"text": "C++"
},
{
"code": null,
"e": 6832,
"s": 6828,
"text": "CPP"
},
{
"code": null,
"e": 6930,
"s": 6832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6954,
"s": 6930,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 6974,
"s": 6954,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 6999,
"s": 6974,
"text": "std::string class in C++"
},
{
"code": null,
"e": 7032,
"s": 6999,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 7076,
"s": 7032,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7121,
"s": 7076,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7169,
"s": 7121,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 7213,
"s": 7169,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7230,
"s": 7213,
"text": "std::find in C++"
}
] |
Permutation and Combination in Python
|
11 Apr, 2022
Python provides direct methods to find permutations and combinations of a sequence. These methods are present in itertools package.
First import itertools package to implement the permutations method in python. This method takes a list as an input and returns an object list of tuples that contain all permutations in a list form.
Python3
# A Python program to print all# permutations using library functionfrom itertools import permutations # Get all permutations of [1, 2, 3]perm = permutations([1, 2, 3]) # Print the obtained permutationsfor i in list(perm): print (i)
Output:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
It generates n! permutations if the length of the input sequence is n. If want to get permutations of length L then implement it in this way.
Python3
# A Python program to print all# permutations of given lengthfrom itertools import permutations # Get all permutations of length 2# and length 2perm = permutations([1, 2, 3], 2) # Print the obtained permutationsfor i in list(perm): print (i)
Output:
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
It generates nCr * r! permutations if the length of the input sequence is n and the input parameter is r.
This method takes a list and an input r as an input and return an object list of tuples which contain all possible combination of length r in a list form.
Python3
# A Python program to print all# combinations of given lengthfrom itertools import combinations # Get all combinations of [1, 2, 3]# and length 2comb = combinations([1, 2, 3], 2) # Print the obtained combinationsfor i in list(comb): print (i)
Output:
(1, 2)
(1, 3)
(2, 3)
1. Combinations are emitted in lexicographic sort order of input. So, if the input list is sorted, the combination tuples will be produced in sorted order.
Python3
# A Python program to print all# combinations of a given lengthfrom itertools import combinations # Get all combinations of [1, 2, 3]# and length 2comb = combinations([1, 2, 3], 2) # Print the obtained combinationsfor i in list(comb): print (i)
Output:
(1, 2)
(1, 3)
(2, 3)
2. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.
Python3
# A Python program to print all combinations# of given length with unsorted input.from itertools import combinations # Get all combinations of [2, 1, 3]# and length 2comb = combinations([2, 1, 3], 2) # Print the obtained combinationsfor i in list(comb): print (i)
Output:
(2, 1)
(2, 3)
(1, 3)
3. If we want to make a combination of the same element to the same element then we use combinations_with_replacement.
Python3
# A Python program to print all combinations# with an element-to-itself combination is# also includedfrom itertools import combinations_with_replacement # Get all combinations of [1, 2, 3] and length 2comb = combinations_with_replacement([1, 2, 3], 2) # Print the obtained combinationsfor i in list(comb): print (i)
Output:
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)
sandeepkumarkasera1
simmytarika5
permutation
Combinatorial
Python
permutation
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subsets with sum equal to X
Find the K-th Permutation Sequence of first N natural numbers
Find the Number of Permutations that satisfy the given condition in an array
Count Derangements (Permutation such that no element appears in its original position)
Stack Permutations (Check if an array is stack permutation of other)
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 184,
"s": 52,
"text": "Python provides direct methods to find permutations and combinations of a sequence. These methods are present in itertools package."
},
{
"code": null,
"e": 385,
"s": 184,
"text": "First import itertools package to implement the permutations method in python. This method takes a list as an input and returns an object list of tuples that contain all permutations in a list form. "
},
{
"code": null,
"e": 393,
"s": 385,
"text": "Python3"
},
{
"code": "# A Python program to print all# permutations using library functionfrom itertools import permutations # Get all permutations of [1, 2, 3]perm = permutations([1, 2, 3]) # Print the obtained permutationsfor i in list(perm): print (i)",
"e": 629,
"s": 393,
"text": null
},
{
"code": null,
"e": 638,
"s": 629,
"text": "Output: "
},
{
"code": null,
"e": 698,
"s": 638,
"text": "(1, 2, 3)\n(1, 3, 2)\n(2, 1, 3)\n(2, 3, 1)\n(3, 1, 2)\n(3, 2, 1)"
},
{
"code": null,
"e": 843,
"s": 698,
"text": "It generates n! permutations if the length of the input sequence is n. If want to get permutations of length L then implement it in this way. "
},
{
"code": null,
"e": 851,
"s": 843,
"text": "Python3"
},
{
"code": "# A Python program to print all# permutations of given lengthfrom itertools import permutations # Get all permutations of length 2# and length 2perm = permutations([1, 2, 3], 2) # Print the obtained permutationsfor i in list(perm): print (i)",
"e": 1096,
"s": 851,
"text": null
},
{
"code": null,
"e": 1105,
"s": 1096,
"text": "Output: "
},
{
"code": null,
"e": 1147,
"s": 1105,
"text": "(1, 2)\n(1, 3)\n(2, 1)\n(2, 3)\n(3, 1)\n(3, 2)"
},
{
"code": null,
"e": 1253,
"s": 1147,
"text": "It generates nCr * r! permutations if the length of the input sequence is n and the input parameter is r."
},
{
"code": null,
"e": 1410,
"s": 1253,
"text": "This method takes a list and an input r as an input and return an object list of tuples which contain all possible combination of length r in a list form. "
},
{
"code": null,
"e": 1418,
"s": 1410,
"text": "Python3"
},
{
"code": "# A Python program to print all# combinations of given lengthfrom itertools import combinations # Get all combinations of [1, 2, 3]# and length 2comb = combinations([1, 2, 3], 2) # Print the obtained combinationsfor i in list(comb): print (i)",
"e": 1664,
"s": 1418,
"text": null
},
{
"code": null,
"e": 1673,
"s": 1664,
"text": "Output: "
},
{
"code": null,
"e": 1694,
"s": 1673,
"text": "(1, 2)\n(1, 3)\n(2, 3)"
},
{
"code": null,
"e": 1854,
"s": 1696,
"text": "1. Combinations are emitted in lexicographic sort order of input. So, if the input list is sorted, the combination tuples will be produced in sorted order. "
},
{
"code": null,
"e": 1862,
"s": 1854,
"text": "Python3"
},
{
"code": "# A Python program to print all# combinations of a given lengthfrom itertools import combinations # Get all combinations of [1, 2, 3]# and length 2comb = combinations([1, 2, 3], 2) # Print the obtained combinationsfor i in list(comb): print (i)",
"e": 2110,
"s": 1862,
"text": null
},
{
"code": null,
"e": 2119,
"s": 2110,
"text": "Output: "
},
{
"code": null,
"e": 2140,
"s": 2119,
"text": "(1, 2)\n(1, 3)\n(2, 3)"
},
{
"code": null,
"e": 2312,
"s": 2142,
"text": "2. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination. "
},
{
"code": null,
"e": 2320,
"s": 2312,
"text": "Python3"
},
{
"code": "# A Python program to print all combinations# of given length with unsorted input.from itertools import combinations # Get all combinations of [2, 1, 3]# and length 2comb = combinations([2, 1, 3], 2) # Print the obtained combinationsfor i in list(comb): print (i)",
"e": 2587,
"s": 2320,
"text": null
},
{
"code": null,
"e": 2596,
"s": 2587,
"text": "Output: "
},
{
"code": null,
"e": 2617,
"s": 2596,
"text": "(2, 1)\n(2, 3)\n(1, 3)"
},
{
"code": null,
"e": 2740,
"s": 2619,
"text": "3. If we want to make a combination of the same element to the same element then we use combinations_with_replacement. "
},
{
"code": null,
"e": 2748,
"s": 2740,
"text": "Python3"
},
{
"code": "# A Python program to print all combinations# with an element-to-itself combination is# also includedfrom itertools import combinations_with_replacement # Get all combinations of [1, 2, 3] and length 2comb = combinations_with_replacement([1, 2, 3], 2) # Print the obtained combinationsfor i in list(comb): print (i)",
"e": 3067,
"s": 2748,
"text": null
},
{
"code": null,
"e": 3075,
"s": 3067,
"text": "Output:"
},
{
"code": null,
"e": 3118,
"s": 3075,
"text": "(1, 1)\n(1, 2)\n(1, 3)\n(2, 2)\n(2, 3)\n(3, 3) "
},
{
"code": null,
"e": 3140,
"s": 3120,
"text": "sandeepkumarkasera1"
},
{
"code": null,
"e": 3153,
"s": 3140,
"text": "simmytarika5"
},
{
"code": null,
"e": 3165,
"s": 3153,
"text": "permutation"
},
{
"code": null,
"e": 3179,
"s": 3165,
"text": "Combinatorial"
},
{
"code": null,
"e": 3186,
"s": 3179,
"text": "Python"
},
{
"code": null,
"e": 3198,
"s": 3186,
"text": "permutation"
},
{
"code": null,
"e": 3212,
"s": 3198,
"text": "Combinatorial"
},
{
"code": null,
"e": 3310,
"s": 3212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3347,
"s": 3310,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 3409,
"s": 3347,
"text": "Find the K-th Permutation Sequence of first N natural numbers"
},
{
"code": null,
"e": 3486,
"s": 3409,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 3573,
"s": 3486,
"text": "Count Derangements (Permutation such that no element appears in its original position)"
},
{
"code": null,
"e": 3642,
"s": 3573,
"text": "Stack Permutations (Check if an array is stack permutation of other)"
},
{
"code": null,
"e": 3670,
"s": 3642,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3720,
"s": 3670,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3742,
"s": 3720,
"text": "Python map() function"
}
] |
How to add a border to the top and bottom of an Android View?
|
This example demonstrates how to add a border to the top and bottom of an Android View .
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/drawable/border_top_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<stroke
android:width="2dp"
android:color="#e10606" />
<solid android:color="#9bce64" />
</shape>
</item>
<item android:bottom="2dp" android:top="2dp">
<shape android:shape="rectangle">
<stroke android:width="2dp" android:color="#9bce64" />
</shape>
</item>
</layer-list>
Step 3 β Add the following code to res/layout/top_bottom_border_in_android_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Adding Border in Top and Bottom of an Android View" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="@drawable/border_top_bottom"
android:padding="30dp"
android:text="Top Bottom Border in TextView"
android:textColor="#000000"
android:textSize="18sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="@drawable/border_top_bottom"
android:text="Top Bottom Border in Button" />
</LinearLayout>
Step 4 β Add the following code to res/layout/strings.xml
<resources>
<string name="app_name">Adding Border to an Android View</string>
</resources>
Step 5 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 6 β Add the following code to src/MainActivity.java
package com.example.sample1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.top_bottom_border_in_android_view);
}
}
Step 7 β Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.sample1">
<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>
<dist:module dist:instant="true" />
</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 Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code.
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "This example demonstrates how to add a border to the top and bottom of an Android View ."
},
{
"code": null,
"e": 1281,
"s": 1151,
"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": 1352,
"s": 1281,
"text": "Step 2 β Add the following code to res/drawable/border_top_bottom.xml"
},
{
"code": null,
"e": 1863,
"s": 1352,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <item>\n <shape android:shape=\"rectangle\">\n <stroke\n android:width=\"2dp\"\n android:color=\"#e10606\" />\n <solid android:color=\"#9bce64\" />\n </shape>\n </item>\n <item android:bottom=\"2dp\" android:top=\"2dp\">\n <shape android:shape=\"rectangle\">\n <stroke android:width=\"2dp\" android:color=\"#9bce64\" />\n </shape>\n </item>\n</layer-list>"
},
{
"code": null,
"e": 1948,
"s": 1863,
"text": "Step 3 β Add the following code to res/layout/top_bottom_border_in_android_view.xml"
},
{
"code": null,
"e": 2972,
"s": 1948,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Adding Border in Top and Bottom of an Android View\" />\n <TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"16dp\"\n android:background=\"@drawable/border_top_bottom\"\n android:padding=\"30dp\"\n android:text=\"Top Bottom Border in TextView\"\n android:textColor=\"#000000\"\n android:textSize=\"18sp\" />\n <Button\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"16dp\"\n android:background=\"@drawable/border_top_bottom\"\n android:text=\"Top Bottom Border in Button\" />\n</LinearLayout>"
},
{
"code": null,
"e": 3031,
"s": 2972,
"text": "Step 4 β Add the following code to res/layout/strings.xml"
},
{
"code": null,
"e": 3125,
"s": 3031,
"text": "<resources>\n <string name=\"app_name\">Adding Border to an Android View</string>\n</resources>"
},
{
"code": null,
"e": 3191,
"s": 3125,
"text": "Step 5 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3953,
"s": 3191,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</androidx.constraintlayout.widget.ConstraintLayout>"
},
{
"code": null,
"e": 4011,
"s": 3953,
"text": "Step 6 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4353,
"s": 4011,
"text": "package com.example.sample1;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.top_bottom_border_in_android_view);\n }\n}"
},
{
"code": null,
"e": 4419,
"s": 4353,
"text": "Step 7 β Add the following code to Manifests/AndroidManifest.xml"
},
{
"code": null,
"e": 5196,
"s": 4419,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:dist=\"http://schemas.android.com/apk/distribution\"\n package=\"com.example.sample1\">\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 <dist:module dist:instant=\"true\" />\n</manifest>"
},
{
"code": null,
"e": 5543,
"s": 5196,
"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 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": 5584,
"s": 5543,
"text": "Click here to download the project code."
}
] |
Create A Synthetic Image Dataset β The βWhatβ, The βWhyβ and The βHowβ | by Viraf | Towards Data Science
|
It is quite a known fact that the quality and quantity of dataset used to train your model will have a direct effect on the modelβs performance. Availability of an extensive, versatile dataset could seal the deal, and you could jump to the next step of your Machine Learning / Deep Learning pipeline. But often you might end up in a situation where the dataset you need is just not readily available. Or the data you have is not enough to train a heavy duty model. Now what do you do?
There are so many resources out there that can help you create a new custom dataset of any object class you need. But if I had to describe the process of building a dataset in one word, Iβd call it βcumbersomeβ and βtime-consumingβ and βfrustratingβ and β I know I used more than one word, but you get the point!
Especially when it comes to drawing segmentation masks, I just canβt be bothered to annotate any more than a few images! Donβt get me wrong, I know dataset creation is a very very very important step, but isnβt there a way out?
Data augmentation is a great way to increase the variety of the dataset that your model sees, but again, there is a limit to how much it can help. How about we take it a step further?
Creating any kind of data (image, audio, text, etc.) βartificiallyβ or βprogramaticallyβ results in what we call a synthetic dataset. This data is not collected naturally or normally and labelled manually, so is it safe to use it to train your model? Will it give good results?
While there are many papers claiming that carefully created synthetic data can give a performance at par with natural data, I recommend having a healthy mixture of the two. A well designed synthetic dataset can take the concept of data augmentations to the next level, and gives the model an even larger variety of training data. The more the better right?
There are several ways out there to create synthetic image datasets, and in this tutorial, letβs look at one of the most basic method β Image Composition. We will generate new images by composing the object image as a foreground on multiple background images.
In this tutorial, I am going to create synthetic images for the output class βdogβ. In reality, there are many existing datasets online that include the dog class (for example, COCO), but whatβs the harm in creating more pictures of these cute gifts of nature. :P
Have a look at the import statements below. Install any module you might not already have.
import osimport numpy as npimport skimage.io as ioimport skimage.transform as transformimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectangle%matplotlib inline
There are 2 ways to go about this β
(A) Create your own dataset
First, letβs take an image of a dog available on the internet. There are several websites out there which allow you to use the images for free like β pexels, flickr, unsplash β take your pick. Iβm going to use the one below.
Next, you will have to put in a little manual effort to separate the dog from the background. Yeah, Iβm sorry β there are no free meals. But eventually this is definitely lesser effort than creating an entire dataset, I promise.
A few tools that I know of to get this job done are Photoshop (paid) or GIMP (free). Or you could even use the ever-dependable Microsoft Paint! The final output looks like the one below.
Read the image. Next, cut out the foreground layer from this image and set the remaining pixels to zero. An alternative to coding this step is to add a black background with the tool you used (GIMP/Paint/Photoshop) while segmenting the image itself. But nonetheless, hereβs how to extract the foreground object in python β simple thresholding of pixels.
# Read the imageI = io.imread('./dogSeg.jpg')/255.0# Cut out the foreground layerforeground = I.copy()foreground[foreground>=0.9]=0 # Setting surrounding pixels to zeroplt.axis('off')plt.imshow(foreground)plt.show()
(B) Use an existing dataset
If you donβt want to start from scratch, another option is to make use of the images from an already available dataset.
I am going to use the COCO dataset here to demonstrate. Since COCO already has the object category βdogβ, it will be easy to retrieve the image and its mask. The COCO dataset has 4385 (train) and 177 (val) images for the βdogβ category.
You can refer to the entire code for this process in my GitHub repository for this tutorial. I will not be going over the code for this step in this post.
If you are interested in manipulating the COCO image dataset and creating a data generator to train your model for Image Segmentation, I have an extensive tutorial here.
Letβs play a bit with the dog (pun intended). I have used random rotations, random zoom, random translations and random horizontal flips in my code, but you can use something else too.
The output of the code is shown below. See how different it looks from the original image!
After applying all these changes to the foreground, letβs extract the segmentation mask from the image.
Now you need a new background image. Use the free websites I mentioned earlier to get a wide variety of backgrounds. You can choose any image in the world (see how I sent my dog to the moon in the display picture of this article), but I recommend keeping it as realistic as possible.
I am going to use these 4 images as my backgrounds for this tutorial.
Letβs select a background at random.
# Random selection of background from the backgrounds folderbackground_fileName = np.random.choice(os.listdir("./backgrounds/"))background = io.imread('./backgrounds/'+background_fileName)/255.0
Itβs time to add your dog image to the background!
This function gives the following output. Now, I know itβs not perfect, but itβs quite good!
For object localization tasks, you can also get the box coordinates easily from the new segmentation mask we developed.
And on performing these functions in a loop with all the backgrounds, we get a nice set of images!
In this tutorial, I used 1 foreground with 4 backgrounds. If you use multiple foregrounds in random with multiple backgrounds, you can create many, many images! Maybe you could merge two or more foregrounds on a background as well. Get creative β play with sizes, angles, foregrounds, and backgrounds to build an awesome synthetic dataset according to your needs. There are a lot of design considerations here as well, but with a little effort you can do much more and create more accurate datasets.
Finally, you can find the entire code for this tutorial in my GitHub repository.
As a next step on this topic, check out this nice tutorial on creating synthetic image datasets with Unity 3D.
Well, thatβs it for now β thank you for reading this far into the article. I hope something good came out of it. Any thoughts, questions, comments? Let me know in the responses below!
If you are interested in image datasets for semantic segmentation, check out my post below:
towardsdatascience.com
Or do you want to be rich overnight using ML in stocks? This article is (NOT) for you!
towardsdatascience.com
Can an ML model literally read the stock price charts?
|
[
{
"code": null,
"e": 657,
"s": 172,
"text": "It is quite a known fact that the quality and quantity of dataset used to train your model will have a direct effect on the modelβs performance. Availability of an extensive, versatile dataset could seal the deal, and you could jump to the next step of your Machine Learning / Deep Learning pipeline. But often you might end up in a situation where the dataset you need is just not readily available. Or the data you have is not enough to train a heavy duty model. Now what do you do?"
},
{
"code": null,
"e": 970,
"s": 657,
"text": "There are so many resources out there that can help you create a new custom dataset of any object class you need. But if I had to describe the process of building a dataset in one word, Iβd call it βcumbersomeβ and βtime-consumingβ and βfrustratingβ and β I know I used more than one word, but you get the point!"
},
{
"code": null,
"e": 1198,
"s": 970,
"text": "Especially when it comes to drawing segmentation masks, I just canβt be bothered to annotate any more than a few images! Donβt get me wrong, I know dataset creation is a very very very important step, but isnβt there a way out?"
},
{
"code": null,
"e": 1382,
"s": 1198,
"text": "Data augmentation is a great way to increase the variety of the dataset that your model sees, but again, there is a limit to how much it can help. How about we take it a step further?"
},
{
"code": null,
"e": 1660,
"s": 1382,
"text": "Creating any kind of data (image, audio, text, etc.) βartificiallyβ or βprogramaticallyβ results in what we call a synthetic dataset. This data is not collected naturally or normally and labelled manually, so is it safe to use it to train your model? Will it give good results?"
},
{
"code": null,
"e": 2017,
"s": 1660,
"text": "While there are many papers claiming that carefully created synthetic data can give a performance at par with natural data, I recommend having a healthy mixture of the two. A well designed synthetic dataset can take the concept of data augmentations to the next level, and gives the model an even larger variety of training data. The more the better right?"
},
{
"code": null,
"e": 2277,
"s": 2017,
"text": "There are several ways out there to create synthetic image datasets, and in this tutorial, letβs look at one of the most basic method β Image Composition. We will generate new images by composing the object image as a foreground on multiple background images."
},
{
"code": null,
"e": 2541,
"s": 2277,
"text": "In this tutorial, I am going to create synthetic images for the output class βdogβ. In reality, there are many existing datasets online that include the dog class (for example, COCO), but whatβs the harm in creating more pictures of these cute gifts of nature. :P"
},
{
"code": null,
"e": 2632,
"s": 2541,
"text": "Have a look at the import statements below. Install any module you might not already have."
},
{
"code": null,
"e": 2809,
"s": 2632,
"text": "import osimport numpy as npimport skimage.io as ioimport skimage.transform as transformimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectangle%matplotlib inline"
},
{
"code": null,
"e": 2845,
"s": 2809,
"text": "There are 2 ways to go about this β"
},
{
"code": null,
"e": 2873,
"s": 2845,
"text": "(A) Create your own dataset"
},
{
"code": null,
"e": 3098,
"s": 2873,
"text": "First, letβs take an image of a dog available on the internet. There are several websites out there which allow you to use the images for free like β pexels, flickr, unsplash β take your pick. Iβm going to use the one below."
},
{
"code": null,
"e": 3327,
"s": 3098,
"text": "Next, you will have to put in a little manual effort to separate the dog from the background. Yeah, Iβm sorry β there are no free meals. But eventually this is definitely lesser effort than creating an entire dataset, I promise."
},
{
"code": null,
"e": 3514,
"s": 3327,
"text": "A few tools that I know of to get this job done are Photoshop (paid) or GIMP (free). Or you could even use the ever-dependable Microsoft Paint! The final output looks like the one below."
},
{
"code": null,
"e": 3868,
"s": 3514,
"text": "Read the image. Next, cut out the foreground layer from this image and set the remaining pixels to zero. An alternative to coding this step is to add a black background with the tool you used (GIMP/Paint/Photoshop) while segmenting the image itself. But nonetheless, hereβs how to extract the foreground object in python β simple thresholding of pixels."
},
{
"code": null,
"e": 4084,
"s": 3868,
"text": "# Read the imageI = io.imread('./dogSeg.jpg')/255.0# Cut out the foreground layerforeground = I.copy()foreground[foreground>=0.9]=0 # Setting surrounding pixels to zeroplt.axis('off')plt.imshow(foreground)plt.show()"
},
{
"code": null,
"e": 4112,
"s": 4084,
"text": "(B) Use an existing dataset"
},
{
"code": null,
"e": 4232,
"s": 4112,
"text": "If you donβt want to start from scratch, another option is to make use of the images from an already available dataset."
},
{
"code": null,
"e": 4469,
"s": 4232,
"text": "I am going to use the COCO dataset here to demonstrate. Since COCO already has the object category βdogβ, it will be easy to retrieve the image and its mask. The COCO dataset has 4385 (train) and 177 (val) images for the βdogβ category."
},
{
"code": null,
"e": 4624,
"s": 4469,
"text": "You can refer to the entire code for this process in my GitHub repository for this tutorial. I will not be going over the code for this step in this post."
},
{
"code": null,
"e": 4794,
"s": 4624,
"text": "If you are interested in manipulating the COCO image dataset and creating a data generator to train your model for Image Segmentation, I have an extensive tutorial here."
},
{
"code": null,
"e": 4979,
"s": 4794,
"text": "Letβs play a bit with the dog (pun intended). I have used random rotations, random zoom, random translations and random horizontal flips in my code, but you can use something else too."
},
{
"code": null,
"e": 5070,
"s": 4979,
"text": "The output of the code is shown below. See how different it looks from the original image!"
},
{
"code": null,
"e": 5174,
"s": 5070,
"text": "After applying all these changes to the foreground, letβs extract the segmentation mask from the image."
},
{
"code": null,
"e": 5458,
"s": 5174,
"text": "Now you need a new background image. Use the free websites I mentioned earlier to get a wide variety of backgrounds. You can choose any image in the world (see how I sent my dog to the moon in the display picture of this article), but I recommend keeping it as realistic as possible."
},
{
"code": null,
"e": 5528,
"s": 5458,
"text": "I am going to use these 4 images as my backgrounds for this tutorial."
},
{
"code": null,
"e": 5565,
"s": 5528,
"text": "Letβs select a background at random."
},
{
"code": null,
"e": 5760,
"s": 5565,
"text": "# Random selection of background from the backgrounds folderbackground_fileName = np.random.choice(os.listdir(\"./backgrounds/\"))background = io.imread('./backgrounds/'+background_fileName)/255.0"
},
{
"code": null,
"e": 5811,
"s": 5760,
"text": "Itβs time to add your dog image to the background!"
},
{
"code": null,
"e": 5904,
"s": 5811,
"text": "This function gives the following output. Now, I know itβs not perfect, but itβs quite good!"
},
{
"code": null,
"e": 6024,
"s": 5904,
"text": "For object localization tasks, you can also get the box coordinates easily from the new segmentation mask we developed."
},
{
"code": null,
"e": 6123,
"s": 6024,
"text": "And on performing these functions in a loop with all the backgrounds, we get a nice set of images!"
},
{
"code": null,
"e": 6623,
"s": 6123,
"text": "In this tutorial, I used 1 foreground with 4 backgrounds. If you use multiple foregrounds in random with multiple backgrounds, you can create many, many images! Maybe you could merge two or more foregrounds on a background as well. Get creative β play with sizes, angles, foregrounds, and backgrounds to build an awesome synthetic dataset according to your needs. There are a lot of design considerations here as well, but with a little effort you can do much more and create more accurate datasets."
},
{
"code": null,
"e": 6704,
"s": 6623,
"text": "Finally, you can find the entire code for this tutorial in my GitHub repository."
},
{
"code": null,
"e": 6815,
"s": 6704,
"text": "As a next step on this topic, check out this nice tutorial on creating synthetic image datasets with Unity 3D."
},
{
"code": null,
"e": 6999,
"s": 6815,
"text": "Well, thatβs it for now β thank you for reading this far into the article. I hope something good came out of it. Any thoughts, questions, comments? Let me know in the responses below!"
},
{
"code": null,
"e": 7091,
"s": 6999,
"text": "If you are interested in image datasets for semantic segmentation, check out my post below:"
},
{
"code": null,
"e": 7114,
"s": 7091,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7201,
"s": 7114,
"text": "Or do you want to be rich overnight using ML in stocks? This article is (NOT) for you!"
},
{
"code": null,
"e": 7224,
"s": 7201,
"text": "towardsdatascience.com"
}
] |
How to add a citation in a plot created by using ggplot2 in R?
|
A footnote is generally used to give references to a document, text or image and it is called citation. It helps the reader or viewer to check out the original source using the new text or image is generated. If we want to give citation to a plot in R using ggplot2 package then we can add labs that has caption option to add the footnotes.
Consider the below data frame β
Live Demo
> set.seed(1)
> x<-rnorm(10,1.5)
> y<-rnorm(10,2.5)
> df<-data.frame(x,y)
> df
x y
1 0.8735462 4.0117812
2 1.6836433 2.8898432
3 0.6643714 1.8787594
4 3.0952808 0.2853001
5 1.8295078 3.6249309
6 0.6795316 2.4550664
7 1.9874291 2.4838097
8 2.2383247 3.4438362
9 2.0757814 3.3212212
10 1.1946116 3.0939013
Loading ggplot2 package and creating a scatterplot between x and y β
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Creating the plot with footnote β
> ggplot(df,aes(x,y))+geom_point()+labs(caption="Correlation Analysis")
|
[
{
"code": null,
"e": 1403,
"s": 1062,
"text": "A footnote is generally used to give references to a document, text or image and it is called citation. It helps the reader or viewer to check out the original source using the new text or image is generated. If we want to give citation to a plot in R using ggplot2 package then we can add labs that has caption option to add the footnotes."
},
{
"code": null,
"e": 1435,
"s": 1403,
"text": "Consider the below data frame β"
},
{
"code": null,
"e": 1446,
"s": 1435,
"text": " Live Demo"
},
{
"code": null,
"e": 1525,
"s": 1446,
"text": "> set.seed(1)\n> x<-rnorm(10,1.5)\n> y<-rnorm(10,2.5)\n> df<-data.frame(x,y)\n> df"
},
{
"code": null,
"e": 1762,
"s": 1525,
"text": " x y\n1 0.8735462 4.0117812\n2 1.6836433 2.8898432\n3 0.6643714 1.8787594\n4 3.0952808 0.2853001\n5 1.8295078 3.6249309\n6 0.6795316 2.4550664\n7 1.9874291 2.4838097\n8 2.2383247 3.4438362\n9 2.0757814 3.3212212\n10 1.1946116 3.0939013"
},
{
"code": null,
"e": 1831,
"s": 1762,
"text": "Loading ggplot2 package and creating a scatterplot between x and y β"
},
{
"code": null,
"e": 1885,
"s": 1831,
"text": "> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_point()"
},
{
"code": null,
"e": 1919,
"s": 1885,
"text": "Creating the plot with footnote β"
},
{
"code": null,
"e": 1991,
"s": 1919,
"text": "> ggplot(df,aes(x,y))+geom_point()+labs(caption=\"Correlation Analysis\")"
}
] |
A Standalone Application to Scan Barcode using Webcam | by Gautam Kumar | Towards Data Science
|
When you visit any shopping mall or stores, you must have seen a barcode detector machine (see figure 1, image source flickr) which read barcode of the product you purchased and calculate the cost. Finally, you get a receipt of shopping having items you have purchased and cost of respective items. Use of barcode scanner in shopping malls reduces paperwork and digitize shopping by a great extent. However, it still requires human effort.
Another problem with this is, it comes at a high cost. changes and durability is also an issue with this barcode scanner machine. Therefore, it became necessary to develop such a system which can automate the process of scanning the products and comes at low cost with low maintenance requirement.
In this article, a barcode scanner using python has been developed which can read barcode of the product using webcam, decode the cost of item which is encrypted in barcode and calculate the price of the product, finally at the end of shopping you will get number of items you have purchased, date of purchasing, name of items purchased and the corresponding cost. Developed system is found to be cost effective, durable, easy to use, fully automated the billing process i.e donβt require human effort to scan barcode.
Now a days, there are many standard libraries available in python to create barcode. I have used pyBarcode. It can provide EAN-8, EAN-13, EAN-14, UPC-A, JAN, ISBN-10, ISBN-13, ISSN, Code 39, Code 128, PZN types of standard barcode. To install pyBarcode use pip as
pip install pyBarcode
Once you install pyBarcode, run following four lines of code to create barcode image. This will save barcode image file in .svg format. However, you can also save it as .png with minor changes in the following code which is taken from here.
>>>import barcode>>>EAN = barcode.get_barcode_class('ean13')>>>ean = EAN(u'5901234123457')>>>fullname = ean.save('ean13_barcode')
Above code will save barcode in European Article Number (EAN) standard. You can change standard as per for choice. Generated barcode using python scripts is shown in Figure 2.
Alternatively, you can download any software freely available on the internet to generate barcode. I used tool downloaded from this website. You just need to set data and text above and below (optional) barcode. You can also set the width and height of the barcode image and extract it as .png or store in excel. In my application, i used CODE 128 standard and extracted image as .png. The barcode generated using software tool is look like shown in figure 3.
Similarly, I generated barcode for four products (2 books, one calculator and one computer mouse), took the print out of those barcodes and stick them to products. After these steps, my four products look like, as shown in figure 4.
So, in this way you can also create your own bar codes of products for your shopping store.
Here, i have developed a python application to read barcode that i have created and decode data from that using webcam. The script initializes live video stream and extracts each frame from the video. It finds edges by blurring frame. Bilateral filter or Gaussian filter can be used for this purpose. Then an adaptive threshold is used to obtained processed image. After the morphological operation, a contour is drawn around the barcode. All these steps are taken care of by decode object of pyzbar. Therefore, before executing program make sure that you have installed pyzbar which can be installed using pip as
pip install pyzbar
For rest of the process, please download complete code from GitHub repository and follow steps as mentioned in readme.
The data (cost of the product) encrypted in the barcode is a combination of product name and its cost. For example, data of barcode for the item calculator is set as C4 where βCβ is considered the item ID (Calculator) and β4β as the item cost in $. For each scanned item, application records purchase date, purchased item ID and item cost. Once we press button βeβ to exit from the barcode reading process, the application adds the cost of every purchased item and display the final cost of shopping. The demo video of the complete process is shown here.
This application can be considered as cost effective, as cost of webcam is quite very low compared to cost of bar code reader machine.It is very easy to handle and also donβt require human effort as webcam can be fixed at certain place and customers only need to keep items to be purchased facing barcodes towards webcam.Webcam is more durable and even if some problem occurs, it is easy to fix compared to barcode reader machines.This application can be used in shopping malls and small stores to automate billing process. It can also be used to develop similar application like in library, a book can be assigned to student using barcode scanning system.
This application can be considered as cost effective, as cost of webcam is quite very low compared to cost of bar code reader machine.
It is very easy to handle and also donβt require human effort as webcam can be fixed at certain place and customers only need to keep items to be purchased facing barcodes towards webcam.
Webcam is more durable and even if some problem occurs, it is easy to fix compared to barcode reader machines.
This application can be used in shopping malls and small stores to automate billing process. It can also be used to develop similar application like in library, a book can be assigned to student using barcode scanning system.
If barcode is small in size or distance between webcam and barcode is more then system fails to scan barcode.
If barcode is small in size or distance between webcam and barcode is more then system fails to scan barcode.
This application can also be used to read QR code with miner changes in the code. You can download code and create your own barcode with setting cost of the product as per your requirement. Finally, you will have a complete application for automated billing process for your shop/shopping store. Thanks to Jayeeta Chakraborty, who helped me to develop this project. Hope this application may help researchers and developer to develop custom barcode scanner.
|
[
{
"code": null,
"e": 612,
"s": 172,
"text": "When you visit any shopping mall or stores, you must have seen a barcode detector machine (see figure 1, image source flickr) which read barcode of the product you purchased and calculate the cost. Finally, you get a receipt of shopping having items you have purchased and cost of respective items. Use of barcode scanner in shopping malls reduces paperwork and digitize shopping by a great extent. However, it still requires human effort."
},
{
"code": null,
"e": 910,
"s": 612,
"text": "Another problem with this is, it comes at a high cost. changes and durability is also an issue with this barcode scanner machine. Therefore, it became necessary to develop such a system which can automate the process of scanning the products and comes at low cost with low maintenance requirement."
},
{
"code": null,
"e": 1429,
"s": 910,
"text": "In this article, a barcode scanner using python has been developed which can read barcode of the product using webcam, decode the cost of item which is encrypted in barcode and calculate the price of the product, finally at the end of shopping you will get number of items you have purchased, date of purchasing, name of items purchased and the corresponding cost. Developed system is found to be cost effective, durable, easy to use, fully automated the billing process i.e donβt require human effort to scan barcode."
},
{
"code": null,
"e": 1693,
"s": 1429,
"text": "Now a days, there are many standard libraries available in python to create barcode. I have used pyBarcode. It can provide EAN-8, EAN-13, EAN-14, UPC-A, JAN, ISBN-10, ISBN-13, ISSN, Code 39, Code 128, PZN types of standard barcode. To install pyBarcode use pip as"
},
{
"code": null,
"e": 1715,
"s": 1693,
"text": "pip install pyBarcode"
},
{
"code": null,
"e": 1956,
"s": 1715,
"text": "Once you install pyBarcode, run following four lines of code to create barcode image. This will save barcode image file in .svg format. However, you can also save it as .png with minor changes in the following code which is taken from here."
},
{
"code": null,
"e": 2086,
"s": 1956,
"text": ">>>import barcode>>>EAN = barcode.get_barcode_class('ean13')>>>ean = EAN(u'5901234123457')>>>fullname = ean.save('ean13_barcode')"
},
{
"code": null,
"e": 2262,
"s": 2086,
"text": "Above code will save barcode in European Article Number (EAN) standard. You can change standard as per for choice. Generated barcode using python scripts is shown in Figure 2."
},
{
"code": null,
"e": 2722,
"s": 2262,
"text": "Alternatively, you can download any software freely available on the internet to generate barcode. I used tool downloaded from this website. You just need to set data and text above and below (optional) barcode. You can also set the width and height of the barcode image and extract it as .png or store in excel. In my application, i used CODE 128 standard and extracted image as .png. The barcode generated using software tool is look like shown in figure 3."
},
{
"code": null,
"e": 2955,
"s": 2722,
"text": "Similarly, I generated barcode for four products (2 books, one calculator and one computer mouse), took the print out of those barcodes and stick them to products. After these steps, my four products look like, as shown in figure 4."
},
{
"code": null,
"e": 3047,
"s": 2955,
"text": "So, in this way you can also create your own bar codes of products for your shopping store."
},
{
"code": null,
"e": 3661,
"s": 3047,
"text": "Here, i have developed a python application to read barcode that i have created and decode data from that using webcam. The script initializes live video stream and extracts each frame from the video. It finds edges by blurring frame. Bilateral filter or Gaussian filter can be used for this purpose. Then an adaptive threshold is used to obtained processed image. After the morphological operation, a contour is drawn around the barcode. All these steps are taken care of by decode object of pyzbar. Therefore, before executing program make sure that you have installed pyzbar which can be installed using pip as"
},
{
"code": null,
"e": 3680,
"s": 3661,
"text": "pip install pyzbar"
},
{
"code": null,
"e": 3799,
"s": 3680,
"text": "For rest of the process, please download complete code from GitHub repository and follow steps as mentioned in readme."
},
{
"code": null,
"e": 4354,
"s": 3799,
"text": "The data (cost of the product) encrypted in the barcode is a combination of product name and its cost. For example, data of barcode for the item calculator is set as C4 where βCβ is considered the item ID (Calculator) and β4β as the item cost in $. For each scanned item, application records purchase date, purchased item ID and item cost. Once we press button βeβ to exit from the barcode reading process, the application adds the cost of every purchased item and display the final cost of shopping. The demo video of the complete process is shown here."
},
{
"code": null,
"e": 5011,
"s": 4354,
"text": "This application can be considered as cost effective, as cost of webcam is quite very low compared to cost of bar code reader machine.It is very easy to handle and also donβt require human effort as webcam can be fixed at certain place and customers only need to keep items to be purchased facing barcodes towards webcam.Webcam is more durable and even if some problem occurs, it is easy to fix compared to barcode reader machines.This application can be used in shopping malls and small stores to automate billing process. It can also be used to develop similar application like in library, a book can be assigned to student using barcode scanning system."
},
{
"code": null,
"e": 5146,
"s": 5011,
"text": "This application can be considered as cost effective, as cost of webcam is quite very low compared to cost of bar code reader machine."
},
{
"code": null,
"e": 5334,
"s": 5146,
"text": "It is very easy to handle and also donβt require human effort as webcam can be fixed at certain place and customers only need to keep items to be purchased facing barcodes towards webcam."
},
{
"code": null,
"e": 5445,
"s": 5334,
"text": "Webcam is more durable and even if some problem occurs, it is easy to fix compared to barcode reader machines."
},
{
"code": null,
"e": 5671,
"s": 5445,
"text": "This application can be used in shopping malls and small stores to automate billing process. It can also be used to develop similar application like in library, a book can be assigned to student using barcode scanning system."
},
{
"code": null,
"e": 5781,
"s": 5671,
"text": "If barcode is small in size or distance between webcam and barcode is more then system fails to scan barcode."
},
{
"code": null,
"e": 5891,
"s": 5781,
"text": "If barcode is small in size or distance between webcam and barcode is more then system fails to scan barcode."
}
] |
Global and Local Variables in Python?
|
There are two types of variables: global variables and local variables.
The scope of global variables is the entire program whereas the scope of local variable is limited to the function where it is defined.
def func():
x = "Python"
print(x)
print(s)
s = "Tutorialspoint"
print(s)
func()
print(x)
In above program- x is a local variable whereas s is a global variable, we can access the local variable only within the function it is defined (func() above) and trying to call local variable outside its scope(func()) will through an Error. However, we can call global variable anywhere in the program including functions (func()) defined in the program.
Local variables can only be reached within their scope(like func() above).
Like in below program- there are two local variables β x and y.
def sum(x,y):
sum = x + y
return sum
print(sum(5, 10))
15
The variables x and y will only work/used inside the function sum() and they donβt exist outside of the function.
So trying to use local variable outside their scope, might through NameError. So obviously below line will not work.
print(x)
A global variable can be used anywhere in the program as its scope is the entire program.
Letβs understand global variable with a very simple example -
z = 25
def func():
global z
print(z)
z=20
func()
print(z)
25
20
A calling func(), the global variable value is changed for the entire program.
Below example shows a combination of local and global variables and function parameters -
def func(x, y):
global a
a = 45
x,y = y,x
b = 33
b = 17
c = 100
print(a,b,x,y)
a,b,x,y = 3,15,3,4
func(9,81)
print (a,b,x,y)
45 17 81 9
45 15 3 4
|
[
{
"code": null,
"e": 1134,
"s": 1062,
"text": "There are two types of variables: global variables and local variables."
},
{
"code": null,
"e": 1270,
"s": 1134,
"text": "The scope of global variables is the entire program whereas the scope of local variable is limited to the function where it is defined."
},
{
"code": null,
"e": 1359,
"s": 1270,
"text": "def func():\nx = \"Python\"\nprint(x)\nprint(s)\ns = \"Tutorialspoint\"\nprint(s)\nfunc()\nprint(x)"
},
{
"code": null,
"e": 1715,
"s": 1359,
"text": "In above program- x is a local variable whereas s is a global variable, we can access the local variable only within the function it is defined (func() above) and trying to call local variable outside its scope(func()) will through an Error. However, we can call global variable anywhere in the program including functions (func()) defined in the program."
},
{
"code": null,
"e": 1790,
"s": 1715,
"text": "Local variables can only be reached within their scope(like func() above)."
},
{
"code": null,
"e": 1854,
"s": 1790,
"text": "Like in below program- there are two local variables β x and y."
},
{
"code": null,
"e": 1909,
"s": 1854,
"text": "def sum(x,y):\nsum = x + y\nreturn sum\nprint(sum(5, 10))"
},
{
"code": null,
"e": 1912,
"s": 1909,
"text": "15"
},
{
"code": null,
"e": 2143,
"s": 1912,
"text": "The variables x and y will only work/used inside the function sum() and they donβt exist outside of the function.\nSo trying to use local variable outside their scope, might through NameError. So obviously below line will not work."
},
{
"code": null,
"e": 2152,
"s": 2143,
"text": "print(x)"
},
{
"code": null,
"e": 2242,
"s": 2152,
"text": "A global variable can be used anywhere in the program as its scope is the entire program."
},
{
"code": null,
"e": 2304,
"s": 2242,
"text": "Letβs understand global variable with a very simple example -"
},
{
"code": null,
"e": 2362,
"s": 2304,
"text": "z = 25\ndef func():\nglobal z\nprint(z)\nz=20\nfunc()\nprint(z)"
},
{
"code": null,
"e": 2368,
"s": 2362,
"text": "25\n20"
},
{
"code": null,
"e": 2447,
"s": 2368,
"text": "A calling func(), the global variable value is changed for the entire program."
},
{
"code": null,
"e": 2537,
"s": 2447,
"text": "Below example shows a combination of local and global variables and function parameters -"
},
{
"code": null,
"e": 2662,
"s": 2537,
"text": "def func(x, y):\nglobal a\na = 45\nx,y = y,x\nb = 33\nb = 17\nc = 100\nprint(a,b,x,y)\na,b,x,y = 3,15,3,4\nfunc(9,81)\nprint (a,b,x,y)"
},
{
"code": null,
"e": 2683,
"s": 2662,
"text": "45 17 81 9\n45 15 3 4"
}
] |
Image Thumbnail with Bootstrap
|
To add a thumbnail to the image, use the .img-thumbnail Bootstrap class.
You can try to run the following code to add a thumbnail to images
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Images</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<p>Styling images with Bootstrap</p>
<h1>Original Image</h1>
<img src = "https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg">
<h1>Thumbnail Image</h1>
<img src = "https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg" class = "img-thumbnail">
</body>
</html>
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To add a thumbnail to the image, use the .img-thumbnail Bootstrap class."
},
{
"code": null,
"e": 1202,
"s": 1135,
"text": "You can try to run the following code to add a thumbnail to images"
},
{
"code": null,
"e": 1212,
"s": 1202,
"text": "Live Demo"
},
{
"code": null,
"e": 1841,
"s": 1212,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Images</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>Styling images with Bootstrap</p>\n <h1>Original Image</h1>\n <img src = \"https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg\">\n <h1>Thumbnail Image</h1>\n <img src = \"https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg\" class = \"img-thumbnail\">\n </body>\n</html>"
}
] |
Java - String replace() Method
|
This method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Here is the syntax of this method β
public String replace(char oldChar, char newChar)
Here is the detail of parameters β
oldChar β the old character.
oldChar β the old character.
newChar β the new character.
newChar β the new character.
It returns a string derived from this string by replacing every occurrence of oldChar with newChar.
It returns a string derived from this string by replacing every occurrence of oldChar with newChar.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.replace('o', 'T'));
System.out.print("Return Value :" );
System.out.println(Str.replace('l', 'D'));
}
}
This will produce the following result β
Return Value :WelcTme tT TutTrialspTint.cTm
Return Value :WeDcome to TutoriaDspoint.com
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": 2491,
"s": 2377,
"text": "This method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."
},
{
"code": null,
"e": 2528,
"s": 2491,
"text": "Here is the syntax of this method β"
},
{
"code": null,
"e": 2579,
"s": 2528,
"text": "public String replace(char oldChar, char newChar)\n"
},
{
"code": null,
"e": 2614,
"s": 2579,
"text": "Here is the detail of parameters β"
},
{
"code": null,
"e": 2643,
"s": 2614,
"text": "oldChar β the old character."
},
{
"code": null,
"e": 2672,
"s": 2643,
"text": "oldChar β the old character."
},
{
"code": null,
"e": 2701,
"s": 2672,
"text": "newChar β the new character."
},
{
"code": null,
"e": 2730,
"s": 2701,
"text": "newChar β the new character."
},
{
"code": null,
"e": 2830,
"s": 2730,
"text": "It returns a string derived from this string by replacing every occurrence of oldChar with newChar."
},
{
"code": null,
"e": 2930,
"s": 2830,
"text": "It returns a string derived from this string by replacing every occurrence of oldChar with newChar."
},
{
"code": null,
"e": 3270,
"s": 2930,
"text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.replace('o', 'T'));\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.replace('l', 'D'));\n }\n}"
},
{
"code": null,
"e": 3311,
"s": 3270,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 3400,
"s": 3311,
"text": "Return Value :WelcTme tT TutTrialspTint.cTm\nReturn Value :WeDcome to TutoriaDspoint.com\n"
},
{
"code": null,
"e": 3433,
"s": 3400,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3449,
"s": 3433,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3482,
"s": 3449,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3498,
"s": 3482,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3533,
"s": 3498,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3547,
"s": 3533,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3581,
"s": 3547,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3595,
"s": 3581,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3632,
"s": 3595,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3647,
"s": 3632,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3680,
"s": 3647,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3699,
"s": 3680,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3706,
"s": 3699,
"text": " Print"
},
{
"code": null,
"e": 3717,
"s": 3706,
"text": " Add Notes"
}
] |
C++ String Library - operator[]
|
It returns a reference to the character at position pos in the string.
Following is the declaration for std::string::operator[]
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
pos β Value with the position of a character within the string.
It returns a reference to the character at position pos in the string.
if an exception is thrown, there are no changes in the string.
In below example for std::string::operator[].
#include <iostream>
#include <string>
int main () {
std::string str ("Sairamkrishna Mammahe");
for (int i=0; i<str.length(); ++i) {
std::cout << str[i];
}
return 0;
}
Sairamkrishna Mammahe
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2674,
"s": 2603,
"text": "It returns a reference to the character at position pos in the string."
},
{
"code": null,
"e": 2731,
"s": 2674,
"text": "Following is the declaration for std::string::operator[]"
},
{
"code": null,
"e": 2763,
"s": 2731,
"text": " char& operator[] (size_t pos);"
},
{
"code": null,
"e": 2806,
"s": 2763,
"text": "const char& operator[] (size_t pos) const;"
},
{
"code": null,
"e": 2870,
"s": 2806,
"text": "pos β Value with the position of a character within the string."
},
{
"code": null,
"e": 2941,
"s": 2870,
"text": "It returns a reference to the character at position pos in the string."
},
{
"code": null,
"e": 3004,
"s": 2941,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 3050,
"s": 3004,
"text": "In below example for std::string::operator[]."
},
{
"code": null,
"e": 3236,
"s": 3050,
"text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str (\"Sairamkrishna Mammahe\");\n for (int i=0; i<str.length(); ++i) {\n std::cout << str[i];\n }\n return 0;\n}"
},
{
"code": null,
"e": 3260,
"s": 3236,
"text": "Sairamkrishna Mammahe \n"
},
{
"code": null,
"e": 3267,
"s": 3260,
"text": " Print"
},
{
"code": null,
"e": 3278,
"s": 3267,
"text": " Add Notes"
}
] |
Linux Admin - Remote Management
|
When talking about remote management in CentOS as an Administrator, we will explore two methods β
Console Management
GUI Management
Remote Console Management means performing administration tasks from the command line via a service such as ssh. To use CentOS Linux effectively, as an Administrator, you will need to be proficient with the command line. Linux at its heart was designed to be used from the console. Even today, some system administrators prefer the power of the command and save money on the hardware by running bare-bones Linux boxes with no physical terminal and no GUI installed.
Remote GUI Management is usually accomplished in two ways: either a remote X-Session or a GUI application layer protocol like VNC. Each has its strengths and drawbacks. However, for the most part, VNC is the best choice for Administration. It allows graphical control from other operating systems such as Windows or OS X that do not natively support the X Windows protocol.
Using remote X Sessions is native to both X-Window's Window-Managers and DesktopManagers running on X. However, the entire X Session architecture is mostly used with Linux. Not every System Administrator will have a Linux Laptop on hand to establish a remote X Session. Therefore, it is most common to use an adapted version of VNC Server.
The biggest drawbacks to VNC are: VNC does not natively support a multi-user environment such as remote X-Sessions. Hence, for GUI access to end-users remote XSessions would be the best choice. However, we are mainly concerned with administering a CentOS server remotely.
We will discuss configuring VNC for multiple administrators versus a few hundred endusers with remote X-Sessions.
ssh or Secure Shell is now the standard for remotely administering any Linux server. SSH unlike telnet uses TLS for authenticity and end-to-end encryption of communications. When properly configured an administrator can be pretty sure both their password and the server are trusted remotely.
Before configuring SSH, lets talk a little about the basic security and least common access. When SSH is running on its default port of 22; sooner rather than later, you are going to get brute force dictionary attacks against common user names and passwords. This just comes with the territory. No matter how many hosts you add to your deny files, they will just come in from different IP addresses daily.
With a few common rules, you can simply take some pro-active steps and let the bad guys waste their time. Following are a few rules of security to follow using SSH for remote administration on a production server β
Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com
Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com
Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH.
Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH.
Password policy is a must: Complex SSH user passwords like: "This&IS&a&GUD&P@ssW0rd&24&me". Change passwords every few months to eliminate susceptibility to incremental brute force attacks.
Password policy is a must: Complex SSH user passwords like: "This&IS&a&GUD&P@ssW0rd&24&me". Change passwords every few months to eliminate susceptibility to incremental brute force attacks.
Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example.
Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example.
Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don't have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits.
Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don't have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits.
Note On Linux Security β Anyone interested in Linux Administration should actively pursue current Cyber-Security news and technology. While we mostly hear about other operating systems being compromised, an insecure Linux box is a sought-after treasure for cybercriminals. With the power of Linux on a high-speed internet connection, a skilled cybercriminal can use Linux to leverage attacks on other operating systems.
Step 1 β Install SSH Server and all dependent packages.
[root@localhost]# yum -y install openssh-server
'Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: repos.centos.net
* extras: repos.dfw.centos.com
* updates: centos.centos.com
Resolving Dependencies
--> Running transaction check
---> Package openssh-server.x86_64 0:6.6.1p1-33.el7_3 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
Step 2 β Make a secure regular use to add for shell access.
[root@localhost ~]# useradd choozer
[root@localhost ~]# usermod -c "Remote Access" -d /home/choozer -g users -G
wheel -a choozer
Note β We added the new user to the wheel group enabling ability to su into root once SSH access has been authenticated. We also used a username that cannot be found in common word lists. This way, our account will not get locked out when SSH is attacked.
The file holding configuration settings for sshd server is /etc/ssh/sshd_config.
The portions we want to edit initially are β
LoginGraceTime 60m
PermitRootLogin no
Step 3 β Reload the SSH daemon sshd.
[root@localhost]# systemctl reload sshd
It is good to set the logout grace period to 60 minutes. Some complex administration tasks can exceed the default of 2 minutes. There is really nothing more frustrating than having SSH session timeout when configuring or researching changes.
Step 4 β Let's try to login using the root credentials.
bash-3.2# ssh centos.vmnet.local
root@centos.vmnet.local's password:
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
Step 5 β We can no longer login remotely via ssh with root credentials. So let's login to our unprivileged user account and su into the root account.
bash-3.2# ssh chooser@centos.vmnet.local
choozer@centos.vmnet.local's password:
[choozer@localhost ~]$ su root
Password:
[root@localhost choozer]#
Step 6 β Finally, let's make sure the SSHD service loads on boot and firewalld allows outside SSH connections.
[root@localhost]# systemctl enable sshd
[root@localhost]# firewall-cmd --permanent --add-service=ssh
success
[root@localhost]# firewall-cmd --reload
success
[root@localhost]#
SSH is now set up and ready for remote administration. Depending on your enterprise border, the packet filtering border device may need to be configured to allow SSH remote administration outside the corporate LAN.
There are a few ways to enable remote CentOS administration via VNC on CentOS 6 - 7. The easiest, but most limiting way is simply using a package called vino. Vino is a Virtual Network Desktop Connection application for Linux designed around the Gnome Desktop platform. Hence, it is assumed the installation was completed with Gnome Desktop. If the Gnome Desktop has not been installed, please do so before continuing. Vino will be installed with a Gnome GUI install by default.
To configure screen sharing with Vino under Gnome, we want to go into the CentOS System Preferences for screen sharing.
Applications->System Tools->Settings->Sharing
Notes to configuring VNC Desktop Sharing β
Disable New Connections must ask for access β This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop.
Disable New Connections must ask for access β This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop.
Enable Require a password β This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security).
Enable Require a password β This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security).
Forward UP&P Ports: If available leave disabled β Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this.
Forward UP&P Ports: If available leave disabled β Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this.
Make sure vino is listening on the VNC Port 5900.
[root@localhost]# netstat -antup | grep vino
tcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 4873/vino-server
tcp6 0 0 :::5900 :::* LISTEN 4873/vino-server
[root@localhost]#
Let's now configure our Firewall to allow incoming VNC connections.
[root@localhost]# firewall-cmd --permanent --add-port=5900/tcp
success
[root@localhost]# firewall-cmd --reload
success
[root@localhost rdc]#
Finally, as you can see we are able to connect our CentOS Box and administer it with a VNC client on either Windows or OS X.
It is just as important to obey the same rules for VNC as we set forth for SSH. Just like SSH, VNC is continually scanned across IP ranges and tested for weak passwords. It is also worth a note that leaving the default CentOS login enabled with a console timeout does help with remote VNC security. As an attacker will need the VNC and user password, make sure your screen sharing password is different and just as hard to guess as the user password.
After entering the the VNC screen sharing password, we must also enter the user password to access a locked desktop.
Security Note β By default, VNC is not an encrypted protocol. Hence, the VNC connection should be tunneled through SSH for encryption.
Setting up an SSH Tunnel will provide a layer of SSH encryption to tunnel the VNC connection through. Another great feature is it uses SSH compression to add another layer of compression to the VNC GUI screen updates. More secure and faster is always a good thing when dealing with the administration of CentOS servers!
So from your client that will be initiating the VNC connection, let's set up a remote SSH tunnel. In this demonstration, we are using OS X. First we need to sudo -s to root.
bash-3.2# sudo -s
password:
Enter the user password and we should now have root shell with a # prompt β
bash-3.2#
Now, let's create our SSH Tunnel.
ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N
Let's break this command down β
ssh β Runs the local ssh utility
ssh β Runs the local ssh utility
-f β ssh should run in the background after the task fully executes
-f β ssh should run in the background after the task fully executes
rdc@192.168.1.143 β Remote ssh user on the CentOS server hosting VNC services
rdc@192.168.1.143 β Remote ssh user on the CentOS server hosting VNC services
-L 2200:192.168.1.143:5900 β Create our tunnel [Local Port]:[remote host]:[remote port of VNC service]
-L 2200:192.168.1.143:5900 β Create our tunnel [Local Port]:[remote host]:[remote port of VNC service]
-N tells ssh we do not wish to execute a command on the remote system
-N tells ssh we do not wish to execute a command on the remote system
bash-3.2# ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N
rdc@192.168.1.143's password:
After successfully entering the remote ssh user's password, our ssh tunnel is created. Now for the cool part! To connect we point our VNC client at the localhost on the port of our tunnel, in this case port 2200. Following is the configuration on Mac Laptop's VNC Client β
And finally, our remote VNC Desktop Connection!
The cool thing about SSH tunneling is it can be used for almost any protocol. SSH tunnels are commonly used to bypass egress and ingress port filtering by an ISP, as well as trick application layer IDS/IPS while evading other session layer monitoring.
Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered).
Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered).
Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data.
Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data.
SSH Tunneling is great tool in a Linux Administrator's toolbox for getting things done. However, as an Administrator we want to explore locking down the availability of lesser privileged users having access to SSH tunneling.
Administration Security Note β Restricting SSH Tunneling is something that requires thought on the part of an Administrator. Assessing why users need SSH Tunneling in the first place; what users need tunneling; along with practical risk probability and worst-case impact.
This is an advanced topic stretching outside the realm of an intermediate level primer. Research on this topic is advised for those who wish to reach the upper echelons of CentOS Linux Administration.
The design of X-Windows in Linux is really neat compared to that of Windows. If we want to control a remote Linux box from another Linux boxm we can take advantage of mechanisms built into X.
X-Windows (often called just "X"), provides the mechanism to display application windows originating from one Linux box to the display portion of X on another Linux box. So through SSH we can request an X-Windows application be forwarded to the display of another Linux box across the world!
To run an X Application remotely via an ssh tunnel, we just need to run a single command β
[root@localhost]# ssh -X rdc@192.168.1.105
The syntax is β ssh -X [user]@[host], and the host must be running ssh with a valid user.
Following is a screenshot of GIMP running on a Ubuntu Workstation through a remote XWindows ssh tunnel.
It is pretty simple to run applications remotely from another Linux server or workstation. It is also possible to start an entire X-Session and have the entire desktop environment remotely through a few methods.
XDMCP
XDMCP
Headless software packages such as NX
Headless software packages such as NX
Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE
Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE
This method is most commonly used for headless servers with no physical display and really exceeds the scope of an intermediate level primer. However, it is good to know of the options available.
57 Lectures
7.5 hours
Mamta Tripathi
25 Lectures
3 hours
Lets Kode It
14 Lectures
1.5 hours
Abhilash Nelson
58 Lectures
2.5 hours
Frahaan Hussain
129 Lectures
23 hours
Eduonix Learning Solutions
23 Lectures
5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2355,
"s": 2257,
"text": "When talking about remote management in CentOS as an Administrator, we will explore two methods β"
},
{
"code": null,
"e": 2374,
"s": 2355,
"text": "Console Management"
},
{
"code": null,
"e": 2389,
"s": 2374,
"text": "GUI Management"
},
{
"code": null,
"e": 2855,
"s": 2389,
"text": "Remote Console Management means performing administration tasks from the command line via a service such as ssh. To use CentOS Linux effectively, as an Administrator, you will need to be proficient with the command line. Linux at its heart was designed to be used from the console. Even today, some system administrators prefer the power of the command and save money on the hardware by running bare-bones Linux boxes with no physical terminal and no GUI installed."
},
{
"code": null,
"e": 3229,
"s": 2855,
"text": "Remote GUI Management is usually accomplished in two ways: either a remote X-Session or a GUI application layer protocol like VNC. Each has its strengths and drawbacks. However, for the most part, VNC is the best choice for Administration. It allows graphical control from other operating systems such as Windows or OS X that do not natively support the X Windows protocol."
},
{
"code": null,
"e": 3569,
"s": 3229,
"text": "Using remote X Sessions is native to both X-Window's Window-Managers and DesktopManagers running on X. However, the entire X Session architecture is mostly used with Linux. Not every System Administrator will have a Linux Laptop on hand to establish a remote X Session. Therefore, it is most common to use an adapted version of VNC Server."
},
{
"code": null,
"e": 3841,
"s": 3569,
"text": "The biggest drawbacks to VNC are: VNC does not natively support a multi-user environment such as remote X-Sessions. Hence, for GUI access to end-users remote XSessions would be the best choice. However, we are mainly concerned with administering a CentOS server remotely."
},
{
"code": null,
"e": 3955,
"s": 3841,
"text": "We will discuss configuring VNC for multiple administrators versus a few hundred endusers with remote X-Sessions."
},
{
"code": null,
"e": 4247,
"s": 3955,
"text": "ssh or Secure Shell is now the standard for remotely administering any Linux server. SSH unlike telnet uses TLS for authenticity and end-to-end encryption of communications. When properly configured an administrator can be pretty sure both their password and the server are trusted remotely."
},
{
"code": null,
"e": 4653,
"s": 4247,
"text": "Before configuring SSH, lets talk a little about the basic security and least common access. When SSH is running on its default port of 22; sooner rather than later, you are going to get brute force dictionary attacks against common user names and passwords. This just comes with the territory. No matter how many hosts you add to your deny files, they will just come in from different IP addresses daily."
},
{
"code": null,
"e": 4868,
"s": 4653,
"text": "With a few common rules, you can simply take some pro-active steps and let the bad guys waste their time. Following are a few rules of security to follow using SSH for remote administration on a production server β"
},
{
"code": null,
"e": 5042,
"s": 4868,
"text": "Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com"
},
{
"code": null,
"e": 5216,
"s": 5042,
"text": "Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com"
},
{
"code": null,
"e": 5382,
"s": 5216,
"text": "Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH."
},
{
"code": null,
"e": 5548,
"s": 5382,
"text": "Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH."
},
{
"code": null,
"e": 5738,
"s": 5548,
"text": "Password policy is a must: Complex SSH user passwords like: \"This&IS&a&GUD&P@ssW0rd&24&me\". Change passwords every few months to eliminate susceptibility to incremental brute force attacks."
},
{
"code": null,
"e": 5928,
"s": 5738,
"text": "Password policy is a must: Complex SSH user passwords like: \"This&IS&a&GUD&P@ssW0rd&24&me\". Change passwords every few months to eliminate susceptibility to incremental brute force attacks."
},
{
"code": null,
"e": 6172,
"s": 5928,
"text": "Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example."
},
{
"code": null,
"e": 6416,
"s": 6172,
"text": "Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example."
},
{
"code": null,
"e": 6734,
"s": 6416,
"text": "Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don't have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits."
},
{
"code": null,
"e": 7052,
"s": 6734,
"text": "Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don't have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits."
},
{
"code": null,
"e": 7472,
"s": 7052,
"text": "Note On Linux Security β Anyone interested in Linux Administration should actively pursue current Cyber-Security news and technology. While we mostly hear about other operating systems being compromised, an insecure Linux box is a sought-after treasure for cybercriminals. With the power of Linux on a high-speed internet connection, a skilled cybercriminal can use Linux to leverage attacks on other operating systems."
},
{
"code": null,
"e": 7528,
"s": 7472,
"text": "Step 1 β Install SSH Server and all dependent packages."
},
{
"code": null,
"e": 7948,
"s": 7528,
"text": "[root@localhost]# yum -y install openssh-server \n'Loaded plugins: fastestmirror, langpacks \nLoading mirror speeds from cached hostfile \n* base: repos.centos.net \n* extras: repos.dfw.centos.com \n* updates: centos.centos.com \nResolving Dependencies \n --> Running transaction check \n ---> Package openssh-server.x86_64 0:6.6.1p1-33.el7_3 will be installed \n --> Finished Dependency Resolution \nDependencies Resolved\n"
},
{
"code": null,
"e": 8008,
"s": 7948,
"text": "Step 2 β Make a secure regular use to add for shell access."
},
{
"code": null,
"e": 8140,
"s": 8008,
"text": "[root@localhost ~]# useradd choozer \n[root@localhost ~]# usermod -c \"Remote Access\" -d /home/choozer -g users -G \nwheel -a choozer\n"
},
{
"code": null,
"e": 8396,
"s": 8140,
"text": "Note β We added the new user to the wheel group enabling ability to su into root once SSH access has been authenticated. We also used a username that cannot be found in common word lists. This way, our account will not get locked out when SSH is attacked."
},
{
"code": null,
"e": 8477,
"s": 8396,
"text": "The file holding configuration settings for sshd server is /etc/ssh/sshd_config."
},
{
"code": null,
"e": 8522,
"s": 8477,
"text": "The portions we want to edit initially are β"
},
{
"code": null,
"e": 8561,
"s": 8522,
"text": "LoginGraceTime 60m\nPermitRootLogin no\n"
},
{
"code": null,
"e": 8598,
"s": 8561,
"text": "Step 3 β Reload the SSH daemon sshd."
},
{
"code": null,
"e": 8639,
"s": 8598,
"text": "[root@localhost]# systemctl reload sshd\n"
},
{
"code": null,
"e": 8881,
"s": 8639,
"text": "It is good to set the logout grace period to 60 minutes. Some complex administration tasks can exceed the default of 2 minutes. There is really nothing more frustrating than having SSH session timeout when configuring or researching changes."
},
{
"code": null,
"e": 8937,
"s": 8881,
"text": "Step 4 β Let's try to login using the root credentials."
},
{
"code": null,
"e": 9080,
"s": 8937,
"text": "bash-3.2# ssh centos.vmnet.local \nroot@centos.vmnet.local's password: \nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\n"
},
{
"code": null,
"e": 9230,
"s": 9080,
"text": "Step 5 β We can no longer login remotely via ssh with root credentials. So let's login to our unprivileged user account and su into the root account."
},
{
"code": null,
"e": 9379,
"s": 9230,
"text": "bash-3.2# ssh chooser@centos.vmnet.local\nchoozer@centos.vmnet.local's password:\n[choozer@localhost ~]$ su root\nPassword:\n\n[root@localhost choozer]#\n"
},
{
"code": null,
"e": 9490,
"s": 9379,
"text": "Step 6 β Finally, let's make sure the SSHD service loads on boot and firewalld allows outside SSH connections."
},
{
"code": null,
"e": 9673,
"s": 9490,
"text": "[root@localhost]# systemctl enable sshd\n\n[root@localhost]# firewall-cmd --permanent --add-service=ssh \nsuccess\n\n[root@localhost]# firewall-cmd --reload \nsuccess\n \n[root@localhost]#\n "
},
{
"code": null,
"e": 9888,
"s": 9673,
"text": "SSH is now set up and ready for remote administration. Depending on your enterprise border, the packet filtering border device may need to be configured to allow SSH remote administration outside the corporate LAN."
},
{
"code": null,
"e": 10367,
"s": 9888,
"text": "There are a few ways to enable remote CentOS administration via VNC on CentOS 6 - 7. The easiest, but most limiting way is simply using a package called vino. Vino is a Virtual Network Desktop Connection application for Linux designed around the Gnome Desktop platform. Hence, it is assumed the installation was completed with Gnome Desktop. If the Gnome Desktop has not been installed, please do so before continuing. Vino will be installed with a Gnome GUI install by default."
},
{
"code": null,
"e": 10487,
"s": 10367,
"text": "To configure screen sharing with Vino under Gnome, we want to go into the CentOS System Preferences for screen sharing."
},
{
"code": null,
"e": 10534,
"s": 10487,
"text": "Applications->System Tools->Settings->Sharing\n"
},
{
"code": null,
"e": 10577,
"s": 10534,
"text": "Notes to configuring VNC Desktop Sharing β"
},
{
"code": null,
"e": 10778,
"s": 10577,
"text": "Disable New Connections must ask for access β This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop."
},
{
"code": null,
"e": 10979,
"s": 10778,
"text": "Disable New Connections must ask for access β This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop."
},
{
"code": null,
"e": 11190,
"s": 10979,
"text": "Enable Require a password β This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security)."
},
{
"code": null,
"e": 11401,
"s": 11190,
"text": "Enable Require a password β This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security)."
},
{
"code": null,
"e": 11610,
"s": 11401,
"text": "Forward UP&P Ports: If available leave disabled β Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this."
},
{
"code": null,
"e": 11819,
"s": 11610,
"text": "Forward UP&P Ports: If available leave disabled β Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this."
},
{
"code": null,
"e": 11869,
"s": 11819,
"text": "Make sure vino is listening on the VNC Port 5900."
},
{
"code": null,
"e": 12118,
"s": 11869,
"text": "[root@localhost]# netstat -antup | grep vino \ntcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 4873/vino-server\ntcp6 0 0 :::5900 :::* LISTEN 4873/vino-server\n \n[root@localhost]#\n"
},
{
"code": null,
"e": 12186,
"s": 12118,
"text": "Let's now configure our Firewall to allow incoming VNC connections."
},
{
"code": null,
"e": 12332,
"s": 12186,
"text": "[root@localhost]# firewall-cmd --permanent --add-port=5900/tcp \nsuccess\n\n[root@localhost]# firewall-cmd --reload \nsuccess\n\n[root@localhost rdc]#\n"
},
{
"code": null,
"e": 12457,
"s": 12332,
"text": "Finally, as you can see we are able to connect our CentOS Box and administer it with a VNC client on either Windows or OS X."
},
{
"code": null,
"e": 12908,
"s": 12457,
"text": "It is just as important to obey the same rules for VNC as we set forth for SSH. Just like SSH, VNC is continually scanned across IP ranges and tested for weak passwords. It is also worth a note that leaving the default CentOS login enabled with a console timeout does help with remote VNC security. As an attacker will need the VNC and user password, make sure your screen sharing password is different and just as hard to guess as the user password."
},
{
"code": null,
"e": 13025,
"s": 12908,
"text": "After entering the the VNC screen sharing password, we must also enter the user password to access a locked desktop."
},
{
"code": null,
"e": 13160,
"s": 13025,
"text": "Security Note β By default, VNC is not an encrypted protocol. Hence, the VNC connection should be tunneled through SSH for encryption."
},
{
"code": null,
"e": 13480,
"s": 13160,
"text": "Setting up an SSH Tunnel will provide a layer of SSH encryption to tunnel the VNC connection through. Another great feature is it uses SSH compression to add another layer of compression to the VNC GUI screen updates. More secure and faster is always a good thing when dealing with the administration of CentOS servers!"
},
{
"code": null,
"e": 13654,
"s": 13480,
"text": "So from your client that will be initiating the VNC connection, let's set up a remote SSH tunnel. In this demonstration, we are using OS X. First we need to sudo -s to root."
},
{
"code": null,
"e": 13684,
"s": 13654,
"text": "bash-3.2# sudo -s \npassword:\n"
},
{
"code": null,
"e": 13760,
"s": 13684,
"text": "Enter the user password and we should now have root shell with a # prompt β"
},
{
"code": null,
"e": 13771,
"s": 13760,
"text": "bash-3.2#\n"
},
{
"code": null,
"e": 13805,
"s": 13771,
"text": "Now, let's create our SSH Tunnel."
},
{
"code": null,
"e": 13861,
"s": 13805,
"text": "ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N\n"
},
{
"code": null,
"e": 13893,
"s": 13861,
"text": "Let's break this command down β"
},
{
"code": null,
"e": 13926,
"s": 13893,
"text": "ssh β Runs the local ssh utility"
},
{
"code": null,
"e": 13959,
"s": 13926,
"text": "ssh β Runs the local ssh utility"
},
{
"code": null,
"e": 14027,
"s": 13959,
"text": "-f β ssh should run in the background after the task fully executes"
},
{
"code": null,
"e": 14095,
"s": 14027,
"text": "-f β ssh should run in the background after the task fully executes"
},
{
"code": null,
"e": 14173,
"s": 14095,
"text": "rdc@192.168.1.143 β Remote ssh user on the CentOS server hosting VNC services"
},
{
"code": null,
"e": 14251,
"s": 14173,
"text": "rdc@192.168.1.143 β Remote ssh user on the CentOS server hosting VNC services"
},
{
"code": null,
"e": 14354,
"s": 14251,
"text": "-L 2200:192.168.1.143:5900 β Create our tunnel [Local Port]:[remote host]:[remote port of VNC service]"
},
{
"code": null,
"e": 14457,
"s": 14354,
"text": "-L 2200:192.168.1.143:5900 β Create our tunnel [Local Port]:[remote host]:[remote port of VNC service]"
},
{
"code": null,
"e": 14527,
"s": 14457,
"text": "-N tells ssh we do not wish to execute a command on the remote system"
},
{
"code": null,
"e": 14597,
"s": 14527,
"text": "-N tells ssh we do not wish to execute a command on the remote system"
},
{
"code": null,
"e": 14693,
"s": 14597,
"text": "bash-3.2# ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N\nrdc@192.168.1.143's password:\n"
},
{
"code": null,
"e": 14966,
"s": 14693,
"text": "After successfully entering the remote ssh user's password, our ssh tunnel is created. Now for the cool part! To connect we point our VNC client at the localhost on the port of our tunnel, in this case port 2200. Following is the configuration on Mac Laptop's VNC Client β"
},
{
"code": null,
"e": 15014,
"s": 14966,
"text": "And finally, our remote VNC Desktop Connection!"
},
{
"code": null,
"e": 15266,
"s": 15014,
"text": "The cool thing about SSH tunneling is it can be used for almost any protocol. SSH tunnels are commonly used to bypass egress and ingress port filtering by an ISP, as well as trick application layer IDS/IPS while evading other session layer monitoring."
},
{
"code": null,
"e": 15406,
"s": 15266,
"text": "Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered)."
},
{
"code": null,
"e": 15546,
"s": 15406,
"text": "Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered)."
},
{
"code": null,
"e": 15712,
"s": 15546,
"text": "Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data."
},
{
"code": null,
"e": 15878,
"s": 15712,
"text": "Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data."
},
{
"code": null,
"e": 16103,
"s": 15878,
"text": "SSH Tunneling is great tool in a Linux Administrator's toolbox for getting things done. However, as an Administrator we want to explore locking down the availability of lesser privileged users having access to SSH tunneling."
},
{
"code": null,
"e": 16375,
"s": 16103,
"text": "Administration Security Note β Restricting SSH Tunneling is something that requires thought on the part of an Administrator. Assessing why users need SSH Tunneling in the first place; what users need tunneling; along with practical risk probability and worst-case impact."
},
{
"code": null,
"e": 16576,
"s": 16375,
"text": "This is an advanced topic stretching outside the realm of an intermediate level primer. Research on this topic is advised for those who wish to reach the upper echelons of CentOS Linux Administration."
},
{
"code": null,
"e": 16768,
"s": 16576,
"text": "The design of X-Windows in Linux is really neat compared to that of Windows. If we want to control a remote Linux box from another Linux boxm we can take advantage of mechanisms built into X."
},
{
"code": null,
"e": 17060,
"s": 16768,
"text": "X-Windows (often called just \"X\"), provides the mechanism to display application windows originating from one Linux box to the display portion of X on another Linux box. So through SSH we can request an X-Windows application be forwarded to the display of another Linux box across the world!"
},
{
"code": null,
"e": 17151,
"s": 17060,
"text": "To run an X Application remotely via an ssh tunnel, we just need to run a single command β"
},
{
"code": null,
"e": 17195,
"s": 17151,
"text": "[root@localhost]# ssh -X rdc@192.168.1.105\n"
},
{
"code": null,
"e": 17285,
"s": 17195,
"text": "The syntax is β ssh -X [user]@[host], and the host must be running ssh with a valid user."
},
{
"code": null,
"e": 17389,
"s": 17285,
"text": "Following is a screenshot of GIMP running on a Ubuntu Workstation through a remote XWindows ssh tunnel."
},
{
"code": null,
"e": 17601,
"s": 17389,
"text": "It is pretty simple to run applications remotely from another Linux server or workstation. It is also possible to start an entire X-Session and have the entire desktop environment remotely through a few methods."
},
{
"code": null,
"e": 17607,
"s": 17601,
"text": "XDMCP"
},
{
"code": null,
"e": 17613,
"s": 17607,
"text": "XDMCP"
},
{
"code": null,
"e": 17651,
"s": 17613,
"text": "Headless software packages such as NX"
},
{
"code": null,
"e": 17689,
"s": 17651,
"text": "Headless software packages such as NX"
},
{
"code": null,
"e": 17780,
"s": 17689,
"text": "Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE"
},
{
"code": null,
"e": 17871,
"s": 17780,
"text": "Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE"
},
{
"code": null,
"e": 18067,
"s": 17871,
"text": "This method is most commonly used for headless servers with no physical display and really exceeds the scope of an intermediate level primer. However, it is good to know of the options available."
},
{
"code": null,
"e": 18102,
"s": 18067,
"text": "\n 57 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 18118,
"s": 18102,
"text": " Mamta Tripathi"
},
{
"code": null,
"e": 18151,
"s": 18118,
"text": "\n 25 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 18165,
"s": 18151,
"text": " Lets Kode It"
},
{
"code": null,
"e": 18200,
"s": 18165,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 18217,
"s": 18200,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 18252,
"s": 18217,
"text": "\n 58 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 18269,
"s": 18252,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 18304,
"s": 18269,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 18332,
"s": 18304,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 18365,
"s": 18332,
"text": "\n 23 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 18405,
"s": 18365,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 18412,
"s": 18405,
"text": " Print"
},
{
"code": null,
"e": 18423,
"s": 18412,
"text": " Add Notes"
}
] |
How to Split large string in to n-size chunks in JavaScript?
|
There are two ways to split a large string in to n-sized sub strings.
This is a pure logic method in which only conventional methods are used such as for loop, concat, modulous etc. This method is not as sophisticated as regex method, because it's a predetermined method. The number of chunks that string to be divided should be predetermined before starting coding.
In the following example the string "tutorixtutorixtutorix" is divided in to 3-chunks of sub strings.
Live Demo
<html>
<body>
<script>
var v = [];
var str = "tutorixtutorixtutorix"
var t = str.split("");
document.write(t);
document.write("</br>");
for (var i = 0; i< t.length; i++){
if((i % 3) == 2){
v.push(t[i-2].concat(t[i-1],t[i]));
}
}
document.write(v);
</script>
</body>
</html>
tut,ori,xtu,tor,ixt,uto,rix
It is not a predetermined method. Regex method provides a slot to mention the size to chunk the string.
In general, for any string out of which you want to extract at-most n-sized sub strings, the syntax is
str.match(/.{1,n}/g); // Replace n with the size of the substring
If the string contains any newlines or carriage returns, then the syntax is
str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring
The original syntax of the code is
function chunkString(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
Live Demo
<html>
<body>
<script>
stringChop = function(str, size){
if (str == null)
return [];
str = String(str);
return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str];
}
document.write(stringChop('tutorialspoint'));
document.write("<br>");
document.write(stringChop('tutorix',2));
document.write("<br>");
document.write(stringChop('tutorialspoint',3));
</script>
</body>
</html>
["tutorialspoint"]
["tu","to","ri","x"]
["tut","ori","als","poi","nt"]
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "There are two ways to split a large string in to n-sized sub strings."
},
{
"code": null,
"e": 1429,
"s": 1132,
"text": "This is a pure logic method in which only conventional methods are used such as for loop, concat, modulous etc. This method is not as sophisticated as regex method, because it's a predetermined method. The number of chunks that string to be divided should be predetermined before starting coding."
},
{
"code": null,
"e": 1531,
"s": 1429,
"text": "In the following example the string \"tutorixtutorixtutorix\" is divided in to 3-chunks of sub strings."
},
{
"code": null,
"e": 1541,
"s": 1531,
"text": "Live Demo"
},
{
"code": null,
"e": 1860,
"s": 1541,
"text": "<html>\n<body>\n<script>\n var v = [];\n var str = \"tutorixtutorixtutorix\"\n var t = str.split(\"\");\n document.write(t);\n document.write(\"</br>\");\n for (var i = 0; i< t.length; i++){\n if((i % 3) == 2){\n v.push(t[i-2].concat(t[i-1],t[i]));\n }\n }\n document.write(v);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1888,
"s": 1860,
"text": "tut,ori,xtu,tor,ixt,uto,rix"
},
{
"code": null,
"e": 1993,
"s": 1888,
"text": "It is not a predetermined method. Regex method provides a slot to mention the size to chunk the string. "
},
{
"code": null,
"e": 2096,
"s": 1993,
"text": "In general, for any string out of which you want to extract at-most n-sized sub strings, the syntax is"
},
{
"code": null,
"e": 2165,
"s": 2096,
"text": " str.match(/.{1,n}/g); // Replace n with the size of the substring"
},
{
"code": null,
"e": 2241,
"s": 2165,
"text": "If the string contains any newlines or carriage returns, then the syntax is"
},
{
"code": null,
"e": 2318,
"s": 2241,
"text": " str.match(/(.|[\\r\\n]){1,n}/g); // Replace n with the size of the substring"
},
{
"code": null,
"e": 2353,
"s": 2318,
"text": "The original syntax of the code is"
},
{
"code": null,
"e": 2453,
"s": 2353,
"text": " function chunkString(str, size) {\n return str.match(new RegExp('.{1,' + size + '}', 'g'));\n}"
},
{
"code": null,
"e": 2463,
"s": 2453,
"text": "Live Demo"
},
{
"code": null,
"e": 2907,
"s": 2463,
"text": "<html>\n<body>\n<script>\n stringChop = function(str, size){\n if (str == null)\n return [];\n str = String(str);\n return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str];\n }\n document.write(stringChop('tutorialspoint'));\n document.write(\"<br>\");\n document.write(stringChop('tutorix',2));\n document.write(\"<br>\");\n document.write(stringChop('tutorialspoint',3));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2978,
"s": 2907,
"text": "[\"tutorialspoint\"]\n[\"tu\",\"to\",\"ri\",\"x\"]\n[\"tut\",\"ori\",\"als\",\"poi\",\"nt\"]"
}
] |
@Autowired,@Qualifier,@Value annotations in Spring - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
The Spring framework provides an autowiring feature to enable the object dependency implicitly. @Autowired and @Qualifier are the two different autowire annotations to achieve the automatic dependency injunction in Spring.
In Spring, we can use @Autowired annotation to tell the IOC container that the dependency of the properties will be injected by the container itself.
The @Autowired annotations can be used on top of a field, setter methods or on top of a constructor of a class.
If we declare the autowire annotation on top of the method or property, the IOC container searches whether a dependency property name and the bean id in the XML are matched or not, if those are matched the automatic dependency injection will happen.
public class Book {
private Author author;
@Autowired
public void setAuthor(Author author) {
this.author = author;
}
}
Xml Configuration :
<bean id="author" class="com.onlinetutorialspoint.beans.Author">
<property name="name" value="OnlineTutorialsPoint" />
<property name="name" value="Hyderabad" />
</bean>
We can use the @Autowired annotation, on top of the constructor.
Here is the syntax:
public class Book {
private Author author;
@Autowired
public Book(Author author) {
this.author = author;
}
}
We can use the Autowired annotation, on top of the property. Here is the syntax:
public class Book {
@Autowired
private Author author;
}
Xml Configuration :
<bean id="author" class="com.onlinetutorialspoint.beans.Author">
<property name="name" value="OnlineTutorialsPoint" />
<property name="name" value="Hyderabad" />
</bean>
@Qualifier is one of the autowiring properties in spring. If a dependency class is configured more than once in the spring configuration file, the IOC container will throw the Exception for bean ambiguity. In order to resolve the ambiguity, we can use @Qualifier annotation along with the @Autowired annotation.
Example:
public class Book {
private Author author;
@Autowired
@Qualifier("author2")
private Author author;
public void setAuthor(Author author){
this.author = author
}
}
Xml Configuration :
<bean id="author" class="com.onlinetutorialspoint.beans.Author">
<property name="name" value="OnlineTutorialsPoint" />
<property name="name" value="Hyderabad" />
</bean>
@Value annotation is used to assign a value to a property. It can be used to assign a value for simple type properties like int, float etc.. the @Value annotation tells IOC container, that read the value of a key from the resource bundle and initializes a simple property with that value.
Example:
public class Sample {
@Value("${k1}")
private int i;
}
At runtime, the IOC container initializes the i with the value of k1 from the resource bundle. Here the resource bundle can be a properties or yaml file. In the properties file, if the k1 value is 100 then in runtime IOC container assign the 100 value to i
Spring Expression Language.
Happy Learning π
Spring Java Configuration Example
@Qualifier annotation example in Spring
spring expression language example
Spring Bean Autowire By Constructor Example
Types of Spring Bean Scopes Example
Spring Bean Autowire ByName Example
Spring Bean Autowire ByType Example
@Component,@Service,@Repository,@Controller in spring
Repeating Annotations in Java 8
Spring Collection Map Dependency Example
How to Get All Spring Beans Details Loaded in ICO
Spring Collection Dependency List Example
Spring Boot Lazy Loading Beans Example
Spring Hibernate Example
Hibernate Many to Many Mapping Example (XML)
Spring Java Configuration Example
@Qualifier annotation example in Spring
spring expression language example
Spring Bean Autowire By Constructor Example
Types of Spring Bean Scopes Example
Spring Bean Autowire ByName Example
Spring Bean Autowire ByType Example
@Component,@Service,@Repository,@Controller in spring
Repeating Annotations in Java 8
Spring Collection Map Dependency Example
How to Get All Spring Beans Details Loaded in ICO
Spring Collection Dependency List Example
Spring Boot Lazy Loading Beans Example
Spring Hibernate Example
Hibernate Many to Many Mapping Example (XML)
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 621,
"s": 398,
"text": "The Spring framework provides an autowiring feature to enable the object dependency implicitly. @Autowired and @Qualifier are the two different autowire annotations to achieve the automatic dependency injunction in Spring."
},
{
"code": null,
"e": 771,
"s": 621,
"text": "In Spring, we can use @Autowired annotation to tell the IOC container that the dependency of the properties will be injected by the container itself."
},
{
"code": null,
"e": 883,
"s": 771,
"text": "The @Autowired annotations can be used on top of a field, setter methods or on top of a constructor of a class."
},
{
"code": null,
"e": 1133,
"s": 883,
"text": "If we declare the autowire annotation on top of the method or property, the IOC container searches whether a dependency property name and the bean id in the XML are matched or not, if those are matched the automatic dependency injection will happen."
},
{
"code": null,
"e": 1277,
"s": 1133,
"text": "public class Book {\n private Author author;\n\n @Autowired\n public void setAuthor(Author author) {\n this.author = author;\n }\n}"
},
{
"code": null,
"e": 1297,
"s": 1277,
"text": "Xml Configuration :"
},
{
"code": null,
"e": 1483,
"s": 1297,
"text": "<bean id=\"author\" class=\"com.onlinetutorialspoint.beans.Author\"> \n <property name=\"name\" value=\"OnlineTutorialsPoint\" /> \n <property name=\"name\" value=\"Hyderabad\" />\n</bean>"
},
{
"code": null,
"e": 1548,
"s": 1483,
"text": "We can use the @Autowired annotation, on top of the constructor."
},
{
"code": null,
"e": 1568,
"s": 1548,
"text": "Here is the syntax:"
},
{
"code": null,
"e": 1702,
"s": 1568,
"text": "public class Book {\n private Author author;\n\n @Autowired\n public Book(Author author) {\n this.author = author;\n }\n}"
},
{
"code": null,
"e": 1783,
"s": 1702,
"text": "We can use the Autowired annotation, on top of the property. Here is the syntax:"
},
{
"code": null,
"e": 1847,
"s": 1783,
"text": "public class Book {\n @Autowired\n private Author author;\n}"
},
{
"code": null,
"e": 1867,
"s": 1847,
"text": "Xml Configuration :"
},
{
"code": null,
"e": 2048,
"s": 1867,
"text": "<bean id=\"author\" class=\"com.onlinetutorialspoint.beans.Author\">\n <property name=\"name\" value=\"OnlineTutorialsPoint\" /> \n <property name=\"name\" value=\"Hyderabad\" />\n</bean>"
},
{
"code": null,
"e": 2361,
"s": 2048,
"text": "@Qualifier is one of the autowiring properties in spring. If a dependency class is configured more than once in the spring configuration file, the IOC container will throw the Exception for bean ambiguity. In order to resolve the ambiguity, we can use @Qualifier annotation along with the @Autowired annotation."
},
{
"code": null,
"e": 2370,
"s": 2361,
"text": "Example:"
},
{
"code": null,
"e": 2565,
"s": 2370,
"text": "public class Book {\n private Author author;\n @Autowired\n @Qualifier(\"author2\")\n private Author author;\n\n public void setAuthor(Author author){\n this.author = author\n }\n}"
},
{
"code": null,
"e": 2585,
"s": 2565,
"text": "Xml Configuration :"
},
{
"code": null,
"e": 2761,
"s": 2585,
"text": "<bean id=\"author\" class=\"com.onlinetutorialspoint.beans.Author\">\n <property name=\"name\" value=\"OnlineTutorialsPoint\" />\n <property name=\"name\" value=\"Hyderabad\" />\n</bean>"
},
{
"code": null,
"e": 3050,
"s": 2761,
"text": "@Value annotation is used to assign a value to a property. It can be used to assign a value for simple type properties like int, float etc.. the @Value annotation tells IOC container, that read the value of a key from the resource bundle and initializes a simple property with that value."
},
{
"code": null,
"e": 3059,
"s": 3050,
"text": "Example:"
},
{
"code": null,
"e": 3122,
"s": 3059,
"text": "public class Sample {\n @Value(\"${k1}\")\n private int i;\n}"
},
{
"code": null,
"e": 3379,
"s": 3122,
"text": "At runtime, the IOC container initializes the i with the value of k1 from the resource bundle. Here the resource bundle can be a properties or yaml file. In the properties file, if the k1 value is 100 then in runtime IOC container assign the 100 value to i"
},
{
"code": null,
"e": 3407,
"s": 3379,
"text": "Spring Expression Language."
},
{
"code": null,
"e": 3424,
"s": 3407,
"text": "Happy Learning π"
},
{
"code": null,
"e": 4015,
"s": 3424,
"text": "\nSpring Java Configuration Example\n@Qualifier annotation example in Spring\nspring expression language example\nSpring Bean Autowire By Constructor Example\nTypes of Spring Bean Scopes Example\nSpring Bean Autowire ByName Example\nSpring Bean Autowire ByType Example\n@Component,@Service,@Repository,@Controller in spring\nRepeating Annotations in Java 8\nSpring Collection Map Dependency Example\nHow to Get All Spring Beans Details Loaded in ICO\nSpring Collection Dependency List Example\nSpring Boot Lazy Loading Beans Example\nSpring Hibernate Example\nHibernate Many to Many Mapping Example (XML)\n"
},
{
"code": null,
"e": 4049,
"s": 4015,
"text": "Spring Java Configuration Example"
},
{
"code": null,
"e": 4089,
"s": 4049,
"text": "@Qualifier annotation example in Spring"
},
{
"code": null,
"e": 4124,
"s": 4089,
"text": "spring expression language example"
},
{
"code": null,
"e": 4168,
"s": 4124,
"text": "Spring Bean Autowire By Constructor Example"
},
{
"code": null,
"e": 4204,
"s": 4168,
"text": "Types of Spring Bean Scopes Example"
},
{
"code": null,
"e": 4240,
"s": 4204,
"text": "Spring Bean Autowire ByName Example"
},
{
"code": null,
"e": 4276,
"s": 4240,
"text": "Spring Bean Autowire ByType Example"
},
{
"code": null,
"e": 4330,
"s": 4276,
"text": "@Component,@Service,@Repository,@Controller in spring"
},
{
"code": null,
"e": 4362,
"s": 4330,
"text": "Repeating Annotations in Java 8"
},
{
"code": null,
"e": 4403,
"s": 4362,
"text": "Spring Collection Map Dependency Example"
},
{
"code": null,
"e": 4453,
"s": 4403,
"text": "How to Get All Spring Beans Details Loaded in ICO"
},
{
"code": null,
"e": 4495,
"s": 4453,
"text": "Spring Collection Dependency List Example"
},
{
"code": null,
"e": 4534,
"s": 4495,
"text": "Spring Boot Lazy Loading Beans Example"
},
{
"code": null,
"e": 4559,
"s": 4534,
"text": "Spring Hibernate Example"
}
] |
Difference between Python iterable and iterator
|
An iterable can be loosely defined as an object which would generate an iterator when passed to in-built method iter(). There are a couple of conditions, for an object to be iterable, the object of the class needs to define two instance mehtod: __len__ and __getitem__. An object which fulfills these conditions when passed to method iter() would generate an iterator.
Letβs understand the below example, to understand the iterable β
string = "Tutorialspoint"
for char in string:
print (char)
T
u
t
o
r
i
a
l
s
p
o
i
n
t
Above the code use the __getitem__(index) method which would return the element at the position specified by index.
So, our above code β
Start with index 0
Call string.__getitem__(index)
IndexError raised? Stop
The run body of the loop
Increment index, revert back to step 2.
Iterators are defined as an object that counts interation via an iternal state variable. The variable, in this case, is NOT set to zero when the iteration crosses the last item, instead, StopIteration() is raised to indicate the end of the iteration. This also means that iterated item will be iterated once only, like in below example β
my_list = ['itemOne', 'TutorialsPoints']
iterators_of_some_list = iter(my_list)
for i in iterators_of_some_list:
print(i)
for j in iterators_of_some_list: # doesn't work
print(j)
#However
for k in my_list:
print(k)
for l in my_list: # it worked
print(l)
itemOne
TutorialsPoints
itemOne
TutorialsPoints
itemOne
TutorialsPoints
Above code holds true because the iter() method on the iterator returns itself (is to remember the current state). So above we have a loop kind of implementation similar to βforβ to terminate it.
|
[
{
"code": null,
"e": 1431,
"s": 1062,
"text": "An iterable can be loosely defined as an object which would generate an iterator when passed to in-built method iter(). There are a couple of conditions, for an object to be iterable, the object of the class needs to define two instance mehtod: __len__ and __getitem__. An object which fulfills these conditions when passed to method iter() would generate an iterator."
},
{
"code": null,
"e": 1496,
"s": 1431,
"text": "Letβs understand the below example, to understand the iterable β"
},
{
"code": null,
"e": 1555,
"s": 1496,
"text": "string = \"Tutorialspoint\"\nfor char in string:\nprint (char)"
},
{
"code": null,
"e": 1583,
"s": 1555,
"text": "T\nu\nt\no\nr\ni\na\nl\ns\np\no\ni\nn\nt"
},
{
"code": null,
"e": 1699,
"s": 1583,
"text": "Above the code use the __getitem__(index) method which would return the element at the position specified by index."
},
{
"code": null,
"e": 1720,
"s": 1699,
"text": "So, our above code β"
},
{
"code": null,
"e": 1739,
"s": 1720,
"text": "Start with index 0"
},
{
"code": null,
"e": 1770,
"s": 1739,
"text": "Call string.__getitem__(index)"
},
{
"code": null,
"e": 1794,
"s": 1770,
"text": "IndexError raised? Stop"
},
{
"code": null,
"e": 1819,
"s": 1794,
"text": "The run body of the loop"
},
{
"code": null,
"e": 1859,
"s": 1819,
"text": "Increment index, revert back to step 2."
},
{
"code": null,
"e": 2197,
"s": 1859,
"text": "Iterators are defined as an object that counts interation via an iternal state variable. The variable, in this case, is NOT set to zero when the iteration crosses the last item, instead, StopIteration() is raised to indicate the end of the iteration. This also means that iterated item will be iterated once only, like in below example β"
},
{
"code": null,
"e": 2463,
"s": 2197,
"text": "my_list = ['itemOne', 'TutorialsPoints']\niterators_of_some_list = iter(my_list)\nfor i in iterators_of_some_list:\n print(i)\nfor j in iterators_of_some_list: # doesn't work\n print(j)\n#However\nfor k in my_list:\n print(k)\nfor l in my_list: # it worked\n print(l)"
},
{
"code": null,
"e": 2535,
"s": 2463,
"text": "itemOne\nTutorialsPoints\nitemOne\nTutorialsPoints\nitemOne\nTutorialsPoints"
},
{
"code": null,
"e": 2731,
"s": 2535,
"text": "Above code holds true because the iter() method on the iterator returns itself (is to remember the current state). So above we have a loop kind of implementation similar to βforβ to terminate it."
}
] |
How to store MongoDB result in an array?
|
To store MongoDB result in an array, use the toArray() method β
var anyVariableName=db.yourCollectionName.find().toArray();
Let us first create a collection with documents β
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"David Miller","CustomerAge":24,"isMarried":false});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd99bd5b50a6c6dd317ad92")
}
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"Sam Williams","CustomerAge":46,"isMarried":true});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd99beab50a6c6dd317ad93")
}
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"Carol Taylor","CustomerAge":23,"isMarried":false});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd99bf9b50a6c6dd317ad94")
}
Following is the query to display all documents from a collection with the help of find() method β
> db.mongoDbResultInArrayDemo.find().pretty();
This will produce the following output β
{
"_id" : ObjectId("5cd99bd5b50a6c6dd317ad92"),
"CustomerName" : "David Miller",
"CustomerAge" : 24,
"isMarried" : false
}
{
"_id" : ObjectId("5cd99beab50a6c6dd317ad93"),
"CustomerName" : "Sam Williams",
"CustomerAge" : 46,
"isMarried" : true
}
{
"_id" : ObjectId("5cd99bf9b50a6c6dd317ad94"),
"CustomerName" : "Carol Taylor",
"CustomerAge" : 23,
"isMarried" : false
}
Following is the query to store MongoDB result in an array β
> var mongoDbResultIntoArray=db.mongoDbResultInArrayDemo.find().toArray();
Let us display the records of above variable β
> mongoDbResultIntoArray
This will produce the following output β
[
{
"_id" : ObjectId("5cd99bd5b50a6c6dd317ad92"),
"CustomerName" : "David Miller",
"CustomerAge" : 24,
"isMarried" : false
},
{
"_id" : ObjectId("5cd99beab50a6c6dd317ad93"),
"CustomerName" : "Sam Williams",
"CustomerAge" : 46,
"isMarried" : true
},
{
"_id" : ObjectId("5cd99bf9b50a6c6dd317ad94"),
"CustomerName" : "Carol Taylor",
"CustomerAge" : 23,
"isMarried" : false
}
]
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To store MongoDB result in an array, use the toArray() method β"
},
{
"code": null,
"e": 1186,
"s": 1126,
"text": "var anyVariableName=db.yourCollectionName.find().toArray();"
},
{
"code": null,
"e": 1236,
"s": 1186,
"text": "Let us first create a collection with documents β"
},
{
"code": null,
"e": 1817,
"s": 1236,
"text": "> db.mongoDbResultInArrayDemo.insertOne({\"CustomerName\":\"David Miller\",\"CustomerAge\":24,\"isMarried\":false});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd99bd5b50a6c6dd317ad92\")\n}\n> db.mongoDbResultInArrayDemo.insertOne({\"CustomerName\":\"Sam Williams\",\"CustomerAge\":46,\"isMarried\":true});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd99beab50a6c6dd317ad93\")\n}\n> db.mongoDbResultInArrayDemo.insertOne({\"CustomerName\":\"Carol Taylor\",\"CustomerAge\":23,\"isMarried\":false});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd99bf9b50a6c6dd317ad94\")\n}"
},
{
"code": null,
"e": 1916,
"s": 1817,
"text": "Following is the query to display all documents from a collection with the help of find() method β"
},
{
"code": null,
"e": 1963,
"s": 1916,
"text": "> db.mongoDbResultInArrayDemo.find().pretty();"
},
{
"code": null,
"e": 2004,
"s": 1963,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2408,
"s": 2004,
"text": "{\n \"_id\" : ObjectId(\"5cd99bd5b50a6c6dd317ad92\"),\n \"CustomerName\" : \"David Miller\",\n \"CustomerAge\" : 24,\n \"isMarried\" : false\n}\n{\n \"_id\" : ObjectId(\"5cd99beab50a6c6dd317ad93\"),\n \"CustomerName\" : \"Sam Williams\",\n \"CustomerAge\" : 46,\n \"isMarried\" : true\n}\n{\n \"_id\" : ObjectId(\"5cd99bf9b50a6c6dd317ad94\"),\n \"CustomerName\" : \"Carol Taylor\",\n \"CustomerAge\" : 23,\n \"isMarried\" : false\n}"
},
{
"code": null,
"e": 2469,
"s": 2408,
"text": "Following is the query to store MongoDB result in an array β"
},
{
"code": null,
"e": 2544,
"s": 2469,
"text": "> var mongoDbResultIntoArray=db.mongoDbResultInArrayDemo.find().toArray();"
},
{
"code": null,
"e": 2591,
"s": 2544,
"text": "Let us display the records of above variable β"
},
{
"code": null,
"e": 2616,
"s": 2591,
"text": "> mongoDbResultIntoArray"
},
{
"code": null,
"e": 2657,
"s": 2616,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 3121,
"s": 2657,
"text": "[\n {\n \"_id\" : ObjectId(\"5cd99bd5b50a6c6dd317ad92\"),\n \"CustomerName\" : \"David Miller\",\n \"CustomerAge\" : 24,\n \"isMarried\" : false\n },\n {\n \"_id\" : ObjectId(\"5cd99beab50a6c6dd317ad93\"),\n \"CustomerName\" : \"Sam Williams\",\n \"CustomerAge\" : 46,\n \"isMarried\" : true\n },\n {\n \"_id\" : ObjectId(\"5cd99bf9b50a6c6dd317ad94\"),\n \"CustomerName\" : \"Carol Taylor\",\n \"CustomerAge\" : 23,\n \"isMarried\" : false\n }\n]"
}
] |
How can we use Python Ternary Operator Without else?
|
If you want to convert a statement like β
if <condition>:
<some-code>
to a single line, You can use the single line if syntax to do so β
if <condition>: <some-code>
Another way to do this is leveraging the short-circuiting and operator like β
<condition> and <some-code>
If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and <some-code> will be evaluated.
|
[
{
"code": null,
"e": 1104,
"s": 1062,
"text": "If you want to convert a statement like β"
},
{
"code": null,
"e": 1135,
"s": 1104,
"text": "if <condition>:\n <some-code>"
},
{
"code": null,
"e": 1202,
"s": 1135,
"text": "to a single line, You can use the single line if syntax to do so β"
},
{
"code": null,
"e": 1230,
"s": 1202,
"text": "if <condition>: <some-code>"
},
{
"code": null,
"e": 1308,
"s": 1230,
"text": "Another way to do this is leveraging the short-circuiting and operator like β"
},
{
"code": null,
"e": 1336,
"s": 1308,
"text": "<condition> and <some-code>"
},
{
"code": null,
"e": 1542,
"s": 1336,
"text": "If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and <some-code> will be evaluated."
}
] |
Install Apache Solr on Windows 10 | Apache Solr 7.5.0 Installation
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Apache Solr is an opensource Java library builds on Lucene which provides indexing, searching and advanced analytic capabilities on data. In this tutorial, we are going to see how to install Apache Solr on Windows 10 operating system and run the basic commands on standalone solr console.
We can freely install the Apache Solr in any system with the minimum system requirements and suitable Java environment. Solr currently supports Linux, MacOS/OS X, and Microsoft Windows operating system. The latest Solr 7.x.x installation requires Java 8+
Step 1: Download the latest Apache Solr version from the official website. For me it is 7.5.0 is the most recent release and I am going with this.
Click on above heightened binary release then it will get automatically download into your machine.
Step 2: Extract the solr-7.5.0.zip into your favorite folder then you can see the following directories.
bin: It contains all the necessary binary scripts, which helps the solr make easier to run.
contrib: Solrβs contrib directory includes add-on plugins for specialized features of Solr.
dist: The dist directory contains the main Solr .jar files.
docs: The docs directory includes a link to online Javadocs for Solr.
example: The example directory includes several types of examples that demonstrate various Solr capabilities.
licenses: The licenses directory includes all of the licenses for 3rd party libraries used by Solr.
server: This directory is where the heart of the Solr application resides.
Step 3: Goto bin directory from command prompt and execute the >solr start command to start Solr instance.
You can notice the above solr console, I started the Solr server on port 8983.
Step 4: Access Apache Solr dashboard from the web browser.
http://localhost:8983/solr
This is the Solr dashboard, where we can see a lot of default configuration details such as solr-spec version, JVM detail, processor, physical, heap memory occupied by solr and etc..
As I highlighted above, solr doesnβt create any default cores. A Solr core is a running instance of the lucene index, that contains all solr configuration details. We have to create solr core to perform operations like indexing and analyzing the data.
A Solr can contain one or more cores if require these cores can communicate with each other.
Below is the syntax for creating core in Apache Solr.
bin/solr create_core [-c name] [-d confdir] [-p port]
Where create_core is used to create solr code, [-c name] giving a name to the core, [-d confdir] specifying configuration directory location to store the core in standalone mode and [-p port] is used to providing the port for the specific core.
Here confdir and port are optional if you donβt specify these two values, solr assigns it to the default values as $SOLR_HOME as confdir and 8983 as the port.
Example:
Creating sample-items Solr core with default confdir and port.
bin/solr create_core -c sample-items
Output:
Refresh the Solr dashboard on the web browser, there you can see the created solr core.
Likewise, you can create your solr cores with optional parameters like confdir and port.
bin/solr create_core -c sample-items2 -d myconfig -p 8989
We can delete the solr core using delete command, letβs delete the solr-items core.
>solr delete -c sample-items
Solr Installation guide
Apache Solr Reference Guide
Apache Lucene
Happy Learning π
Install Docker Desktop on Windows 10
Install Mysql on Windows 10 Step by Step
How to Install Git windows 10 Operating System
How to install Android SDK Windows 10 Manual Process
Apache Solr- Delete Documents from Solr using SolrJ
Apache Solr β How to Add Documents to Solr using SolrJ
Install Apache Kafka on Windows 10
How to install Apache Kafka on Ubuntu 18.04
How to Install Ant on Windows 10
How install Python on Windows 10
How to install Elasticsearch on Windows 10
How to install PuTTY on windows 10
How to install RabbitMQ on Windows 10
How to install Gradle on Windows 10
How to install SOAPUI on Windows 10
Install Docker Desktop on Windows 10
Install Mysql on Windows 10 Step by Step
How to Install Git windows 10 Operating System
How to install Android SDK Windows 10 Manual Process
Apache Solr- Delete Documents from Solr using SolrJ
Apache Solr β How to Add Documents to Solr using SolrJ
Install Apache Kafka on Windows 10
How to install Apache Kafka on Ubuntu 18.04
How to Install Ant on Windows 10
How install Python on Windows 10
How to install Elasticsearch on Windows 10
How to install PuTTY on windows 10
How to install RabbitMQ on Windows 10
How to install Gradle on Windows 10
How to install SOAPUI on Windows 10
Ashan
July 3, 2019 at 6:13 pm - Reply
Thanks
Ashan
July 3, 2019 at 6:13 pm - Reply
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 687,
"s": 398,
"text": "Apache Solr is an opensource Java library builds on Lucene which provides indexing, searching and advanced analytic capabilities on data. In this tutorial, we are going to see how to install Apache Solr on Windows 10 operating system and run the basic commands on standalone solr console."
},
{
"code": null,
"e": 942,
"s": 687,
"text": "We can freely install the Apache Solr in any system with the minimum system requirements and suitable Java environment. Solr currently supports Linux, MacOS/OS X, and Microsoft Windows operating system. The latest Solr 7.x.x installation requires Java 8+"
},
{
"code": null,
"e": 1089,
"s": 942,
"text": "Step 1: Download the latest Apache Solr version from the official website. For me it is 7.5.0 is the most recent release and I am going with this."
},
{
"code": null,
"e": 1191,
"s": 1091,
"text": "Click on above heightened binary release then it will get automatically download into your machine."
},
{
"code": null,
"e": 1296,
"s": 1191,
"text": "Step 2: Extract the solr-7.5.0.zip into your favorite folder then you can see the following directories."
},
{
"code": null,
"e": 1388,
"s": 1296,
"text": "bin: It contains all the necessary binary scripts, which helps the solr make easier to run."
},
{
"code": null,
"e": 1480,
"s": 1388,
"text": "contrib: Solrβs contrib directory includes add-on plugins for specialized features of Solr."
},
{
"code": null,
"e": 1540,
"s": 1480,
"text": "dist: The dist directory contains the main Solr .jar files."
},
{
"code": null,
"e": 1610,
"s": 1540,
"text": "docs: The docs directory includes a link to online Javadocs for Solr."
},
{
"code": null,
"e": 1720,
"s": 1610,
"text": "example: The example directory includes several types of examples that demonstrate various Solr capabilities."
},
{
"code": null,
"e": 1820,
"s": 1720,
"text": "licenses: The licenses directory includes all of the licenses for 3rd party libraries used by Solr."
},
{
"code": null,
"e": 1895,
"s": 1820,
"text": "server: This directory is where the heart of the Solr application resides."
},
{
"code": null,
"e": 2002,
"s": 1895,
"text": "Step 3: Goto bin directory from command prompt and execute the >solr start command to start Solr instance."
},
{
"code": null,
"e": 2081,
"s": 2002,
"text": "You can notice the above solr console, I started the Solr server on port 8983."
},
{
"code": null,
"e": 2140,
"s": 2081,
"text": "Step 4: Access Apache Solr dashboard from the web browser."
},
{
"code": null,
"e": 2167,
"s": 2140,
"text": "http://localhost:8983/solr"
},
{
"code": null,
"e": 2350,
"s": 2167,
"text": "This is the Solr dashboard, where we can see a lot of default configuration details such as solr-spec version, JVM detail, processor, physical, heap memory occupied by solr and etc.."
},
{
"code": null,
"e": 2604,
"s": 2352,
"text": "As I highlighted above, solr doesnβt create any default cores. A Solr core is a running instance of the lucene index, that contains all solr configuration details. We have to create solr core to perform operations like indexing and analyzing the data."
},
{
"code": null,
"e": 2697,
"s": 2604,
"text": "A Solr can contain one or more cores if require these cores can communicate with each other."
},
{
"code": null,
"e": 2751,
"s": 2697,
"text": "Below is the syntax for creating core in Apache Solr."
},
{
"code": null,
"e": 2805,
"s": 2751,
"text": "bin/solr create_core [-c name] [-d confdir] [-p port]"
},
{
"code": null,
"e": 3050,
"s": 2805,
"text": "Where create_core is used to create solr code, [-c name] giving a name to the core, [-d confdir] specifying configuration directory location to store the core in standalone mode and [-p port] is used to providing the port for the specific core."
},
{
"code": null,
"e": 3209,
"s": 3050,
"text": "Here confdir and port are optional if you donβt specify these two values, solr assigns it to the default values as $SOLR_HOME as confdir and 8983 as the port."
},
{
"code": null,
"e": 3218,
"s": 3209,
"text": "Example:"
},
{
"code": null,
"e": 3281,
"s": 3218,
"text": "Creating sample-items Solr core with default confdir and port."
},
{
"code": null,
"e": 3318,
"s": 3281,
"text": "bin/solr create_core -c sample-items"
},
{
"code": null,
"e": 3326,
"s": 3318,
"text": "Output:"
},
{
"code": null,
"e": 3414,
"s": 3326,
"text": "Refresh the Solr dashboard on the web browser, there you can see the created solr core."
},
{
"code": null,
"e": 3503,
"s": 3414,
"text": "Likewise, you can create your solr cores with optional parameters like confdir and port."
},
{
"code": null,
"e": 3561,
"s": 3503,
"text": "bin/solr create_core -c sample-items2 -d myconfig -p 8989"
},
{
"code": null,
"e": 3645,
"s": 3561,
"text": "We can delete the solr core using delete command, letβs delete the solr-items core."
},
{
"code": null,
"e": 3674,
"s": 3645,
"text": ">solr delete -c sample-items"
},
{
"code": null,
"e": 3698,
"s": 3674,
"text": "Solr Installation guide"
},
{
"code": null,
"e": 3726,
"s": 3698,
"text": "Apache Solr Reference Guide"
},
{
"code": null,
"e": 3740,
"s": 3726,
"text": "Apache Lucene"
},
{
"code": null,
"e": 3757,
"s": 3740,
"text": "Happy Learning π"
},
{
"code": null,
"e": 4377,
"s": 3757,
"text": "\nInstall Docker Desktop on Windows 10\nInstall Mysql on Windows 10 Step by Step\nHow to Install Git windows 10 Operating System\nHow to install Android SDK Windows 10 Manual Process\nApache Solr- Delete Documents from Solr using SolrJ\nApache Solr β How to Add Documents to Solr using SolrJ\nInstall Apache Kafka on Windows 10\nHow to install Apache Kafka on Ubuntu 18.04\nHow to Install Ant on Windows 10\nHow install Python on Windows 10\nHow to install Elasticsearch on Windows 10\nHow to install PuTTY on windows 10\nHow to install RabbitMQ on Windows 10\nHow to install Gradle on Windows 10\nHow to install SOAPUI on Windows 10\n"
},
{
"code": null,
"e": 4414,
"s": 4377,
"text": "Install Docker Desktop on Windows 10"
},
{
"code": null,
"e": 4455,
"s": 4414,
"text": "Install Mysql on Windows 10 Step by Step"
},
{
"code": null,
"e": 4502,
"s": 4455,
"text": "How to Install Git windows 10 Operating System"
},
{
"code": null,
"e": 4555,
"s": 4502,
"text": "How to install Android SDK Windows 10 Manual Process"
},
{
"code": null,
"e": 4607,
"s": 4555,
"text": "Apache Solr- Delete Documents from Solr using SolrJ"
},
{
"code": null,
"e": 4662,
"s": 4607,
"text": "Apache Solr β How to Add Documents to Solr using SolrJ"
},
{
"code": null,
"e": 4697,
"s": 4662,
"text": "Install Apache Kafka on Windows 10"
},
{
"code": null,
"e": 4741,
"s": 4697,
"text": "How to install Apache Kafka on Ubuntu 18.04"
},
{
"code": null,
"e": 4774,
"s": 4741,
"text": "How to Install Ant on Windows 10"
},
{
"code": null,
"e": 4807,
"s": 4774,
"text": "How install Python on Windows 10"
},
{
"code": null,
"e": 4850,
"s": 4807,
"text": "How to install Elasticsearch on Windows 10"
},
{
"code": null,
"e": 4885,
"s": 4850,
"text": "How to install PuTTY on windows 10"
},
{
"code": null,
"e": 4923,
"s": 4885,
"text": "How to install RabbitMQ on Windows 10"
},
{
"code": null,
"e": 4959,
"s": 4923,
"text": "How to install Gradle on Windows 10"
},
{
"code": null,
"e": 4995,
"s": 4959,
"text": "How to install SOAPUI on Windows 10"
},
{
"code": null,
"e": 5053,
"s": 4995,
"text": "\n\n\n\n\n\nAshan\nJuly 3, 2019 at 6:13 pm - Reply \n\nThanks\n\n\n\n\n"
}
] |
Pushdown Automata Introduction
|
A pushdown automaton is a way to implement a context-free grammar in a similar way we design DFA for a regular grammar. A DFA can remember a finite amount of information, but a PDA can remember an infinite amount of information.
Basically a pushdown automaton is β
"Finite state machine" + "a stack"
A pushdown automaton has three components β
an input tape,
a control unit, and
a stack with infinite size.
The stack head scans the top symbol of the stack.
A stack does two operations β
Push β a new symbol is added at the top.
Push β a new symbol is added at the top.
Pop β the top symbol is read and removed.
Pop β the top symbol is read and removed.
A PDA may or may not read an input symbol, but it has to read the top of the stack in every transition.
A PDA can be formally described as a 7-tuple (Q, β, S, Ξ΄, q0, I, F) β
Q is the finite number of states
Q is the finite number of states
β is input alphabet
β is input alphabet
S is stack symbols
S is stack symbols
Ξ΄ is the transition function: Q Γ (β βͺ {Ξ΅}) Γ S Γ Q Γ S*
Ξ΄ is the transition function: Q Γ (β βͺ {Ξ΅}) Γ S Γ Q Γ S*
q0 is the initial state (q0 β Q)
q0 is the initial state (q0 β Q)
I is the initial stack top symbol (I β S)
I is the initial stack top symbol (I β S)
F is a set of accepting states (F β Q)
F is a set of accepting states (F β Q)
The following diagram shows a transition in a PDA from a state q1 to state q2, labeled as a,b β c β
This means at state q1, if we encounter an input string βaβ and top symbol of the stack is βbβ, then we pop βbβ, push βcβ on top of the stack and move to state q2.
The instantaneous description (ID) of a PDA is represented by a triplet (q, w, s) where
q is the state
q is the state
w is unconsumed input
w is unconsumed input
s is the stack contents
s is the stack contents
The "turnstile" notation is used for connecting pairs of ID's that represent one or many moves of a PDA. The process of transition is denoted by the turnstile symbol "β’".
Consider a PDA (Q, β, S, Ξ΄, q0, I, F). A transition can be mathematically represented by the following turnstile notation β
(p, aw, TΞ²) β’ (q, w, Ξ±b)
This implies that while taking a transition from state p to state q, the input symbol βaβ is consumed, and the top of the stack βTβ is replaced by a new string βΞ±β.
Note β If we want zero or more moves of a PDA, we have to use the symbol (β’*) for it.
98 Lectures
10 hours
Arnab Chakraborty
15 Lectures
2 hours
Anchal Kamra
16 Lectures
1.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2912,
"s": 2683,
"text": "A pushdown automaton is a way to implement a context-free grammar in a similar way we design DFA for a regular grammar. A DFA can remember a finite amount of information, but a PDA can remember an infinite amount of information."
},
{
"code": null,
"e": 2948,
"s": 2912,
"text": "Basically a pushdown automaton is β"
},
{
"code": null,
"e": 2983,
"s": 2948,
"text": "\"Finite state machine\" + \"a stack\""
},
{
"code": null,
"e": 3027,
"s": 2983,
"text": "A pushdown automaton has three components β"
},
{
"code": null,
"e": 3042,
"s": 3027,
"text": "an input tape,"
},
{
"code": null,
"e": 3062,
"s": 3042,
"text": "a control unit, and"
},
{
"code": null,
"e": 3090,
"s": 3062,
"text": "a stack with infinite size."
},
{
"code": null,
"e": 3140,
"s": 3090,
"text": "The stack head scans the top symbol of the stack."
},
{
"code": null,
"e": 3170,
"s": 3140,
"text": "A stack does two operations β"
},
{
"code": null,
"e": 3211,
"s": 3170,
"text": "Push β a new symbol is added at the top."
},
{
"code": null,
"e": 3252,
"s": 3211,
"text": "Push β a new symbol is added at the top."
},
{
"code": null,
"e": 3294,
"s": 3252,
"text": "Pop β the top symbol is read and removed."
},
{
"code": null,
"e": 3336,
"s": 3294,
"text": "Pop β the top symbol is read and removed."
},
{
"code": null,
"e": 3440,
"s": 3336,
"text": "A PDA may or may not read an input symbol, but it has to read the top of the stack in every transition."
},
{
"code": null,
"e": 3510,
"s": 3440,
"text": "A PDA can be formally described as a 7-tuple (Q, β, S, Ξ΄, q0, I, F) β"
},
{
"code": null,
"e": 3543,
"s": 3510,
"text": "Q is the finite number of states"
},
{
"code": null,
"e": 3576,
"s": 3543,
"text": "Q is the finite number of states"
},
{
"code": null,
"e": 3596,
"s": 3576,
"text": "β is input alphabet"
},
{
"code": null,
"e": 3616,
"s": 3596,
"text": "β is input alphabet"
},
{
"code": null,
"e": 3635,
"s": 3616,
"text": "S is stack symbols"
},
{
"code": null,
"e": 3654,
"s": 3635,
"text": "S is stack symbols"
},
{
"code": null,
"e": 3711,
"s": 3654,
"text": "Ξ΄ is the transition function: Q Γ (β βͺ {Ξ΅}) Γ S Γ Q Γ S*"
},
{
"code": null,
"e": 3768,
"s": 3711,
"text": "Ξ΄ is the transition function: Q Γ (β βͺ {Ξ΅}) Γ S Γ Q Γ S*"
},
{
"code": null,
"e": 3801,
"s": 3768,
"text": "q0 is the initial state (q0 β Q)"
},
{
"code": null,
"e": 3834,
"s": 3801,
"text": "q0 is the initial state (q0 β Q)"
},
{
"code": null,
"e": 3876,
"s": 3834,
"text": "I is the initial stack top symbol (I β S)"
},
{
"code": null,
"e": 3918,
"s": 3876,
"text": "I is the initial stack top symbol (I β S)"
},
{
"code": null,
"e": 3957,
"s": 3918,
"text": "F is a set of accepting states (F β Q)"
},
{
"code": null,
"e": 3996,
"s": 3957,
"text": "F is a set of accepting states (F β Q)"
},
{
"code": null,
"e": 4096,
"s": 3996,
"text": "The following diagram shows a transition in a PDA from a state q1 to state q2, labeled as a,b β c β"
},
{
"code": null,
"e": 4260,
"s": 4096,
"text": "This means at state q1, if we encounter an input string βaβ and top symbol of the stack is βbβ, then we pop βbβ, push βcβ on top of the stack and move to state q2."
},
{
"code": null,
"e": 4348,
"s": 4260,
"text": "The instantaneous description (ID) of a PDA is represented by a triplet (q, w, s) where"
},
{
"code": null,
"e": 4363,
"s": 4348,
"text": "q is the state"
},
{
"code": null,
"e": 4378,
"s": 4363,
"text": "q is the state"
},
{
"code": null,
"e": 4400,
"s": 4378,
"text": "w is unconsumed input"
},
{
"code": null,
"e": 4422,
"s": 4400,
"text": "w is unconsumed input"
},
{
"code": null,
"e": 4446,
"s": 4422,
"text": "s is the stack contents"
},
{
"code": null,
"e": 4470,
"s": 4446,
"text": "s is the stack contents"
},
{
"code": null,
"e": 4641,
"s": 4470,
"text": "The \"turnstile\" notation is used for connecting pairs of ID's that represent one or many moves of a PDA. The process of transition is denoted by the turnstile symbol \"β’\"."
},
{
"code": null,
"e": 4765,
"s": 4641,
"text": "Consider a PDA (Q, β, S, Ξ΄, q0, I, F). A transition can be mathematically represented by the following turnstile notation β"
},
{
"code": null,
"e": 4791,
"s": 4765,
"text": "(p, aw, TΞ²) β’ (q, w, Ξ±b)\n"
},
{
"code": null,
"e": 4956,
"s": 4791,
"text": "This implies that while taking a transition from state p to state q, the input symbol βaβ is consumed, and the top of the stack βTβ is replaced by a new string βΞ±β."
},
{
"code": null,
"e": 5042,
"s": 4956,
"text": "Note β If we want zero or more moves of a PDA, we have to use the symbol (β’*) for it."
},
{
"code": null,
"e": 5076,
"s": 5042,
"text": "\n 98 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5095,
"s": 5076,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5128,
"s": 5095,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5142,
"s": 5128,
"text": " Anchal Kamra"
},
{
"code": null,
"e": 5177,
"s": 5142,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5195,
"s": 5177,
"text": " Packt Publishing"
},
{
"code": null,
"e": 5202,
"s": 5195,
"text": " Print"
},
{
"code": null,
"e": 5213,
"s": 5202,
"text": " Add Notes"
}
] |
Java program to transpose a matrix.
|
Following is the required program.
Live Demo
public class Tester {
public static void main(String args[]) {
int a[][] = { { 1, 3, 4 }, { 2, 4, 3 }, { 3, 4, 5 } };
int t[][] = new int[3][3];
// transpose the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
t[i][j] = a[j][i];
}
}
System.out.println("Original Matrix:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println("Transposed Matrix:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(t[i][j] + " ");
}
System.out.println();
}
}
}
Original Matrix:
1 3 4
2 4 3
3 4 5
Transposed Matrix:
1 2 3
3 4 4
4 3 5
|
[
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Following is the required program."
},
{
"code": null,
"e": 1107,
"s": 1097,
"text": "Live Demo"
},
{
"code": null,
"e": 1863,
"s": 1107,
"text": "public class Tester {\n public static void main(String args[]) {\n int a[][] = { { 1, 3, 4 }, { 2, 4, 3 }, { 3, 4, 5 } };\n int t[][] = new int[3][3];\n // transpose the matrix\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n t[i][j] = a[j][i];\n }\n }\n System.out.println(\"Original Matrix:\");\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n System.out.print(a[i][j] + \" \");\n }\n System.out.println();\n }\n System.out.println(\"Transposed Matrix:\");\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n System.out.print(t[i][j] + \" \");\n }\n System.out.println();\n }\n }\n}"
},
{
"code": null,
"e": 1935,
"s": 1863,
"text": "Original Matrix:\n1 3 4\n2 4 3\n3 4 5\nTransposed Matrix:\n1 2 3\n3 4 4\n4 3 5"
}
] |
Replace Multiple of 3 and 5 With Fizz, Buzz in Python
|
Suppose we have a number n. We have to find a string that is representing all numbers from 1
to n, but we have to follow some rules.
When the number is divisible by 3, put Fizz instead of the number
When the number is divisible by 3, put Fizz instead of the number
When the number is divisible by 5, put Buzz instead of the number
When the number is divisible by 5, put Buzz instead of the number
When the number is divisible by 3 and 5 both, put FizzBuzz instead of the number
When the number is divisible by 3 and 5 both, put FizzBuzz instead of the number
To solve this, we will follow these steps β
For all number from 1 to n,if number is divisible by 3 and 5 both, put βFizzBuzzβotherwise when number is divisible by 3, put βFizzβotherwise when number is divisible by 5, put βBuzzβotherwise write the number as string
if number is divisible by 3 and 5 both, put βFizzBuzzβ
otherwise when number is divisible by 3, put βFizzβ
otherwise when number is divisible by 5, put βBuzzβ
otherwise write the number as string
Let us see the following implementation to get better understanding β
Live Demo
class Solution(object):
def fizzBuzz(self, n):
result = []
for i in range(1,n+1):
if i% 3== 0 and i%5==0:
result.append("FizzBuzz")
elif i %3==0:
result.append("Fizz")
elif i% 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
ob1 = Solution()
print(ob1.fizzBuzz(15))
15
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "Suppose we have a number n. We have to find a string that is representing all numbers from 1\nto n, but we have to follow some rules."
},
{
"code": null,
"e": 1261,
"s": 1195,
"text": "When the number is divisible by 3, put Fizz instead of the number"
},
{
"code": null,
"e": 1327,
"s": 1261,
"text": "When the number is divisible by 3, put Fizz instead of the number"
},
{
"code": null,
"e": 1393,
"s": 1327,
"text": "When the number is divisible by 5, put Buzz instead of the number"
},
{
"code": null,
"e": 1459,
"s": 1393,
"text": "When the number is divisible by 5, put Buzz instead of the number"
},
{
"code": null,
"e": 1540,
"s": 1459,
"text": "When the number is divisible by 3 and 5 both, put FizzBuzz instead of the number"
},
{
"code": null,
"e": 1621,
"s": 1540,
"text": "When the number is divisible by 3 and 5 both, put FizzBuzz instead of the number"
},
{
"code": null,
"e": 1665,
"s": 1621,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1885,
"s": 1665,
"text": "For all number from 1 to n,if number is divisible by 3 and 5 both, put βFizzBuzzβotherwise when number is divisible by 3, put βFizzβotherwise when number is divisible by 5, put βBuzzβotherwise write the number as string"
},
{
"code": null,
"e": 1940,
"s": 1885,
"text": "if number is divisible by 3 and 5 both, put βFizzBuzzβ"
},
{
"code": null,
"e": 1992,
"s": 1940,
"text": "otherwise when number is divisible by 3, put βFizzβ"
},
{
"code": null,
"e": 2044,
"s": 1992,
"text": "otherwise when number is divisible by 5, put βBuzzβ"
},
{
"code": null,
"e": 2081,
"s": 2044,
"text": "otherwise write the number as string"
},
{
"code": null,
"e": 2151,
"s": 2081,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 2162,
"s": 2151,
"text": " Live Demo"
},
{
"code": null,
"e": 2556,
"s": 2162,
"text": "class Solution(object):\n def fizzBuzz(self, n):\n result = []\n for i in range(1,n+1):\n if i% 3== 0 and i%5==0:\n result.append(\"FizzBuzz\")\n elif i %3==0:\n result.append(\"Fizz\")\n elif i% 5 == 0:\n result.append(\"Buzz\")\n else:\n result.append(str(i))\n return result\nob1 = Solution()\nprint(ob1.fizzBuzz(15))"
},
{
"code": null,
"e": 2559,
"s": 2556,
"text": "15"
},
{
"code": null,
"e": 2663,
"s": 2559,
"text": "['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']"
}
] |
Apache Presto - Installation
|
This chapter will explain how to install Presto on your machine. Letβs go through the basic requirements of Presto,
Linux or Mac OS
Java version 8
Now, letβs continue the following steps to install Presto on your machine.
Hopefully, you have already installed Java version 8 on your machine right now, so you just verify it using the following command.
$ java -version
If Java is successfully installed on your machine, you could see the version of installed Java. If Java is not installed, follow the subsequent steps to install Java 8 on your machine.
Download JDK. Download the latest version of JDK by visiting the following link.
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
The latest version is JDK 8u 92 and the file is βjdk-8u92-linux-x64.tar.gzβ. Please download the file on your machine.
After that, extract the files and move to the specific directory.
Then set Java alternatives. Finally Java will be installed on your machine.
Download the latest version of Presto by visiting the following link,
https://repo1.maven.org/maven2/com/facebook/presto/presto-server/0.149/
Now the latest version of βpresto-server-0.149.tar.gzβ will be downloaded on your machine.
Extract the tar file using the following command β
$ tar -zxf presto-server-0.149.tar.gz
$ cd presto-server-0.149
Create a data directory outside the installation directory, which will be used for storing logs, metadata, etc., so that it is to be easily preserved when upgrading Presto. It is defined using the following code β
$ cd
$ mkdir data
To view the path where it is located, use the command βpwdβ. This location will be assigned in the next node.properties file.
Create an etc directory inside Presto installation directory using the following code β
$ cd presto-server-0.149
$ mkdir etc
This directory will hold configuration files. Letβs create each file one by one.
Presto node properties file contains environmental configuration specific to each node. It is created inside etc directory (etc/node.properties) using the following code β
$ cd etc
$ vi node.properties
node.environment = production
node.id = ffffffff-ffff-ffff-ffff-ffffffffffff
node.data-dir = /Users/../workspace/Presto
After making all the changes, save the file, and quit the terminal. Here node.data is the location path of the above created data directory. node.id represents the unique identifier for each node.
Create a file βjvm.configβ inside etc directory (etc/jvm.config). This file contains a list of command line options used for launching the Java Virtual Machine.
$ cd etc
$ vi jvm.config
-server
-Xmx16G
-XX:+UseG1GC
-XX:G1HeapRegionSize = 32M
-XX:+UseGCOverheadLimit
-XX:+ExplicitGCInvokesConcurrent
-XX:+HeapDumpOnOutOfMemoryError
-XX:OnOutOfMemoryError = kill -9 %p
After making all the changes, save the file, and quit the terminal.
Create a file βconfig.propertiesβ inside etc directory(etc/config.properties). This file contains the configuration of Presto server. If you are setting up a single machine for testing, Presto server can function only as the coordination process as defined using the following code β
$ cd etc
$ vi config.properties
coordinator = true
node-scheduler.include-coordinator = true
http-server.http.port = 8080
query.max-memory = 5GB
query.max-memory-per-node = 1GB
discovery-server.enabled = true
discovery.uri = http://localhost:8080
Here,
coordinator β master node.
coordinator β master node.
node-scheduler.include-coordinator β Allows scheduling work on the coordinator.
node-scheduler.include-coordinator β Allows scheduling work on the coordinator.
http-server.http.port β Specifies the port for the HTTP server.
http-server.http.port β Specifies the port for the HTTP server.
query.max-memory=5GB β The maximum amount of distributed memory.
query.max-memory=5GB β The maximum amount of distributed memory.
query.max-memory-per-node=1GB β The maximum amount of memory per node.
query.max-memory-per-node=1GB β The maximum amount of memory per node.
discovery-server.enabled β Presto uses the Discovery service to find all the nodes in the cluster.
discovery-server.enabled β Presto uses the Discovery service to find all the nodes in the cluster.
discovery.uri β he URI to the Discovery server.
discovery.uri β he URI to the Discovery server.
If you are setting up multiple machine Presto server, Presto will function as both coordination and worker process. Use this configuration setting to test Presto server on multiple machines.
$ cd etc
$ vi config.properties
coordinator = true
node-scheduler.include-coordinator = false
http-server.http.port = 8080
query.max-memory = 50GB
query.max-memory-per-node = 1GB
discovery-server.enabled = true
discovery.uri = http://localhost:8080
$ cd etc
$ vi config.properties
coordinator = false
http-server.http.port = 8080
query.max-memory = 50GB
query.max-memory-per-node = 1GB
discovery.uri = http://localhost:8080
Create a file βlog.propertiesβ inside etc directory(etc/log.properties). This file contains minimum log level for named logger hierarchies. It is defined using the following code β
$ cd etc
$ vi log.properties
com.facebook.presto = INFO
Save the file and quit the terminal. Here, four log levels are used such as DEBUG, INFO, WARN and ERROR. Default log level is INFO.
Create a directory βcatalogβ inside etc directory(etc/catalog). This will be used for mounting data. For example, create etc/catalog/jmx.properties with the following contents to mount the jmx connector as the jmx catalog β
$ cd etc
$ mkdir catalog
$ cd catalog
$ vi jmx.properties
connector.name = jmx
Presto can be started using the following command,
$ bin/launcher start
Then you will see the response similar to this,
Started as 840
To launch Presto server, use the following command β
$ bin/launcher run
After successfully launching Presto server, you can find log files in βvar/logβ directory.
launcher.log β This log is created by the launcher and is connected to the stdout and stderr streams of the server.
launcher.log β This log is created by the launcher and is connected to the stdout and stderr streams of the server.
server.log β This is the main log file used by Presto.
server.log β This is the main log file used by Presto.
http-request.log β HTTP request received by the server.
http-request.log β HTTP request received by the server.
As of now, you have successfully installed Presto configuration settings on your machine. Letβs continue the steps to install Presto CLI.
The Presto CLI provides a terminal-based interactive shell for running queries.
Download the Presto CLI by visiting the following link,
https://repo1.maven.org/maven2/com/facebook/presto/presto-cli/0.149/
Now βpresto-cli-0.149-executable.jarβ will be installed on your machine.
After downloading the presto-cli, copy it to the location which you want to run it from. This location may be any node that has network access to the coordinator. First change the name of the Jar file to Presto. Then make it executable with chmod + x command using the following code β
$ mv presto-cli-0.149-executable.jar presto
$ chmod +x presto
Now execute CLI using the following command,
./presto --server localhost:8080 --catalog jmx --schema default
Here jmx(Java Management Extension) refers to catalog and default referes to schema.
You will see the following response,
presto:default>
Now type βjpsβ command on your terminal and you will see the running daemons.
After having performed all the executions, you can stop the presto server using the following command β
$ bin/launcher stop
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": 2122,
"s": 2006,
"text": "This chapter will explain how to install Presto on your machine. Letβs go through the basic requirements of Presto,"
},
{
"code": null,
"e": 2138,
"s": 2122,
"text": "Linux or Mac OS"
},
{
"code": null,
"e": 2153,
"s": 2138,
"text": "Java version 8"
},
{
"code": null,
"e": 2228,
"s": 2153,
"text": "Now, letβs continue the following steps to install Presto on your machine."
},
{
"code": null,
"e": 2359,
"s": 2228,
"text": "Hopefully, you have already installed Java version 8 on your machine right now, so you just verify it using the following command."
},
{
"code": null,
"e": 2377,
"s": 2359,
"text": "$ java -version \n"
},
{
"code": null,
"e": 2562,
"s": 2377,
"text": "If Java is successfully installed on your machine, you could see the version of installed Java. If Java is not installed, follow the subsequent steps to install Java 8 on your machine."
},
{
"code": null,
"e": 2643,
"s": 2562,
"text": "Download JDK. Download the latest version of JDK by visiting the following link."
},
{
"code": null,
"e": 2727,
"s": 2643,
"text": "http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html"
},
{
"code": null,
"e": 2846,
"s": 2727,
"text": "The latest version is JDK 8u 92 and the file is βjdk-8u92-linux-x64.tar.gzβ. Please download the file on your machine."
},
{
"code": null,
"e": 2912,
"s": 2846,
"text": "After that, extract the files and move to the specific directory."
},
{
"code": null,
"e": 2988,
"s": 2912,
"text": "Then set Java alternatives. Finally Java will be installed on your machine."
},
{
"code": null,
"e": 3058,
"s": 2988,
"text": "Download the latest version of Presto by visiting the following link,"
},
{
"code": null,
"e": 3130,
"s": 3058,
"text": "https://repo1.maven.org/maven2/com/facebook/presto/presto-server/0.149/"
},
{
"code": null,
"e": 3221,
"s": 3130,
"text": "Now the latest version of βpresto-server-0.149.tar.gzβ will be downloaded on your machine."
},
{
"code": null,
"e": 3272,
"s": 3221,
"text": "Extract the tar file using the following command β"
},
{
"code": null,
"e": 3340,
"s": 3272,
"text": "$ tar -zxf presto-server-0.149.tar.gz \n$ cd presto-server-0.149 \n"
},
{
"code": null,
"e": 3554,
"s": 3340,
"text": "Create a data directory outside the installation directory, which will be used for storing logs, metadata, etc., so that it is to be easily preserved when upgrading Presto. It is defined using the following code β"
},
{
"code": null,
"e": 3575,
"s": 3554,
"text": "$ cd \n$ mkdir data\n"
},
{
"code": null,
"e": 3701,
"s": 3575,
"text": "To view the path where it is located, use the command βpwdβ. This location will be assigned in the next node.properties file."
},
{
"code": null,
"e": 3789,
"s": 3701,
"text": "Create an etc directory inside Presto installation directory using the following code β"
},
{
"code": null,
"e": 3828,
"s": 3789,
"text": "$ cd presto-server-0.149 \n$ mkdir etc\n"
},
{
"code": null,
"e": 3909,
"s": 3828,
"text": "This directory will hold configuration files. Letβs create each file one by one."
},
{
"code": null,
"e": 4081,
"s": 3909,
"text": "Presto node properties file contains environmental configuration specific to each node. It is created inside etc directory (etc/node.properties) using the following code β"
},
{
"code": null,
"e": 4238,
"s": 4081,
"text": "$ cd etc \n$ vi node.properties \n\nnode.environment = production \nnode.id = ffffffff-ffff-ffff-ffff-ffffffffffff \nnode.data-dir = /Users/../workspace/Presto\n"
},
{
"code": null,
"e": 4435,
"s": 4238,
"text": "After making all the changes, save the file, and quit the terminal. Here node.data is the location path of the above created data directory. node.id represents the unique identifier for each node."
},
{
"code": null,
"e": 4596,
"s": 4435,
"text": "Create a file βjvm.configβ inside etc directory (etc/jvm.config). This file contains a list of command line options used for launching the Java Virtual Machine."
},
{
"code": null,
"e": 4815,
"s": 4596,
"text": "$ cd etc \n$ vi jvm.config \n\n-server \n-Xmx16G \n-XX:+UseG1GC \n-XX:G1HeapRegionSize = 32M \n-XX:+UseGCOverheadLimit \n-XX:+ExplicitGCInvokesConcurrent \n-XX:+HeapDumpOnOutOfMemoryError \n-XX:OnOutOfMemoryError = kill -9 %p \n"
},
{
"code": null,
"e": 4883,
"s": 4815,
"text": "After making all the changes, save the file, and quit the terminal."
},
{
"code": null,
"e": 5167,
"s": 4883,
"text": "Create a file βconfig.propertiesβ inside etc directory(etc/config.properties). This file contains the configuration of Presto server. If you are setting up a single machine for testing, Presto server can function only as the coordination process as defined using the following code β"
},
{
"code": null,
"e": 5425,
"s": 5167,
"text": "$ cd etc \n$ vi config.properties \n\ncoordinator = true \nnode-scheduler.include-coordinator = true \nhttp-server.http.port = 8080 \nquery.max-memory = 5GB \nquery.max-memory-per-node = 1GB \ndiscovery-server.enabled = true \ndiscovery.uri = http://localhost:8080\n"
},
{
"code": null,
"e": 5431,
"s": 5425,
"text": "Here,"
},
{
"code": null,
"e": 5458,
"s": 5431,
"text": "coordinator β master node."
},
{
"code": null,
"e": 5485,
"s": 5458,
"text": "coordinator β master node."
},
{
"code": null,
"e": 5565,
"s": 5485,
"text": "node-scheduler.include-coordinator β Allows scheduling work on the coordinator."
},
{
"code": null,
"e": 5645,
"s": 5565,
"text": "node-scheduler.include-coordinator β Allows scheduling work on the coordinator."
},
{
"code": null,
"e": 5709,
"s": 5645,
"text": "http-server.http.port β Specifies the port for the HTTP server."
},
{
"code": null,
"e": 5773,
"s": 5709,
"text": "http-server.http.port β Specifies the port for the HTTP server."
},
{
"code": null,
"e": 5838,
"s": 5773,
"text": "query.max-memory=5GB β The maximum amount of distributed memory."
},
{
"code": null,
"e": 5903,
"s": 5838,
"text": "query.max-memory=5GB β The maximum amount of distributed memory."
},
{
"code": null,
"e": 5974,
"s": 5903,
"text": "query.max-memory-per-node=1GB β The maximum amount of memory per node."
},
{
"code": null,
"e": 6045,
"s": 5974,
"text": "query.max-memory-per-node=1GB β The maximum amount of memory per node."
},
{
"code": null,
"e": 6144,
"s": 6045,
"text": "discovery-server.enabled β Presto uses the Discovery service to find all the nodes in the cluster."
},
{
"code": null,
"e": 6243,
"s": 6144,
"text": "discovery-server.enabled β Presto uses the Discovery service to find all the nodes in the cluster."
},
{
"code": null,
"e": 6291,
"s": 6243,
"text": "discovery.uri β he URI to the Discovery server."
},
{
"code": null,
"e": 6339,
"s": 6291,
"text": "discovery.uri β he URI to the Discovery server."
},
{
"code": null,
"e": 6530,
"s": 6339,
"text": "If you are setting up multiple machine Presto server, Presto will function as both coordination and worker process. Use this configuration setting to test Presto server on multiple machines."
},
{
"code": null,
"e": 6791,
"s": 6530,
"text": "$ cd etc \n$ vi config.properties \n\ncoordinator = true \nnode-scheduler.include-coordinator = false \nhttp-server.http.port = 8080 \nquery.max-memory = 50GB \nquery.max-memory-per-node = 1GB \ndiscovery-server.enabled = true \ndiscovery.uri = http://localhost:8080 \n"
},
{
"code": null,
"e": 6975,
"s": 6791,
"text": "$ cd etc \n$ vi config.properties \n\ncoordinator = false \nhttp-server.http.port = 8080 \nquery.max-memory = 50GB \nquery.max-memory-per-node = 1GB \ndiscovery.uri = http://localhost:8080\n"
},
{
"code": null,
"e": 7156,
"s": 6975,
"text": "Create a file βlog.propertiesβ inside etc directory(etc/log.properties). This file contains minimum log level for named logger hierarchies. It is defined using the following code β"
},
{
"code": null,
"e": 7216,
"s": 7156,
"text": "$ cd etc \n$ vi log.properties \ncom.facebook.presto = INFO\n"
},
{
"code": null,
"e": 7348,
"s": 7216,
"text": "Save the file and quit the terminal. Here, four log levels are used such as DEBUG, INFO, WARN and ERROR. Default log level is INFO."
},
{
"code": null,
"e": 7572,
"s": 7348,
"text": "Create a directory βcatalogβ inside etc directory(etc/catalog). This will be used for mounting data. For example, create etc/catalog/jmx.properties with the following contents to mount the jmx connector as the jmx catalog β"
},
{
"code": null,
"e": 7658,
"s": 7572,
"text": "$ cd etc \n$ mkdir catalog \n$ cd catalog \n$ vi jmx.properties \nconnector.name = jmx \n"
},
{
"code": null,
"e": 7709,
"s": 7658,
"text": "Presto can be started using the following command,"
},
{
"code": null,
"e": 7732,
"s": 7709,
"text": "$ bin/launcher start \n"
},
{
"code": null,
"e": 7780,
"s": 7732,
"text": "Then you will see the response similar to this,"
},
{
"code": null,
"e": 7796,
"s": 7780,
"text": "Started as 840\n"
},
{
"code": null,
"e": 7849,
"s": 7796,
"text": "To launch Presto server, use the following command β"
},
{
"code": null,
"e": 7869,
"s": 7849,
"text": "$ bin/launcher run\n"
},
{
"code": null,
"e": 7960,
"s": 7869,
"text": "After successfully launching Presto server, you can find log files in βvar/logβ directory."
},
{
"code": null,
"e": 8076,
"s": 7960,
"text": "launcher.log β This log is created by the launcher and is connected to the stdout and stderr streams of the server."
},
{
"code": null,
"e": 8192,
"s": 8076,
"text": "launcher.log β This log is created by the launcher and is connected to the stdout and stderr streams of the server."
},
{
"code": null,
"e": 8247,
"s": 8192,
"text": "server.log β This is the main log file used by Presto."
},
{
"code": null,
"e": 8302,
"s": 8247,
"text": "server.log β This is the main log file used by Presto."
},
{
"code": null,
"e": 8358,
"s": 8302,
"text": "http-request.log β HTTP request received by the server."
},
{
"code": null,
"e": 8414,
"s": 8358,
"text": "http-request.log β HTTP request received by the server."
},
{
"code": null,
"e": 8552,
"s": 8414,
"text": "As of now, you have successfully installed Presto configuration settings on your machine. Letβs continue the steps to install Presto CLI."
},
{
"code": null,
"e": 8632,
"s": 8552,
"text": "The Presto CLI provides a terminal-based interactive shell for running queries."
},
{
"code": null,
"e": 8688,
"s": 8632,
"text": "Download the Presto CLI by visiting the following link,"
},
{
"code": null,
"e": 8757,
"s": 8688,
"text": "https://repo1.maven.org/maven2/com/facebook/presto/presto-cli/0.149/"
},
{
"code": null,
"e": 8830,
"s": 8757,
"text": "Now βpresto-cli-0.149-executable.jarβ will be installed on your machine."
},
{
"code": null,
"e": 9116,
"s": 8830,
"text": "After downloading the presto-cli, copy it to the location which you want to run it from. This location may be any node that has network access to the coordinator. First change the name of the Jar file to Presto. Then make it executable with chmod + x command using the following code β"
},
{
"code": null,
"e": 9181,
"s": 9116,
"text": "$ mv presto-cli-0.149-executable.jar presto \n$ chmod +x presto\n"
},
{
"code": null,
"e": 9226,
"s": 9181,
"text": "Now execute CLI using the following command,"
},
{
"code": null,
"e": 9379,
"s": 9226,
"text": "./presto --server localhost:8080 --catalog jmx --schema default \nHere jmx(Java Management Extension) refers to catalog and default referes to schema. \n"
},
{
"code": null,
"e": 9416,
"s": 9379,
"text": "You will see the following response,"
},
{
"code": null,
"e": 9434,
"s": 9416,
"text": " presto:default>\n"
},
{
"code": null,
"e": 9512,
"s": 9434,
"text": "Now type βjpsβ command on your terminal and you will see the running daemons."
},
{
"code": null,
"e": 9616,
"s": 9512,
"text": "After having performed all the executions, you can stop the presto server using the following command β"
},
{
"code": null,
"e": 9638,
"s": 9616,
"text": "$ bin/launcher stop \n"
},
{
"code": null,
"e": 9673,
"s": 9638,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9692,
"s": 9673,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9727,
"s": 9692,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9748,
"s": 9727,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 9781,
"s": 9748,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9794,
"s": 9781,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 9829,
"s": 9794,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9847,
"s": 9829,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 9880,
"s": 9847,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9898,
"s": 9880,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 9931,
"s": 9898,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9949,
"s": 9931,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 9956,
"s": 9949,
"text": " Print"
},
{
"code": null,
"e": 9967,
"s": 9956,
"text": " Add Notes"
}
] |
Automate These 3 (Boring!!) Excel Tasks with Python! | by Nik Piepenbreier | Towards Data Science
|
Excel is everywhere. Itβs basically the default application for data analysis in the workplace, for better or for worse. There are many boring tasks that you may need to take on in your day to day, that leave you thinking, βthere must be a better wayβ. Python is that way!
All of these examples are possible in VBA, but VBA can be tedious, and hey, we love Python!
You might find yourself with a number of Excel workbooks (such as monthly sales reports). One day, youβre asked to calculate the total number of sales across all these reports. We can easily combine Excel workbooks with Python, using the Pandas library.
You can install Pandas using either pip or conda:
pip install pandasconda install pandas
For this tutorial, letβs load in three separate Excel workbooks that are linked to below:
File 1: https://github.com/datagy/mediumdata/raw/master/january.xlsx
File 2: https://github.com/datagy/mediumdata/raw/master/february.xlsx
File 3: https://github.com/datagy/mediumdata/raw/master/march.xlsx
We can see that the data doesnβt really start until Row 4, so weβll need Pandas to import sheets beginning at that row. In the code below, weβll make use of the read_excel and append functions.
Letβs take a look at what we did here:
In Section 1, we imported pandas, created a list with all the URLs, and generated a blank dataframe called combined.In Section 2, we looped through each of the URLs in files to read each file into a dataframe (βdfβ), skipping the first three rows, and append it to the combined dataframe.In Section 3, we write generate a new Excel file called combined.xlsx containing our merged Excel workbooks!
In Section 1, we imported pandas, created a list with all the URLs, and generated a blank dataframe called combined.
In Section 2, we looped through each of the URLs in files to read each file into a dataframe (βdfβ), skipping the first three rows, and append it to the combined dataframe.
In Section 3, we write generate a new Excel file called combined.xlsx containing our merged Excel workbooks!
Letβs take a look at another example! Say we needed to get only the total for Toronto from each sales report and collect them in a list. We know that the total is stored in cell F5 in every workbook. If youβre following along, this package works if you have your files stored locally. Download the files with the links above and save them to your machine.
For this example, weβll use a different library called openpyxl. You can install it with either pip or conda using the code below:
pip install openpyxlconda install openpyxl
Letβs get coding!
Letβs break this down step-by-step:
In Section 1, we:
Generated a list (βfilesβ) that contains links to all our files. In Windows we can Shift+right-click and use Copy as Path to get its path.
You will likely want to convert the string to a raw string, by prefixing it with βrβ.
We also generated an empty list to store our values.
In Step 2, we
Looped over the files using openpyxl.
The .load_workbook() method loads a file.
We use [βSheet1β] and [βF5β] to reference both sheet names and cell references in workbook and worksheet objects.
Finally, we use the .value attribute to extract the cellβs value and append it to the values list.
Letβs take a look at one final example! In each of the Excel workbooks, we have totals across the rows, but not a grand total for sales. Again, we could open each workbook and add in a formula, or we can use Python to do this for us!
Weβll be making use of openpyxl again. If you need to install it, check out the instructions above. The links to download the files are also available above.
In this piece of code, we again fill a list to the files. The for-loop, opens each file and assigns βSheet1β to a variable sheet.
We then assign the string β=SUM(F5:F8)β to cell F9 and use the .style attribute to assign the currency style directly to the cell. More cell styles can be found in the official documentation.
Python makes working with Excel files quite easy! In this article, we learned how to combine various Excel files, get specific values, and add formulas across workbooks.
Python letβs use create traceable, reproducible code that lets us replicate our analytical design. While you might be stuck with Excel workbooks throughout the day, Python can automate some of the tedious tasks that come along with it.
|
[
{
"code": null,
"e": 445,
"s": 172,
"text": "Excel is everywhere. Itβs basically the default application for data analysis in the workplace, for better or for worse. There are many boring tasks that you may need to take on in your day to day, that leave you thinking, βthere must be a better wayβ. Python is that way!"
},
{
"code": null,
"e": 537,
"s": 445,
"text": "All of these examples are possible in VBA, but VBA can be tedious, and hey, we love Python!"
},
{
"code": null,
"e": 791,
"s": 537,
"text": "You might find yourself with a number of Excel workbooks (such as monthly sales reports). One day, youβre asked to calculate the total number of sales across all these reports. We can easily combine Excel workbooks with Python, using the Pandas library."
},
{
"code": null,
"e": 841,
"s": 791,
"text": "You can install Pandas using either pip or conda:"
},
{
"code": null,
"e": 880,
"s": 841,
"text": "pip install pandasconda install pandas"
},
{
"code": null,
"e": 970,
"s": 880,
"text": "For this tutorial, letβs load in three separate Excel workbooks that are linked to below:"
},
{
"code": null,
"e": 1039,
"s": 970,
"text": "File 1: https://github.com/datagy/mediumdata/raw/master/january.xlsx"
},
{
"code": null,
"e": 1109,
"s": 1039,
"text": "File 2: https://github.com/datagy/mediumdata/raw/master/february.xlsx"
},
{
"code": null,
"e": 1176,
"s": 1109,
"text": "File 3: https://github.com/datagy/mediumdata/raw/master/march.xlsx"
},
{
"code": null,
"e": 1370,
"s": 1176,
"text": "We can see that the data doesnβt really start until Row 4, so weβll need Pandas to import sheets beginning at that row. In the code below, weβll make use of the read_excel and append functions."
},
{
"code": null,
"e": 1409,
"s": 1370,
"text": "Letβs take a look at what we did here:"
},
{
"code": null,
"e": 1806,
"s": 1409,
"text": "In Section 1, we imported pandas, created a list with all the URLs, and generated a blank dataframe called combined.In Section 2, we looped through each of the URLs in files to read each file into a dataframe (βdfβ), skipping the first three rows, and append it to the combined dataframe.In Section 3, we write generate a new Excel file called combined.xlsx containing our merged Excel workbooks!"
},
{
"code": null,
"e": 1923,
"s": 1806,
"text": "In Section 1, we imported pandas, created a list with all the URLs, and generated a blank dataframe called combined."
},
{
"code": null,
"e": 2096,
"s": 1923,
"text": "In Section 2, we looped through each of the URLs in files to read each file into a dataframe (βdfβ), skipping the first three rows, and append it to the combined dataframe."
},
{
"code": null,
"e": 2205,
"s": 2096,
"text": "In Section 3, we write generate a new Excel file called combined.xlsx containing our merged Excel workbooks!"
},
{
"code": null,
"e": 2561,
"s": 2205,
"text": "Letβs take a look at another example! Say we needed to get only the total for Toronto from each sales report and collect them in a list. We know that the total is stored in cell F5 in every workbook. If youβre following along, this package works if you have your files stored locally. Download the files with the links above and save them to your machine."
},
{
"code": null,
"e": 2692,
"s": 2561,
"text": "For this example, weβll use a different library called openpyxl. You can install it with either pip or conda using the code below:"
},
{
"code": null,
"e": 2735,
"s": 2692,
"text": "pip install openpyxlconda install openpyxl"
},
{
"code": null,
"e": 2753,
"s": 2735,
"text": "Letβs get coding!"
},
{
"code": null,
"e": 2789,
"s": 2753,
"text": "Letβs break this down step-by-step:"
},
{
"code": null,
"e": 2807,
"s": 2789,
"text": "In Section 1, we:"
},
{
"code": null,
"e": 2946,
"s": 2807,
"text": "Generated a list (βfilesβ) that contains links to all our files. In Windows we can Shift+right-click and use Copy as Path to get its path."
},
{
"code": null,
"e": 3032,
"s": 2946,
"text": "You will likely want to convert the string to a raw string, by prefixing it with βrβ."
},
{
"code": null,
"e": 3085,
"s": 3032,
"text": "We also generated an empty list to store our values."
},
{
"code": null,
"e": 3099,
"s": 3085,
"text": "In Step 2, we"
},
{
"code": null,
"e": 3137,
"s": 3099,
"text": "Looped over the files using openpyxl."
},
{
"code": null,
"e": 3179,
"s": 3137,
"text": "The .load_workbook() method loads a file."
},
{
"code": null,
"e": 3293,
"s": 3179,
"text": "We use [βSheet1β] and [βF5β] to reference both sheet names and cell references in workbook and worksheet objects."
},
{
"code": null,
"e": 3392,
"s": 3293,
"text": "Finally, we use the .value attribute to extract the cellβs value and append it to the values list."
},
{
"code": null,
"e": 3626,
"s": 3392,
"text": "Letβs take a look at one final example! In each of the Excel workbooks, we have totals across the rows, but not a grand total for sales. Again, we could open each workbook and add in a formula, or we can use Python to do this for us!"
},
{
"code": null,
"e": 3784,
"s": 3626,
"text": "Weβll be making use of openpyxl again. If you need to install it, check out the instructions above. The links to download the files are also available above."
},
{
"code": null,
"e": 3914,
"s": 3784,
"text": "In this piece of code, we again fill a list to the files. The for-loop, opens each file and assigns βSheet1β to a variable sheet."
},
{
"code": null,
"e": 4106,
"s": 3914,
"text": "We then assign the string β=SUM(F5:F8)β to cell F9 and use the .style attribute to assign the currency style directly to the cell. More cell styles can be found in the official documentation."
},
{
"code": null,
"e": 4276,
"s": 4106,
"text": "Python makes working with Excel files quite easy! In this article, we learned how to combine various Excel files, get specific values, and add formulas across workbooks."
}
] |
How to sort the letters in a string alphabetically in Python?
|
To sort letters in a string alphabetically, you need to use the sorted function that returns a sorted list of letters which you can then join to get a string. For example,
>>> s = "helloworld"
>>> ''.join(sorted(s))
'dehllloorw'
If you want only unique characters sorted, you can use sets to get the result. For example,
>>> s = "helloworld"
>>> ''.join(sorted(set(s)))
'dehlorw'
|
[
{
"code": null,
"e": 1234,
"s": 1062,
"text": "To sort letters in a string alphabetically, you need to use the sorted function that returns a sorted list of letters which you can then join to get a string. For example,"
},
{
"code": null,
"e": 1291,
"s": 1234,
"text": ">>> s = \"helloworld\"\n>>> ''.join(sorted(s))\n'dehllloorw'"
},
{
"code": null,
"e": 1383,
"s": 1291,
"text": "If you want only unique characters sorted, you can use sets to get the result. For example,"
},
{
"code": null,
"e": 1442,
"s": 1383,
"text": ">>> s = \"helloworld\"\n>>> ''.join(sorted(set(s)))\n'dehlorw'"
}
] |
How to use a switch case 'or' in PHP? - GeeksforGeeks
|
11 Nov, 2018
Problem: How to use a switch case βorβ in PHP?Solution: This can be achieved in 2 ways. They are as follows:Method 1: Without using break keyword in one of the switch case.Example:
<?php$option = 1;switch ($option){ case 1: case 2: echo "The option is either 1 or 2."; break;}?>
Output:
The option is either 1 or 2.
Method 2: Using or operator in switch case.Example:
<?php$option = 1;switch ($option) { case ($option == 1 || $option == 2): echo 'The option is either 1 or 2'; break;}?>
Output:
The option is either 1 or 2
Reference: http://php.net/manual/en/control-structures.switch.php
PHP-basics
PHP-Control-Statement
Picked
Technical Scripter 2018
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
PHP | Converting string to Date and DateTime
How to fetch data from localserver database and display on HTML table using PHP ?
How to receive JSON POST with PHP ?
Download file from URL using PHP
How to pass JavaScript variables to PHP ?
Best way to initialize empty array in PHP
|
[
{
"code": null,
"e": 24804,
"s": 24776,
"text": "\n11 Nov, 2018"
},
{
"code": null,
"e": 24985,
"s": 24804,
"text": "Problem: How to use a switch case βorβ in PHP?Solution: This can be achieved in 2 ways. They are as follows:Method 1: Without using break keyword in one of the switch case.Example:"
},
{
"code": "<?php$option = 1;switch ($option){ case 1: case 2: echo \"The option is either 1 or 2.\"; break;}?>",
"e": 25099,
"s": 24985,
"text": null
},
{
"code": null,
"e": 25107,
"s": 25099,
"text": "Output:"
},
{
"code": null,
"e": 25137,
"s": 25107,
"text": "The option is either 1 or 2.\n"
},
{
"code": null,
"e": 25189,
"s": 25137,
"text": "Method 2: Using or operator in switch case.Example:"
},
{
"code": "<?php$option = 1;switch ($option) { case ($option == 1 || $option == 2): echo 'The option is either 1 or 2'; break;}?>",
"e": 25325,
"s": 25189,
"text": null
},
{
"code": null,
"e": 25333,
"s": 25325,
"text": "Output:"
},
{
"code": null,
"e": 25362,
"s": 25333,
"text": "The option is either 1 or 2\n"
},
{
"code": null,
"e": 25428,
"s": 25362,
"text": "Reference: http://php.net/manual/en/control-structures.switch.php"
},
{
"code": null,
"e": 25439,
"s": 25428,
"text": "PHP-basics"
},
{
"code": null,
"e": 25461,
"s": 25439,
"text": "PHP-Control-Statement"
},
{
"code": null,
"e": 25468,
"s": 25461,
"text": "Picked"
},
{
"code": null,
"e": 25492,
"s": 25468,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 25496,
"s": 25492,
"text": "PHP"
},
{
"code": null,
"e": 25515,
"s": 25496,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25519,
"s": 25515,
"text": "PHP"
},
{
"code": null,
"e": 25617,
"s": 25519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25626,
"s": 25617,
"text": "Comments"
},
{
"code": null,
"e": 25639,
"s": 25626,
"text": "Old Comments"
},
{
"code": null,
"e": 25689,
"s": 25639,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 25729,
"s": 25689,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 25779,
"s": 25729,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 25806,
"s": 25779,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 25851,
"s": 25806,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 25933,
"s": 25851,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 25969,
"s": 25933,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 26002,
"s": 25969,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 26044,
"s": 26002,
"text": "How to pass JavaScript variables to PHP ?"
}
] |
Compression using the LZMA algorithm using Python (lzma)
|
The LempelβZivβMarkov chain algorithm(LZMA) performs lossless data compression using a dictionary compression scheme featuring a higher compression ratio than other compression algorithms. Pythonβs lzma module consists of classes and convenience functions for compression and decompression of data with LZMA algorithm.
Although the functionality in this module is similar to that of bz2 module, the LZMAFile class is not thread safe as compared to BZ2File class.
Here again, open() function in lzma module is a very easiest way to open lzma-compressed file object.
This function opens a LZMA-compressed file and returns a file object. The function requires two main parameters β file name and mode. The mode parameter is by default βrbβ but can take any of following values
binary mode - "r", "rb", "w", "wb", "x", "xb", "a" or "ab"
text mode - "rt", "wt", "xt", or "at"
This function compresses given data using LZMA algorithm and returns a byte object. This function can optionally hava a format argument that decides the container format. Possible values are FORMAT_XZ (default) and FORMAT_ALONE.
This function decompresses the data and returns uncompressed byte object.
Above functions are used in following examples. To write LZMA compressed data to file
>>> import lzma
>>> data = b"Welcome to TutorialsPoint"
>>> f = lzma.open("test.xz","wb")
>>>f.write(data)
>>>f.close()
A βtest.xzβ file will be created in current working directory. To fetch uncompressed data from this file use following code.
>>> import lzma
>>> f = lzma.open("test.xz","rb")
>>> data = f.read()
>>> data
b'Welcome to TutorialsPoint'
To perform compression using object oriented API of lzma module, we have to use LZMAFile class
This is the constructor for LZMAFile class. It requires file and mode to be specified. The object with βwβ or βwbβ mode makes write() method available to it.
This method compress given data and write it into the file underneath it.
>>> data = b'Welcome to TutorialsPoint'
>>>obj = lzma.LZMAFile("test.xz", mode="wb")
>>>obj.write(data)
>>>obj.close()
The compressed file is read and uncompressed data is rerieved by read() method of LZMAFile object created with mode=βrbβ parameter.
This method reads data from compressed file and returns uncompressed data.
>>>obj = lzma.LZMAFile("test.xz", mode="rb")
>>> data=obj.read()
>>> data
b'Welcome to TutorialsPoint'
The LZMA algorithm allows writing compressed data to an already open file also. In following example, βtest.txtβ is opened normally (using built-in open() function) in βwbβ mode and some text is written to it. Afterwards, the same file is used to write compressed data.
>>> f = open("test.txt","wb")
>>>f.write(b"Hello world")
>>>fp = lzma.open(f,"wb")
>>>fp.write(b"Welcome to Python")
>>>f.write(b"Thank you")
>>>f.close()
>>>fp.flush()
>>>fp.close()
When above code is executed, βtest.txtβ appears in current directory. It contains mix of compressed and uncompressed data as below
Hello worldyΜ7zXZ Γ¦OΜ ΜF!t/aΜΒ£Thank you
As in bz2 module, the lzma module too has incremental compressor and decompressor classes.
This is a constructor that returns incremental compressor object. Multiple chunks can be individually compressed and their concatenated data is written to file
This method compresses given data and returns byte object
This method empties the buffer and returns a byte object.
Following example compresses a list object using incremental compressor object.
>>> data = [b'Hello World', b'How are you?', b'welcome to Python']
>>> obj = lzma.LZMACompressor()
>>> bindata = []
>>> for i in data:
bindata.append(obj.compress(i))
>>> bindata.append(obj.flush())
>>> bindata
[b'\xfd7zXZ\x00\x00\x04\xe6\xd6\xb4F\x02\x00!\x01\x16\x00\x00\x00t/\xe5\xa3', b'', b'', b"\x01\x00'Hello WorldHow are you?welcome to Python\x00\xf5\xc6\xc1d|\xf3\x8ey\x00\x01@(\xd4RJ\xe5\x1f\xb6\xf3}\x01\x00\x00\x00\x00\x04YZ"]
Above code builds bindata as list of compressed byte representations of each item in original list. To retrieve the uncompressed data using LZMADecompressor object, use following statement
>>> obj = lzma.LZMADecompressor()
>>> binstr = b''.join(bindata)
>>> obj.decompress(binstr)
b'Hello WorldHow are you?welcome to Python'
In this article the classes and functions in lzma module have been explained with examples.
|
[
{
"code": null,
"e": 1381,
"s": 1062,
"text": "The LempelβZivβMarkov chain algorithm(LZMA) performs lossless data compression using a dictionary compression scheme featuring a higher compression ratio than other compression algorithms. Pythonβs lzma module consists of classes and convenience functions for compression and decompression of data with LZMA algorithm."
},
{
"code": null,
"e": 1525,
"s": 1381,
"text": "Although the functionality in this module is similar to that of bz2 module, the LZMAFile class is not thread safe as compared to BZ2File class."
},
{
"code": null,
"e": 1627,
"s": 1525,
"text": "Here again, open() function in lzma module is a very easiest way to open lzma-compressed file object."
},
{
"code": null,
"e": 1836,
"s": 1627,
"text": "This function opens a LZMA-compressed file and returns a file object. The function requires two main parameters β file name and mode. The mode parameter is by default βrbβ but can take any of following values"
},
{
"code": null,
"e": 1933,
"s": 1836,
"text": "binary mode - \"r\", \"rb\", \"w\", \"wb\", \"x\", \"xb\", \"a\" or \"ab\"\ntext mode - \"rt\", \"wt\", \"xt\", or \"at\""
},
{
"code": null,
"e": 2162,
"s": 1933,
"text": "This function compresses given data using LZMA algorithm and returns a byte object. This function can optionally hava a format argument that decides the container format. Possible values are FORMAT_XZ (default) and FORMAT_ALONE."
},
{
"code": null,
"e": 2236,
"s": 2162,
"text": "This function decompresses the data and returns uncompressed byte object."
},
{
"code": null,
"e": 2322,
"s": 2236,
"text": "Above functions are used in following examples. To write LZMA compressed data to file"
},
{
"code": null,
"e": 2442,
"s": 2322,
"text": ">>> import lzma\n>>> data = b\"Welcome to TutorialsPoint\"\n>>> f = lzma.open(\"test.xz\",\"wb\")\n>>>f.write(data)\n>>>f.close()"
},
{
"code": null,
"e": 2567,
"s": 2442,
"text": "A βtest.xzβ file will be created in current working directory. To fetch uncompressed data from this file use following code."
},
{
"code": null,
"e": 2675,
"s": 2567,
"text": ">>> import lzma\n>>> f = lzma.open(\"test.xz\",\"rb\")\n>>> data = f.read()\n>>> data\nb'Welcome to TutorialsPoint'"
},
{
"code": null,
"e": 2770,
"s": 2675,
"text": "To perform compression using object oriented API of lzma module, we have to use LZMAFile class"
},
{
"code": null,
"e": 2928,
"s": 2770,
"text": "This is the constructor for LZMAFile class. It requires file and mode to be specified. The object with βwβ or βwbβ mode makes write() method available to it."
},
{
"code": null,
"e": 3002,
"s": 2928,
"text": "This method compress given data and write it into the file underneath it."
},
{
"code": null,
"e": 3121,
"s": 3002,
"text": ">>> data = b'Welcome to TutorialsPoint'\n>>>obj = lzma.LZMAFile(\"test.xz\", mode=\"wb\")\n>>>obj.write(data)\n>>>obj.close()"
},
{
"code": null,
"e": 3253,
"s": 3121,
"text": "The compressed file is read and uncompressed data is rerieved by read() method of LZMAFile object created with mode=βrbβ parameter."
},
{
"code": null,
"e": 3328,
"s": 3253,
"text": "This method reads data from compressed file and returns uncompressed data."
},
{
"code": null,
"e": 3431,
"s": 3328,
"text": ">>>obj = lzma.LZMAFile(\"test.xz\", mode=\"rb\")\n>>> data=obj.read()\n>>> data\nb'Welcome to TutorialsPoint'"
},
{
"code": null,
"e": 3701,
"s": 3431,
"text": "The LZMA algorithm allows writing compressed data to an already open file also. In following example, βtest.txtβ is opened normally (using built-in open() function) in βwbβ mode and some text is written to it. Afterwards, the same file is used to write compressed data."
},
{
"code": null,
"e": 3884,
"s": 3701,
"text": ">>> f = open(\"test.txt\",\"wb\")\n>>>f.write(b\"Hello world\")\n>>>fp = lzma.open(f,\"wb\")\n>>>fp.write(b\"Welcome to Python\")\n>>>f.write(b\"Thank you\")\n>>>f.close()\n>>>fp.flush()\n>>>fp.close()"
},
{
"code": null,
"e": 4015,
"s": 3884,
"text": "When above code is executed, βtest.txtβ appears in current directory. It contains mix of compressed and uncompressed data as below"
},
{
"code": null,
"e": 4055,
"s": 4015,
"text": "Hello worldyΜ7zXZ Γ¦OΜ ΜF!t/aΜΒ£Thank you"
},
{
"code": null,
"e": 4146,
"s": 4055,
"text": "As in bz2 module, the lzma module too has incremental compressor and decompressor classes."
},
{
"code": null,
"e": 4306,
"s": 4146,
"text": "This is a constructor that returns incremental compressor object. Multiple chunks can be individually compressed and their concatenated data is written to file"
},
{
"code": null,
"e": 4364,
"s": 4306,
"text": "This method compresses given data and returns byte object"
},
{
"code": null,
"e": 4422,
"s": 4364,
"text": "This method empties the buffer and returns a byte object."
},
{
"code": null,
"e": 4502,
"s": 4422,
"text": "Following example compresses a list object using incremental compressor object."
},
{
"code": null,
"e": 4941,
"s": 4502,
"text": ">>> data = [b'Hello World', b'How are you?', b'welcome to Python']\n>>> obj = lzma.LZMACompressor()\n>>> bindata = []\n>>> for i in data:\nbindata.append(obj.compress(i))\n>>> bindata.append(obj.flush())\n>>> bindata\n[b'\\xfd7zXZ\\x00\\x00\\x04\\xe6\\xd6\\xb4F\\x02\\x00!\\x01\\x16\\x00\\x00\\x00t/\\xe5\\xa3', b'', b'', b\"\\x01\\x00'Hello WorldHow are you?welcome to Python\\x00\\xf5\\xc6\\xc1d|\\xf3\\x8ey\\x00\\x01@(\\xd4RJ\\xe5\\x1f\\xb6\\xf3}\\x01\\x00\\x00\\x00\\x00\\x04YZ\"]"
},
{
"code": null,
"e": 5130,
"s": 4941,
"text": "Above code builds bindata as list of compressed byte representations of each item in original list. To retrieve the uncompressed data using LZMADecompressor object, use following statement"
},
{
"code": null,
"e": 5266,
"s": 5130,
"text": ">>> obj = lzma.LZMADecompressor()\n>>> binstr = b''.join(bindata)\n>>> obj.decompress(binstr)\nb'Hello WorldHow are you?welcome to Python'"
},
{
"code": null,
"e": 5358,
"s": 5266,
"text": "In this article the classes and functions in lzma module have been explained with examples."
}
] |
0-1 BFS (Shortest Path in a Binary Weight Graph) - GeeksforGeeks
|
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make Apps
School Guide
Python Programming
Learn To Make Apps
All Courses
TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship
Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise
Must Do Questions
DSA Topic-wise
DSA Company-wise
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Geek on the Top
Careers
Internship
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Events
WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Practice DS & Algo.
Must Do Questions
DSA Topic-wise
DSA Company-wise
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
School Learning
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Geek on the Top
Careers
Internship
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
School Guide
Python Programming
Learn To Make Apps
Practice DS & Algo.
Must Do Questions
DSA Topic-wise
DSA Company-wise
Must Do Questions
DSA Topic-wise
DSA Company-wise
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
Software Design Patterns
System Design Tutorial
School Learning
School Programming
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Geek on the Top
Careers
Internship
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Geek on the Top
Careers
Internship
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
0-1 BFS (Shortest Path in a Binary Weight Graph)
Shortest path in an unweighted graph
Kruskalβs Minimum Spanning Tree Algorithm | Greedy Algo-2
Primβs Minimum Spanning Tree (MST) | Greedy Algo-5
Primβs MST for Adjacency List Representation | Greedy Algo-6
Dijkstraβs shortest path algorithm | Greedy Algo-7
Dijkstraβs Algorithm for Adjacency List Representation | Greedy Algo-8
Dijkstraβs shortest path algorithm using set in STL
Dijkstraβs Shortest Path Algorithm using priority_queue of STL
Dijkstraβs shortest path algorithm in Java using PriorityQueue
Java Program for Dijkstraβs shortest path algorithm | Greedy Algo-7
Java Program for Dijkstraβs Algorithm with Path Printing
Printing Paths in Dijkstraβs Shortest Path Algorithm
Shortest Path in a weighted Graph where weight of an edge is 1 or 2
N Queen Problem | Backtracking-3
Printing all solutions in N-Queen Problem
Warnsdorffβs algorithm for Knightβs tour problem
The Knightβs tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Count number of ways to reach destination in a Maze
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Unique paths covering every non-obstacle block exactly once in a grid
Depth First Search or DFS for a Graph
Breadth First Search or BFS for a Graph
Graph and its representations
0-1 BFS (Shortest Path in a Binary Weight Graph)
Shortest path in an unweighted graph
Kruskalβs Minimum Spanning Tree Algorithm | Greedy Algo-2
Primβs Minimum Spanning Tree (MST) | Greedy Algo-5
Primβs MST for Adjacency List Representation | Greedy Algo-6
Dijkstraβs shortest path algorithm | Greedy Algo-7
Dijkstraβs Algorithm for Adjacency List Representation | Greedy Algo-8
Dijkstraβs shortest path algorithm using set in STL
Dijkstraβs Shortest Path Algorithm using priority_queue of STL
Dijkstraβs shortest path algorithm in Java using PriorityQueue
Java Program for Dijkstraβs shortest path algorithm | Greedy Algo-7
Java Program for Dijkstraβs Algorithm with Path Printing
Printing Paths in Dijkstraβs Shortest Path Algorithm
Shortest Path in a weighted Graph where weight of an edge is 1 or 2
N Queen Problem | Backtracking-3
Printing all solutions in N-Queen Problem
Warnsdorffβs algorithm for Knightβs tour problem
The Knightβs tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Count number of ways to reach destination in a Maze
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Unique paths covering every non-obstacle block exactly once in a grid
Depth First Search or DFS for a Graph
Breadth First Search or BFS for a Graph
Graph and its representations
Difficulty Level :
Medium
Given a graph where every edge has weight as either 0 or 1. A source vertex is also given in the graph. Find the shortest path from source vertex to every other vertex. Example:
Input : Source Vertex = 0 and below graph
Output : Shortest distances from given source
0 0 1 1 2 1 2 1 2
Explanation :
Shortest distance from 0 to 0 is 0
Shortest distance from 0 to 1 is 0
Shortest distance from 0 to 2 is 1
..................
In normal BFS of a graph all edges have equal weight but in 0-1 BFS some edges may have 0 weight and some may have 1 weight. In this we will not use bool array to mark visited nodes but at each step we will check for the optimal distance condition. We use double ended queue to store the node. While performing BFS if a edge having weight = 0 is found node is pushed at front of double ended queue and if a edge having weight = 1 is found, it is pushed at back of double ended queue.The approach is similar to Dijkstra that the if the shortest distance to node is relaxed by the previous node then only it will be pushed in the queue. The above idea works in all cases, when pop a vertex (like Dijkstra), it is the minimum weight vertex among remaining vertices. If there is a 0 weight vertex adjacent to it, then this adjacent has same distance. If there is a 1 weight adjacent, then this adjacent has maximum distance among all vertices in dequeue (because all other vertices are either adjacent of currently popped vertex or adjacent of previously popped vertices).Below is the implementation of the above idea.
C++
Java
Python3
Javascript
// C++ program to implement single source// shortest path for a Binary Graph#include<bits/stdc++.h>using namespace std; /* no.of vertices */#define V 9 // a structure to represent edgesstruct node{ // two variable one denote the node // and other the weight int to, weight;}; // vector to store edgesvector <node> edges[V]; // Prints shortest distance from given source to// every other vertexvoid zeroOneBFS(int src){ // Initialize distances from given source int dist[V]; for (int i=0; i<V; i++) dist[i] = INT_MAX; // double ende queue to do BFS. deque <int> Q; dist[src] = 0; Q.push_back(src); while (!Q.empty()) { int v = Q.front(); Q.pop_front(); for (int i=0; i<edges[v].size(); i++) { // checking for the optimal distance if (dist[edges[v][i].to] > dist[v] + edges[v][i].weight) { dist[edges[v][i].to] = dist[v] + edges[v][i].weight; // Put 0 weight edges to front and 1 weight // edges to back so that vertices are processed // in increasing order of weights. if (edges[v][i].weight == 0) Q.push_front(edges[v][i].to); else Q.push_back(edges[v][i].to); } } } // printing the shortest distances for (int i=0; i<V; i++) cout << dist[i] << " ";} void addEdge(int u, int v, int wt){ edges[u].push_back({v, wt}); edges[v].push_back({u, wt});} // Driver functionint main(){ addEdge(0, 1, 0); addEdge(0, 7, 1); addEdge(1, 7, 1); addEdge(1, 2, 1); addEdge(2, 3, 0); addEdge(2, 5, 0); addEdge(2, 8, 1); addEdge(3, 4, 1); addEdge(3, 5, 1); addEdge(4, 5, 1); addEdge(5, 6, 1); addEdge(6, 7, 1); addEdge(7, 8, 1); int src = 0;//source node zeroOneBFS(src); return 0;}
// Java Program to implement 0-1 BFSimport java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque; public class ZeroOneBFS { private static class Node { int to; // the ending vertex int weight; // the weight of the edge public Node(int to, int wt) { this.to = to; this.weight = wt; } } private static final int numVertex = 9; private ArrayList<Node>[] edges = new ArrayList[numVertex]; public ZeroOneBFS() { for (int i = 0; i < edges.length; i++) { edges[i] = new ArrayList<Node>(); } } public void addEdge(int u, int v, int wt) { edges[u].add(edges[u].size(), new Node(v, wt)); edges[v].add(edges[v].size(), new Node(u, wt)); } public void zeroOneBFS(int src) { // initialize distances from given source int[] dist = new int[numVertex]; for (int i = 0; i < numVertex; i++) { dist[i] = Integer.MAX_VALUE; } // double ended queue to do BFS Deque<Integer> queue = new ArrayDeque<Integer>(); dist[src] = 0; queue.addLast(src); while (!queue.isEmpty()) { int v = queue.removeFirst(); for (int i = 0; i < edges[v].size(); i++) { // checking for optimal distance if (dist[edges[v].get(i).to] > dist[v] + edges[v].get(i).weight) { // update the distance dist[edges[v].get(i).to] = dist[v] + edges[v].get(i).weight; // put 0 weight edges to front and 1 // weight edges to back so that vertices // are processed in increasing order of weight if (edges[v].get(i).weight == 0) { queue.addFirst(edges[v].get(i).to); } else { queue.addLast(edges[v].get(i).to); } } } } for (int i = 0; i < dist.length; i++) { System.out.print(dist[i] + " "); } } public static void main(String[] args) { ZeroOneBFS graph = new ZeroOneBFS(); graph.addEdge(0, 1, 0); graph.addEdge(0, 7, 1); graph.addEdge(1, 7, 1); graph.addEdge(1, 2, 1); graph.addEdge(2, 3, 0); graph.addEdge(2, 5, 0); graph.addEdge(2, 8, 1); graph.addEdge(3, 4, 1); graph.addEdge(3, 5, 1); graph.addEdge(4, 5, 1); graph.addEdge(5, 6, 1); graph.addEdge(6, 7, 1); graph.addEdge(7, 8, 1); int src = 0;//source node graph.zeroOneBFS(src); return; }}
# Python3 program to implement single source# shortest path for a Binary Graphfrom sys import maxsize as INT_MAXfrom collections import deque # no.of verticesV = 9 # a structure to represent edgesclass node: def __init__(self, to, weight): # two variable one denote the node # and other the weight self.to = to self.weight = weight # vector to store edgesedges = [0] * Vfor i in range(V): edges[i] = [] # Prints shortest distance from# given source to every other vertexdef zeroOneBFS(src: int): # Initialize distances from given source dist = [0] * V for i in range(V): dist[i] = INT_MAX # double ende queue to do BFS. Q = deque() dist[src] = 0 Q.append(src) while Q: v = Q[0] Q.popleft() for i in range(len(edges[v])): # checking for the optimal distance if (dist[edges[v][i].to] > dist[v] + edges[v][i].weight): dist[edges[v][i].to] = dist[v] + edges[v][i].weight # Put 0 weight edges to front and 1 weight # edges to back so that vertices are processed # in increasing order of weights. if edges[v][i].weight == 0: Q.appendleft(edges[v][i].to) else: Q.append(edges[v][i].to) # printing the shortest distances for i in range(V): print(dist[i], end = " ") print() def addEdge(u: int, v: int, wt: int): edges[u].append(node(v, wt)) edges[u].append(node(v, wt)) # Driver Codeif __name__ == "__main__": addEdge(0, 1, 0) addEdge(0, 7, 1) addEdge(1, 7, 1) addEdge(1, 2, 1) addEdge(2, 3, 0) addEdge(2, 5, 0) addEdge(2, 8, 1) addEdge(3, 4, 1) addEdge(3, 5, 1) addEdge(4, 5, 1) addEdge(5, 6, 1) addEdge(6, 7, 1) addEdge(7, 8, 1) # source node src = 0 zeroOneBFS(src) # This code is contributed by# sanjeev2552
<script>// Javascript Program to implement 0-1 BFS class Node{ constructor(to,wt) { this.to = to; this.weight = wt; } } let numVertex = 9;let edges = new Array(numVertex); function _ZeroOneBFS(){ for (let i = 0; i < edges.length; i++) { edges[i] = []; }} function addEdge(u,v,wt){ edges[u].push(edges[u].length, new Node(v, wt)); edges[v].push(edges[v].length, new Node(u, wt));} function zeroOneBFS(src){ // initialize distances from given source let dist = new Array(numVertex); for (let i = 0; i < numVertex; i++) { dist[i] = Number.MAX_VALUE; } // double ended queue to do BFS let queue = []; dist[src] = 0; queue.push(src); while (queue.length!=0) { let v = queue.shift(); for (let i = 0; i < edges[v].length; i++) { // checking for optimal distance if (dist[edges[v][i].to] > dist[v] + edges[v][i].weight) { // update the distance dist[edges[v][i].to] = dist[v] + edges[v][i].weight; // put 0 weight edges to front and 1 // weight edges to back so that vertices // are processed in increasing order of weight if (edges[v][i].weight == 0) { queue.unshift(edges[v][i].to); } else { queue.push(edges[v][i].to); } } } } for (let i = 0; i < dist.length; i++) { document.write(dist[i] + " "); }} _ZeroOneBFS();addEdge(0, 1, 0);addEdge(0, 7, 1);addEdge(1, 7, 1);addEdge(1, 2, 1);addEdge(2, 3, 0);addEdge(2, 5, 0);addEdge(2, 8, 1);addEdge(3, 4, 1);addEdge(3, 5, 1);addEdge(4, 5, 1);addEdge(5, 6, 1);addEdge(6, 7, 1);addEdge(7, 8, 1);let src = 0;//source nodezeroOneBFS(src); // This code is contributed by avanitrachhadiya2155</script>
Output:
0 0 1 1 2 1 2 1 2
This problem can also be solved by Dijkstra but the time complexity will be O(E + V Log V) whereas by BFS it will be O(V+E).Reference : http://codeforces.com/blog/entry/22276This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
Ankit Bansal 2
sanjeev2552
avanitrachhadiya2155
BFS
deque
Shortest Path
Graph
Graph
Shortest Path
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Topological Sorting
Detect Cycle in a Directed Graph
BellmanβFord Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Detect cycle in an undirected graph
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Strongly Connected Components
|
[
{
"code": null,
"e": 407,
"s": 0,
"text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsAll Courses"
},
{
"code": null,
"e": 588,
"s": 407,
"text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 673,
"s": 588,
"text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More"
},
{
"code": null,
"e": 690,
"s": 673,
"text": "DSA Live Classes"
},
{
"code": null,
"e": 704,
"s": 690,
"text": "System Design"
},
{
"code": null,
"e": 729,
"s": 704,
"text": "Java Backend Development"
},
{
"code": null,
"e": 745,
"s": 729,
"text": "Full Stack LIVE"
},
{
"code": null,
"e": 758,
"s": 745,
"text": "Explore More"
},
{
"code": null,
"e": 830,
"s": 758,
"text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 846,
"s": 830,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 857,
"s": 846,
"text": "SDE Theory"
},
{
"code": null,
"e": 882,
"s": 857,
"text": "Must-Do Coding Questions"
},
{
"code": null,
"e": 895,
"s": 882,
"text": "Explore More"
},
{
"code": null,
"e": 1042,
"s": 895,
"text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1118,
"s": 1042,
"text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More"
},
{
"code": null,
"e": 1142,
"s": 1118,
"text": "Competitive Programming"
},
{
"code": null,
"e": 1167,
"s": 1142,
"text": "Data Structures with C++"
},
{
"code": null,
"e": 1180,
"s": 1167,
"text": "Data Science"
},
{
"code": null,
"e": 1193,
"s": 1180,
"text": "Explore More"
},
{
"code": null,
"e": 1253,
"s": 1193,
"text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1269,
"s": 1253,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 1273,
"s": 1269,
"text": "CIP"
},
{
"code": null,
"e": 1293,
"s": 1273,
"text": "JAVA / Python / C++"
},
{
"code": null,
"e": 1306,
"s": 1293,
"text": "Explore More"
},
{
"code": null,
"e": 1369,
"s": 1306,
"text": "School CoursesSchool GuidePython ProgrammingLearn To Make Apps"
},
{
"code": null,
"e": 1382,
"s": 1369,
"text": "School Guide"
},
{
"code": null,
"e": 1401,
"s": 1382,
"text": "Python Programming"
},
{
"code": null,
"e": 1420,
"s": 1401,
"text": "Learn To Make Apps"
},
{
"code": null,
"e": 1432,
"s": 1420,
"text": "All Courses"
},
{
"code": null,
"e": 3954,
"s": 1432,
"text": "TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship"
},
{
"code": null,
"e": 4021,
"s": 3954,
"text": "Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise"
},
{
"code": null,
"e": 4039,
"s": 4021,
"text": "Must Do Questions"
},
{
"code": null,
"e": 4054,
"s": 4039,
"text": "DSA Topic-wise"
},
{
"code": null,
"e": 4071,
"s": 4054,
"text": "DSA Company-wise"
},
{
"code": null,
"e": 4652,
"s": 4071,
"text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms"
},
{
"code": null,
"e": 4985,
"s": 4652,
"text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question"
},
{
"code": null,
"e": 5005,
"s": 4985,
"text": "Asymptotic Analysis"
},
{
"code": null,
"e": 5035,
"s": 5005,
"text": "Worst, Average and Best Cases"
},
{
"code": null,
"e": 5056,
"s": 5035,
"text": "Asymptotic Notations"
},
{
"code": null,
"e": 5092,
"s": 5056,
"text": "Little o and little omega notations"
},
{
"code": null,
"e": 5121,
"s": 5092,
"text": "Lower and Upper Bound Theory"
},
{
"code": null,
"e": 5139,
"s": 5121,
"text": "Analysis of Loops"
},
{
"code": null,
"e": 5159,
"s": 5139,
"text": "Solving Recurrences"
},
{
"code": null,
"e": 5178,
"s": 5159,
"text": "Amortized Analysis"
},
{
"code": null,
"e": 5214,
"s": 5178,
"text": "What does 'Space Complexity' mean ?"
},
{
"code": null,
"e": 5243,
"s": 5214,
"text": "Pseudo-polynomial Algorithms"
},
{
"code": null,
"e": 5280,
"s": 5243,
"text": "Polynomial Time Approximation Scheme"
},
{
"code": null,
"e": 5307,
"s": 5280,
"text": "A Time Complexity Question"
},
{
"code": null,
"e": 5328,
"s": 5307,
"text": "Searching Algorithms"
},
{
"code": null,
"e": 5347,
"s": 5328,
"text": "Sorting Algorithms"
},
{
"code": null,
"e": 5364,
"s": 5347,
"text": "Graph Algorithms"
},
{
"code": null,
"e": 5382,
"s": 5364,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5403,
"s": 5382,
"text": "Geometric Algorithms"
},
{
"code": null,
"e": 5416,
"s": 5403,
"text": "Mathematical"
},
{
"code": null,
"e": 5435,
"s": 5416,
"text": "Bitwise Algorithms"
},
{
"code": null,
"e": 5457,
"s": 5435,
"text": "Randomized Algorithms"
},
{
"code": null,
"e": 5475,
"s": 5457,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 5495,
"s": 5475,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5514,
"s": 5495,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5527,
"s": 5514,
"text": "Backtracking"
},
{
"code": null,
"e": 5544,
"s": 5527,
"text": "Branch and Bound"
},
{
"code": null,
"e": 5559,
"s": 5544,
"text": "All Algorithms"
},
{
"code": null,
"e": 5702,
"s": 5559,
"text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures"
},
{
"code": null,
"e": 5709,
"s": 5702,
"text": "Arrays"
},
{
"code": null,
"e": 5721,
"s": 5709,
"text": "Linked List"
},
{
"code": null,
"e": 5727,
"s": 5721,
"text": "Stack"
},
{
"code": null,
"e": 5733,
"s": 5727,
"text": "Queue"
},
{
"code": null,
"e": 5745,
"s": 5733,
"text": "Binary Tree"
},
{
"code": null,
"e": 5764,
"s": 5745,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 5769,
"s": 5764,
"text": "Heap"
},
{
"code": null,
"e": 5777,
"s": 5769,
"text": "Hashing"
},
{
"code": null,
"e": 5783,
"s": 5777,
"text": "Graph"
},
{
"code": null,
"e": 5807,
"s": 5783,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 5814,
"s": 5807,
"text": "Matrix"
},
{
"code": null,
"e": 5822,
"s": 5814,
"text": "Strings"
},
{
"code": null,
"e": 5842,
"s": 5822,
"text": "All Data Structures"
},
{
"code": null,
"e": 6062,
"s": 5842,
"text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes"
},
{
"code": null,
"e": 6082,
"s": 6062,
"text": "Company Preparation"
},
{
"code": null,
"e": 6093,
"s": 6082,
"text": "Top Topics"
},
{
"code": null,
"e": 6120,
"s": 6093,
"text": "Practice Company Questions"
},
{
"code": null,
"e": 6142,
"s": 6120,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6165,
"s": 6142,
"text": "Experienced Interviews"
},
{
"code": null,
"e": 6187,
"s": 6165,
"text": "Internship Interviews"
},
{
"code": null,
"e": 6212,
"s": 6187,
"text": "Competititve Programming"
},
{
"code": null,
"e": 6228,
"s": 6212,
"text": "Design Patterns"
},
{
"code": null,
"e": 6251,
"s": 6228,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 6275,
"s": 6251,
"text": "Multiple Choice Quizzes"
},
{
"code": null,
"e": 6356,
"s": 6275,
"text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin"
},
{
"code": null,
"e": 6358,
"s": 6356,
"text": "C"
},
{
"code": null,
"e": 6362,
"s": 6358,
"text": "C++"
},
{
"code": null,
"e": 6367,
"s": 6362,
"text": "Java"
},
{
"code": null,
"e": 6374,
"s": 6367,
"text": "Python"
},
{
"code": null,
"e": 6377,
"s": 6374,
"text": "C#"
},
{
"code": null,
"e": 6388,
"s": 6377,
"text": "JavaScript"
},
{
"code": null,
"e": 6395,
"s": 6388,
"text": "jQuery"
},
{
"code": null,
"e": 6399,
"s": 6395,
"text": "SQL"
},
{
"code": null,
"e": 6403,
"s": 6399,
"text": "PHP"
},
{
"code": null,
"e": 6409,
"s": 6403,
"text": "Scala"
},
{
"code": null,
"e": 6414,
"s": 6409,
"text": "Perl"
},
{
"code": null,
"e": 6426,
"s": 6414,
"text": "Go Language"
},
{
"code": null,
"e": 6431,
"s": 6426,
"text": "HTML"
},
{
"code": null,
"e": 6435,
"s": 6431,
"text": "CSS"
},
{
"code": null,
"e": 6442,
"s": 6435,
"text": "Kotlin"
},
{
"code": null,
"e": 6609,
"s": 6442,
"text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering"
},
{
"code": null,
"e": 6621,
"s": 6609,
"text": "Mathematics"
},
{
"code": null,
"e": 6638,
"s": 6621,
"text": "Operating System"
},
{
"code": null,
"e": 6643,
"s": 6638,
"text": "DBMS"
},
{
"code": null,
"e": 6661,
"s": 6643,
"text": "Computer Networks"
},
{
"code": null,
"e": 6700,
"s": 6661,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 6722,
"s": 6700,
"text": "Theory of Computation"
},
{
"code": null,
"e": 6738,
"s": 6722,
"text": "Compiler Design"
},
{
"code": null,
"e": 6752,
"s": 6738,
"text": "Digital Logic"
},
{
"code": null,
"e": 6773,
"s": 6752,
"text": "Software Engineering"
},
{
"code": null,
"e": 6948,
"s": 6773,
"text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS"
},
{
"code": null,
"e": 6976,
"s": 6948,
"text": "GATE Computer Science Notes"
},
{
"code": null,
"e": 6994,
"s": 6976,
"text": "Last Minute Notes"
},
{
"code": null,
"e": 7016,
"s": 6994,
"text": "GATE CS Solved Papers"
},
{
"code": null,
"e": 7058,
"s": 7016,
"text": "GATE CS Original Papers and Official Keys"
},
{
"code": null,
"e": 7074,
"s": 7058,
"text": "GATE 2021 Dates"
},
{
"code": null,
"e": 7096,
"s": 7074,
"text": "GATE CS 2021 Syllabus"
},
{
"code": null,
"e": 7125,
"s": 7096,
"text": "Important Topics for GATE CS"
},
{
"code": null,
"e": 7199,
"s": 7125,
"text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP"
},
{
"code": null,
"e": 7204,
"s": 7199,
"text": "HTML"
},
{
"code": null,
"e": 7208,
"s": 7204,
"text": "CSS"
},
{
"code": null,
"e": 7219,
"s": 7208,
"text": "JavaScript"
},
{
"code": null,
"e": 7229,
"s": 7219,
"text": "AngularJS"
},
{
"code": null,
"e": 7237,
"s": 7229,
"text": "ReactJS"
},
{
"code": null,
"e": 7244,
"s": 7237,
"text": "NodeJS"
},
{
"code": null,
"e": 7254,
"s": 7244,
"text": "Bootstrap"
},
{
"code": null,
"e": 7261,
"s": 7254,
"text": "jQuery"
},
{
"code": null,
"e": 7265,
"s": 7261,
"text": "PHP"
},
{
"code": null,
"e": 7328,
"s": 7265,
"text": "Software DesignsSoftware Design PatternsSystem Design Tutorial"
},
{
"code": null,
"e": 7353,
"s": 7328,
"text": "Software Design Patterns"
},
{
"code": null,
"e": 7376,
"s": 7353,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 7933,
"s": 7376,
"text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 7952,
"s": 7933,
"text": "School Programming"
},
{
"code": null,
"e": 8044,
"s": 7952,
"text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus"
},
{
"code": null,
"e": 8058,
"s": 8044,
"text": "Number System"
},
{
"code": null,
"e": 8066,
"s": 8058,
"text": "Algebra"
},
{
"code": null,
"e": 8079,
"s": 8066,
"text": "Trigonometry"
},
{
"code": null,
"e": 8090,
"s": 8079,
"text": "Statistics"
},
{
"code": null,
"e": 8102,
"s": 8090,
"text": "Probability"
},
{
"code": null,
"e": 8111,
"s": 8102,
"text": "Geometry"
},
{
"code": null,
"e": 8123,
"s": 8111,
"text": "Mensuration"
},
{
"code": null,
"e": 8132,
"s": 8123,
"text": "Calculus"
},
{
"code": null,
"e": 8225,
"s": 8132,
"text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes"
},
{
"code": null,
"e": 8239,
"s": 8225,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8253,
"s": 8239,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8268,
"s": 8253,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8283,
"s": 8268,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 8298,
"s": 8283,
"text": "Class 12 Notes"
},
{
"code": null,
"e": 8427,
"s": 8298,
"text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8450,
"s": 8427,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8473,
"s": 8450,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8497,
"s": 8473,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8521,
"s": 8497,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8545,
"s": 8521,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8678,
"s": 8545,
"text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8701,
"s": 8678,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8724,
"s": 8701,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8748,
"s": 8724,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8772,
"s": 8748,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8796,
"s": 8772,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8877,
"s": 8796,
"text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 8891,
"s": 8877,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8905,
"s": 8891,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8920,
"s": 8905,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8935,
"s": 8920,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 9141,
"s": 8935,
"text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9252,
"s": 9141,
"text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9294,
"s": 9252,
"text": "ISRO CS Original Papers and Official Keys"
},
{
"code": null,
"e": 9316,
"s": 9294,
"text": "ISRO CS Solved Papers"
},
{
"code": null,
"e": 9361,
"s": 9316,
"text": "ISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9444,
"s": 9361,
"text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9470,
"s": 9444,
"text": "UGC NET CS Notes Paper II"
},
{
"code": null,
"e": 9497,
"s": 9470,
"text": "UGC NET CS Notes Paper III"
},
{
"code": null,
"e": 9522,
"s": 9497,
"text": "UGC NET CS Solved Papers"
},
{
"code": null,
"e": 9712,
"s": 9522,
"text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship"
},
{
"code": null,
"e": 9738,
"s": 9712,
"text": "Campus Ambassador Program"
},
{
"code": null,
"e": 9764,
"s": 9738,
"text": "School Ambassador Program"
},
{
"code": null,
"e": 9772,
"s": 9764,
"text": "Project"
},
{
"code": null,
"e": 9790,
"s": 9772,
"text": "Geek of the Month"
},
{
"code": null,
"e": 9815,
"s": 9790,
"text": "Campus Geek of the Month"
},
{
"code": null,
"e": 9832,
"s": 9815,
"text": "Placement Course"
},
{
"code": null,
"e": 9857,
"s": 9832,
"text": "Competititve Programming"
},
{
"code": null,
"e": 9870,
"s": 9857,
"text": "Testimonials"
},
{
"code": null,
"e": 9886,
"s": 9870,
"text": "Geek on the Top"
},
{
"code": null,
"e": 9894,
"s": 9886,
"text": "Careers"
},
{
"code": null,
"e": 9905,
"s": 9894,
"text": "Internship"
},
{
"code": null,
"e": 9944,
"s": 9905,
"text": "JobsApply for JobsPost a JobJOB-A-THON"
},
{
"code": null,
"e": 9959,
"s": 9944,
"text": "Apply for Jobs"
},
{
"code": null,
"e": 9970,
"s": 9959,
"text": "Post a Job"
},
{
"code": null,
"e": 9981,
"s": 9970,
"text": "JOB-A-THON"
},
{
"code": null,
"e": 9988,
"s": 9981,
"text": "Events"
},
{
"code": null,
"e": 10259,
"s": 9992,
"text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri"
},
{
"code": null,
"e": 10272,
"s": 10259,
"text": "Geeks Digest"
},
{
"code": null,
"e": 10280,
"s": 10272,
"text": "Quizzes"
},
{
"code": null,
"e": 10293,
"s": 10280,
"text": "Geeks Campus"
},
{
"code": null,
"e": 10308,
"s": 10293,
"text": "Gblog Articles"
},
{
"code": null,
"e": 10312,
"s": 10308,
"text": "IDE"
},
{
"code": null,
"e": 10326,
"s": 10312,
"text": "Campus Mantri"
},
{
"code": null,
"e": 10334,
"s": 10326,
"text": "Sign In"
},
{
"code": null,
"e": 10342,
"s": 10334,
"text": "Sign In"
},
{
"code": null,
"e": 10347,
"s": 10342,
"text": "Home"
},
{
"code": null,
"e": 10360,
"s": 10347,
"text": "Saved Videos"
},
{
"code": null,
"e": 10368,
"s": 10360,
"text": "Courses"
},
{
"code": null,
"e": 14481,
"s": 10368,
"text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\n\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n"
},
{
"code": null,
"e": 14535,
"s": 14481,
"text": "\nFor Working Professionals\n \n\n"
},
{
"code": null,
"e": 14658,
"s": 14535,
"text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n"
},
{
"code": null,
"e": 14677,
"s": 14658,
"text": "\nDSA Live Classes\n"
},
{
"code": null,
"e": 14693,
"s": 14677,
"text": "\nSystem Design\n"
},
{
"code": null,
"e": 14720,
"s": 14693,
"text": "\nJava Backend Development\n"
},
{
"code": null,
"e": 14738,
"s": 14720,
"text": "\nFull Stack LIVE\n"
},
{
"code": null,
"e": 14753,
"s": 14738,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 14861,
"s": 14753,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n"
},
{
"code": null,
"e": 14879,
"s": 14861,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 14892,
"s": 14879,
"text": "\nSDE Theory\n"
},
{
"code": null,
"e": 14919,
"s": 14892,
"text": "\nMust-Do Coding Questions\n"
},
{
"code": null,
"e": 14934,
"s": 14919,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 14975,
"s": 14934,
"text": "\nFor Students\n \n\n"
},
{
"code": null,
"e": 15087,
"s": 14975,
"text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n"
},
{
"code": null,
"e": 15113,
"s": 15087,
"text": "\nCompetitive Programming\n"
},
{
"code": null,
"e": 15140,
"s": 15113,
"text": "\nData Structures with C++\n"
},
{
"code": null,
"e": 15155,
"s": 15140,
"text": "\nData Science\n"
},
{
"code": null,
"e": 15170,
"s": 15155,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15266,
"s": 15170,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n"
},
{
"code": null,
"e": 15284,
"s": 15266,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 15290,
"s": 15284,
"text": "\nCIP\n"
},
{
"code": null,
"e": 15312,
"s": 15290,
"text": "\nJAVA / Python / C++\n"
},
{
"code": null,
"e": 15327,
"s": 15312,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15424,
"s": 15327,
"text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n"
},
{
"code": null,
"e": 15439,
"s": 15424,
"text": "\nSchool Guide\n"
},
{
"code": null,
"e": 15460,
"s": 15439,
"text": "\nPython Programming\n"
},
{
"code": null,
"e": 15481,
"s": 15460,
"text": "\nLearn To Make Apps\n"
},
{
"code": null,
"e": 15582,
"s": 15481,
"text": "\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n"
},
{
"code": null,
"e": 15602,
"s": 15582,
"text": "\nMust Do Questions\n"
},
{
"code": null,
"e": 15619,
"s": 15602,
"text": "\nDSA Topic-wise\n"
},
{
"code": null,
"e": 15638,
"s": 15619,
"text": "\nDSA Company-wise\n"
},
{
"code": null,
"e": 15943,
"s": 15638,
"text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n"
},
{
"code": null,
"e": 15966,
"s": 15943,
"text": "\nSearching Algorithms\n"
},
{
"code": null,
"e": 15987,
"s": 15966,
"text": "\nSorting Algorithms\n"
},
{
"code": null,
"e": 16006,
"s": 15987,
"text": "\nGraph Algorithms\n"
},
{
"code": null,
"e": 16026,
"s": 16006,
"text": "\nPattern Searching\n"
},
{
"code": null,
"e": 16049,
"s": 16026,
"text": "\nGeometric Algorithms\n"
},
{
"code": null,
"e": 16064,
"s": 16049,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 16085,
"s": 16064,
"text": "\nBitwise Algorithms\n"
},
{
"code": null,
"e": 16109,
"s": 16085,
"text": "\nRandomized Algorithms\n"
},
{
"code": null,
"e": 16129,
"s": 16109,
"text": "\nGreedy Algorithms\n"
},
{
"code": null,
"e": 16151,
"s": 16129,
"text": "\nDynamic Programming\n"
},
{
"code": null,
"e": 16172,
"s": 16151,
"text": "\nDivide and Conquer\n"
},
{
"code": null,
"e": 16187,
"s": 16172,
"text": "\nBacktracking\n"
},
{
"code": null,
"e": 16206,
"s": 16187,
"text": "\nBranch and Bound\n"
},
{
"code": null,
"e": 16223,
"s": 16206,
"text": "\nAll Algorithms\n"
},
{
"code": null,
"e": 16608,
"s": 16223,
"text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n"
},
{
"code": null,
"e": 16630,
"s": 16608,
"text": "\nAsymptotic Analysis\n"
},
{
"code": null,
"e": 16662,
"s": 16630,
"text": "\nWorst, Average and Best Cases\n"
},
{
"code": null,
"e": 16685,
"s": 16662,
"text": "\nAsymptotic Notations\n"
},
{
"code": null,
"e": 16723,
"s": 16685,
"text": "\nLittle o and little omega notations\n"
},
{
"code": null,
"e": 16754,
"s": 16723,
"text": "\nLower and Upper Bound Theory\n"
},
{
"code": null,
"e": 16774,
"s": 16754,
"text": "\nAnalysis of Loops\n"
},
{
"code": null,
"e": 16796,
"s": 16774,
"text": "\nSolving Recurrences\n"
},
{
"code": null,
"e": 16817,
"s": 16796,
"text": "\nAmortized Analysis\n"
},
{
"code": null,
"e": 16855,
"s": 16817,
"text": "\nWhat does 'Space Complexity' mean ?\n"
},
{
"code": null,
"e": 16886,
"s": 16855,
"text": "\nPseudo-polynomial Algorithms\n"
},
{
"code": null,
"e": 16925,
"s": 16886,
"text": "\nPolynomial Time Approximation Scheme\n"
},
{
"code": null,
"e": 16954,
"s": 16925,
"text": "\nA Time Complexity Question\n"
},
{
"code": null,
"e": 17151,
"s": 16954,
"text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n"
},
{
"code": null,
"e": 17160,
"s": 17151,
"text": "\nArrays\n"
},
{
"code": null,
"e": 17174,
"s": 17160,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 17182,
"s": 17174,
"text": "\nStack\n"
},
{
"code": null,
"e": 17190,
"s": 17182,
"text": "\nQueue\n"
},
{
"code": null,
"e": 17204,
"s": 17190,
"text": "\nBinary Tree\n"
},
{
"code": null,
"e": 17225,
"s": 17204,
"text": "\nBinary Search Tree\n"
},
{
"code": null,
"e": 17232,
"s": 17225,
"text": "\nHeap\n"
},
{
"code": null,
"e": 17242,
"s": 17232,
"text": "\nHashing\n"
},
{
"code": null,
"e": 17250,
"s": 17242,
"text": "\nGraph\n"
},
{
"code": null,
"e": 17276,
"s": 17250,
"text": "\nAdvanced Data Structure\n"
},
{
"code": null,
"e": 17285,
"s": 17276,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 17295,
"s": 17285,
"text": "\nStrings\n"
},
{
"code": null,
"e": 17317,
"s": 17295,
"text": "\nAll Data Structures\n"
},
{
"code": null,
"e": 17585,
"s": 17317,
"text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 17607,
"s": 17585,
"text": "\nCompany Preparation\n"
},
{
"code": null,
"e": 17620,
"s": 17607,
"text": "\nTop Topics\n"
},
{
"code": null,
"e": 17649,
"s": 17620,
"text": "\nPractice Company Questions\n"
},
{
"code": null,
"e": 17673,
"s": 17649,
"text": "\nInterview Experiences\n"
},
{
"code": null,
"e": 17698,
"s": 17673,
"text": "\nExperienced Interviews\n"
},
{
"code": null,
"e": 17722,
"s": 17698,
"text": "\nInternship Interviews\n"
},
{
"code": null,
"e": 17749,
"s": 17722,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 17767,
"s": 17749,
"text": "\nDesign Patterns\n"
},
{
"code": null,
"e": 17792,
"s": 17767,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 17818,
"s": 17792,
"text": "\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 17957,
"s": 17818,
"text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n"
},
{
"code": null,
"e": 17961,
"s": 17957,
"text": "\nC\n"
},
{
"code": null,
"e": 17967,
"s": 17961,
"text": "\nC++\n"
},
{
"code": null,
"e": 17974,
"s": 17967,
"text": "\nJava\n"
},
{
"code": null,
"e": 17983,
"s": 17974,
"text": "\nPython\n"
},
{
"code": null,
"e": 17988,
"s": 17983,
"text": "\nC#\n"
},
{
"code": null,
"e": 18001,
"s": 17988,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 18010,
"s": 18001,
"text": "\njQuery\n"
},
{
"code": null,
"e": 18016,
"s": 18010,
"text": "\nSQL\n"
},
{
"code": null,
"e": 18022,
"s": 18016,
"text": "\nPHP\n"
},
{
"code": null,
"e": 18030,
"s": 18022,
"text": "\nScala\n"
},
{
"code": null,
"e": 18037,
"s": 18030,
"text": "\nPerl\n"
},
{
"code": null,
"e": 18051,
"s": 18037,
"text": "\nGo Language\n"
},
{
"code": null,
"e": 18058,
"s": 18051,
"text": "\nHTML\n"
},
{
"code": null,
"e": 18064,
"s": 18058,
"text": "\nCSS\n"
},
{
"code": null,
"e": 18073,
"s": 18064,
"text": "\nKotlin\n"
},
{
"code": null,
"e": 18286,
"s": 18073,
"text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n"
},
{
"code": null,
"e": 18300,
"s": 18286,
"text": "\nMathematics\n"
},
{
"code": null,
"e": 18319,
"s": 18300,
"text": "\nOperating System\n"
},
{
"code": null,
"e": 18326,
"s": 18319,
"text": "\nDBMS\n"
},
{
"code": null,
"e": 18346,
"s": 18326,
"text": "\nComputer Networks\n"
},
{
"code": null,
"e": 18387,
"s": 18346,
"text": "\nComputer Organization and Architecture\n"
},
{
"code": null,
"e": 18411,
"s": 18387,
"text": "\nTheory of Computation\n"
},
{
"code": null,
"e": 18429,
"s": 18411,
"text": "\nCompiler Design\n"
},
{
"code": null,
"e": 18445,
"s": 18429,
"text": "\nDigital Logic\n"
},
{
"code": null,
"e": 18468,
"s": 18445,
"text": "\nSoftware Engineering\n"
},
{
"code": null,
"e": 18685,
"s": 18468,
"text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 18715,
"s": 18685,
"text": "\nGATE Computer Science Notes\n"
},
{
"code": null,
"e": 18735,
"s": 18715,
"text": "\nLast Minute Notes\n"
},
{
"code": null,
"e": 18759,
"s": 18735,
"text": "\nGATE CS Solved Papers\n"
},
{
"code": null,
"e": 18803,
"s": 18759,
"text": "\nGATE CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 18821,
"s": 18803,
"text": "\nGATE 2021 Dates\n"
},
{
"code": null,
"e": 18845,
"s": 18821,
"text": "\nGATE CS 2021 Syllabus\n"
},
{
"code": null,
"e": 18876,
"s": 18845,
"text": "\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 18996,
"s": 18876,
"text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n"
},
{
"code": null,
"e": 19003,
"s": 18996,
"text": "\nHTML\n"
},
{
"code": null,
"e": 19009,
"s": 19003,
"text": "\nCSS\n"
},
{
"code": null,
"e": 19022,
"s": 19009,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 19034,
"s": 19022,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 19044,
"s": 19034,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 19053,
"s": 19044,
"text": "\nNodeJS\n"
},
{
"code": null,
"e": 19065,
"s": 19053,
"text": "\nBootstrap\n"
},
{
"code": null,
"e": 19074,
"s": 19065,
"text": "\njQuery\n"
},
{
"code": null,
"e": 19080,
"s": 19074,
"text": "\nPHP\n"
},
{
"code": null,
"e": 19175,
"s": 19080,
"text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 19202,
"s": 19175,
"text": "\nSoftware Design Patterns\n"
},
{
"code": null,
"e": 19227,
"s": 19202,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 19291,
"s": 19227,
"text": "\nSchool Learning\n \n\n\nSchool Programming\n"
},
{
"code": null,
"e": 19312,
"s": 19291,
"text": "\nSchool Programming\n"
},
{
"code": null,
"e": 19448,
"s": 19312,
"text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n"
},
{
"code": null,
"e": 19464,
"s": 19448,
"text": "\nNumber System\n"
},
{
"code": null,
"e": 19474,
"s": 19464,
"text": "\nAlgebra\n"
},
{
"code": null,
"e": 19489,
"s": 19474,
"text": "\nTrigonometry\n"
},
{
"code": null,
"e": 19502,
"s": 19489,
"text": "\nStatistics\n"
},
{
"code": null,
"e": 19516,
"s": 19502,
"text": "\nProbability\n"
},
{
"code": null,
"e": 19527,
"s": 19516,
"text": "\nGeometry\n"
},
{
"code": null,
"e": 19541,
"s": 19527,
"text": "\nMensuration\n"
},
{
"code": null,
"e": 19552,
"s": 19541,
"text": "\nCalculus\n"
},
{
"code": null,
"e": 19683,
"s": 19552,
"text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n"
},
{
"code": null,
"e": 19699,
"s": 19683,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 19715,
"s": 19699,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 19732,
"s": 19715,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 19749,
"s": 19732,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 19766,
"s": 19749,
"text": "\nClass 12 Notes\n"
},
{
"code": null,
"e": 19933,
"s": 19766,
"text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 19958,
"s": 19933,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 19983,
"s": 19958,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 20009,
"s": 19983,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 20035,
"s": 20009,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 20061,
"s": 20035,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20232,
"s": 20061,
"text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20257,
"s": 20232,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 20282,
"s": 20257,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 20308,
"s": 20282,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 20334,
"s": 20308,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 20360,
"s": 20334,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20477,
"s": 20360,
"text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n"
},
{
"code": null,
"e": 20493,
"s": 20477,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 20509,
"s": 20493,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 20526,
"s": 20509,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 20543,
"s": 20526,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 20585,
"s": 20543,
"text": "\nCS Exams/PSUs\n \n\n"
},
{
"code": null,
"e": 20730,
"s": 20585,
"text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 20774,
"s": 20730,
"text": "\nISRO CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 20798,
"s": 20774,
"text": "\nISRO CS Solved Papers\n"
},
{
"code": null,
"e": 20845,
"s": 20798,
"text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 20962,
"s": 20845,
"text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 20990,
"s": 20962,
"text": "\nUGC NET CS Notes Paper II\n"
},
{
"code": null,
"e": 21019,
"s": 20990,
"text": "\nUGC NET CS Notes Paper III\n"
},
{
"code": null,
"e": 21046,
"s": 21019,
"text": "\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 21286,
"s": 21046,
"text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n"
},
{
"code": null,
"e": 21314,
"s": 21286,
"text": "\nCampus Ambassador Program\n"
},
{
"code": null,
"e": 21342,
"s": 21314,
"text": "\nSchool Ambassador Program\n"
},
{
"code": null,
"e": 21352,
"s": 21342,
"text": "\nProject\n"
},
{
"code": null,
"e": 21372,
"s": 21352,
"text": "\nGeek of the Month\n"
},
{
"code": null,
"e": 21399,
"s": 21372,
"text": "\nCampus Geek of the Month\n"
},
{
"code": null,
"e": 21418,
"s": 21399,
"text": "\nPlacement Course\n"
},
{
"code": null,
"e": 21445,
"s": 21418,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 21460,
"s": 21445,
"text": "\nTestimonials\n"
},
{
"code": null,
"e": 21478,
"s": 21460,
"text": "\nGeek on the Top\n"
},
{
"code": null,
"e": 21488,
"s": 21478,
"text": "\nCareers\n"
},
{
"code": null,
"e": 21501,
"s": 21488,
"text": "\nInternship\n"
},
{
"code": null,
"e": 21539,
"s": 21501,
"text": "\nTutorials\n \n\n"
},
{
"code": null,
"e": 21612,
"s": 21539,
"text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n"
},
{
"code": null,
"e": 21629,
"s": 21612,
"text": "\nApply for Jobs\n"
},
{
"code": null,
"e": 21642,
"s": 21629,
"text": "\nPost a Job\n"
},
{
"code": null,
"e": 21655,
"s": 21642,
"text": "\nJOB-A-THON\n"
},
{
"code": null,
"e": 21661,
"s": 21655,
"text": "GBlog"
},
{
"code": null,
"e": 21669,
"s": 21661,
"text": "Puzzles"
},
{
"code": null,
"e": 21682,
"s": 21669,
"text": "What's New ?"
},
{
"code": null,
"e": 21688,
"s": 21682,
"text": "Array"
},
{
"code": null,
"e": 21695,
"s": 21688,
"text": "Matrix"
},
{
"code": null,
"e": 21703,
"s": 21695,
"text": "Strings"
},
{
"code": null,
"e": 21711,
"s": 21703,
"text": "Hashing"
},
{
"code": null,
"e": 21723,
"s": 21711,
"text": "Linked List"
},
{
"code": null,
"e": 21729,
"s": 21723,
"text": "Stack"
},
{
"code": null,
"e": 21735,
"s": 21729,
"text": "Queue"
},
{
"code": null,
"e": 21747,
"s": 21735,
"text": "Binary Tree"
},
{
"code": null,
"e": 21766,
"s": 21747,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 21771,
"s": 21766,
"text": "Heap"
},
{
"code": null,
"e": 21777,
"s": 21771,
"text": "Graph"
},
{
"code": null,
"e": 21787,
"s": 21777,
"text": "Searching"
},
{
"code": null,
"e": 21795,
"s": 21787,
"text": "Sorting"
},
{
"code": null,
"e": 21812,
"s": 21795,
"text": "Divide & Conquer"
},
{
"code": null,
"e": 21825,
"s": 21812,
"text": "Mathematical"
},
{
"code": null,
"e": 21835,
"s": 21825,
"text": "Geometric"
},
{
"code": null,
"e": 21843,
"s": 21835,
"text": "Bitwise"
},
{
"code": null,
"e": 21850,
"s": 21843,
"text": "Greedy"
},
{
"code": null,
"e": 21863,
"s": 21850,
"text": "Backtracking"
},
{
"code": null,
"e": 21880,
"s": 21863,
"text": "Branch and Bound"
},
{
"code": null,
"e": 21900,
"s": 21880,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 21918,
"s": 21900,
"text": "Pattern Searching"
},
{
"code": null,
"e": 21929,
"s": 21918,
"text": "Randomized"
},
{
"code": null,
"e": 21978,
"s": 21929,
"text": "0-1 BFS (Shortest Path in a Binary Weight Graph)"
},
{
"code": null,
"e": 22015,
"s": 21978,
"text": "Shortest path in an unweighted graph"
},
{
"code": null,
"e": 22073,
"s": 22015,
"text": "Kruskalβs Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 22124,
"s": 22073,
"text": "Primβs Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 22185,
"s": 22124,
"text": "Primβs MST for Adjacency List Representation | Greedy Algo-6"
},
{
"code": null,
"e": 22236,
"s": 22185,
"text": "Dijkstraβs shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 22307,
"s": 22236,
"text": "Dijkstraβs Algorithm for Adjacency List Representation | Greedy Algo-8"
},
{
"code": null,
"e": 22359,
"s": 22307,
"text": "Dijkstraβs shortest path algorithm using set in STL"
},
{
"code": null,
"e": 22422,
"s": 22359,
"text": "Dijkstraβs Shortest Path Algorithm using priority_queue of STL"
},
{
"code": null,
"e": 22485,
"s": 22422,
"text": "Dijkstraβs shortest path algorithm in Java using PriorityQueue"
},
{
"code": null,
"e": 22553,
"s": 22485,
"text": "Java Program for Dijkstraβs shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 22610,
"s": 22553,
"text": "Java Program for Dijkstraβs Algorithm with Path Printing"
},
{
"code": null,
"e": 22663,
"s": 22610,
"text": "Printing Paths in Dijkstraβs Shortest Path Algorithm"
},
{
"code": null,
"e": 22731,
"s": 22663,
"text": "Shortest Path in a weighted Graph where weight of an edge is 1 or 2"
},
{
"code": null,
"e": 22764,
"s": 22731,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 22806,
"s": 22764,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 22855,
"s": 22806,
"text": "Warnsdorffβs algorithm for Knightβs tour problem"
},
{
"code": null,
"e": 22898,
"s": 22855,
"text": "The Knightβs tour problem | Backtracking-1"
},
{
"code": null,
"e": 22929,
"s": 22898,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 22981,
"s": 22929,
"text": "Count number of ways to reach destination in a Maze"
},
{
"code": null,
"e": 23052,
"s": 22981,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 23123,
"s": 23052,
"text": "Print all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 23161,
"s": 23123,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 23231,
"s": 23161,
"text": "Unique paths covering every non-obstacle block exactly once in a grid"
},
{
"code": null,
"e": 23269,
"s": 23231,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 23309,
"s": 23269,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 23339,
"s": 23309,
"text": "Graph and its representations"
},
{
"code": null,
"e": 23388,
"s": 23339,
"text": "0-1 BFS (Shortest Path in a Binary Weight Graph)"
},
{
"code": null,
"e": 23425,
"s": 23388,
"text": "Shortest path in an unweighted graph"
},
{
"code": null,
"e": 23483,
"s": 23425,
"text": "Kruskalβs Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 23534,
"s": 23483,
"text": "Primβs Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 23595,
"s": 23534,
"text": "Primβs MST for Adjacency List Representation | Greedy Algo-6"
},
{
"code": null,
"e": 23646,
"s": 23595,
"text": "Dijkstraβs shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 23717,
"s": 23646,
"text": "Dijkstraβs Algorithm for Adjacency List Representation | Greedy Algo-8"
},
{
"code": null,
"e": 23769,
"s": 23717,
"text": "Dijkstraβs shortest path algorithm using set in STL"
},
{
"code": null,
"e": 23832,
"s": 23769,
"text": "Dijkstraβs Shortest Path Algorithm using priority_queue of STL"
},
{
"code": null,
"e": 23895,
"s": 23832,
"text": "Dijkstraβs shortest path algorithm in Java using PriorityQueue"
},
{
"code": null,
"e": 23963,
"s": 23895,
"text": "Java Program for Dijkstraβs shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 24020,
"s": 23963,
"text": "Java Program for Dijkstraβs Algorithm with Path Printing"
},
{
"code": null,
"e": 24073,
"s": 24020,
"text": "Printing Paths in Dijkstraβs Shortest Path Algorithm"
},
{
"code": null,
"e": 24141,
"s": 24073,
"text": "Shortest Path in a weighted Graph where weight of an edge is 1 or 2"
},
{
"code": null,
"e": 24174,
"s": 24141,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 24216,
"s": 24174,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 24265,
"s": 24216,
"text": "Warnsdorffβs algorithm for Knightβs tour problem"
},
{
"code": null,
"e": 24308,
"s": 24265,
"text": "The Knightβs tour problem | Backtracking-1"
},
{
"code": null,
"e": 24339,
"s": 24308,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 24391,
"s": 24339,
"text": "Count number of ways to reach destination in a Maze"
},
{
"code": null,
"e": 24462,
"s": 24391,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 24533,
"s": 24462,
"text": "Print all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 24571,
"s": 24533,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 24641,
"s": 24571,
"text": "Unique paths covering every non-obstacle block exactly once in a grid"
},
{
"code": null,
"e": 24679,
"s": 24641,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 24719,
"s": 24679,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 24749,
"s": 24719,
"text": "Graph and its representations"
},
{
"code": null,
"e": 24775,
"s": 24749,
"text": "Difficulty Level :\nMedium"
},
{
"code": null,
"e": 24955,
"s": 24775,
"text": "Given a graph where every edge has weight as either 0 or 1. A source vertex is also given in the graph. Find the shortest path from source vertex to every other vertex. Example: "
},
{
"code": null,
"e": 25213,
"s": 24955,
"text": "Input : Source Vertex = 0 and below graph \n\n\nOutput : Shortest distances from given source\n 0 0 1 1 2 1 2 1 2\n\nExplanation : \nShortest distance from 0 to 0 is 0\nShortest distance from 0 to 1 is 0\nShortest distance from 0 to 2 is 1\n.................."
},
{
"code": null,
"e": 26332,
"s": 25215,
"text": "In normal BFS of a graph all edges have equal weight but in 0-1 BFS some edges may have 0 weight and some may have 1 weight. In this we will not use bool array to mark visited nodes but at each step we will check for the optimal distance condition. We use double ended queue to store the node. While performing BFS if a edge having weight = 0 is found node is pushed at front of double ended queue and if a edge having weight = 1 is found, it is pushed at back of double ended queue.The approach is similar to Dijkstra that the if the shortest distance to node is relaxed by the previous node then only it will be pushed in the queue. The above idea works in all cases, when pop a vertex (like Dijkstra), it is the minimum weight vertex among remaining vertices. If there is a 0 weight vertex adjacent to it, then this adjacent has same distance. If there is a 1 weight adjacent, then this adjacent has maximum distance among all vertices in dequeue (because all other vertices are either adjacent of currently popped vertex or adjacent of previously popped vertices).Below is the implementation of the above idea. "
},
{
"code": null,
"e": 26336,
"s": 26332,
"text": "C++"
},
{
"code": null,
"e": 26341,
"s": 26336,
"text": "Java"
},
{
"code": null,
"e": 26349,
"s": 26341,
"text": "Python3"
},
{
"code": null,
"e": 26360,
"s": 26349,
"text": "Javascript"
},
{
"code": "// C++ program to implement single source// shortest path for a Binary Graph#include<bits/stdc++.h>using namespace std; /* no.of vertices */#define V 9 // a structure to represent edgesstruct node{ // two variable one denote the node // and other the weight int to, weight;}; // vector to store edgesvector <node> edges[V]; // Prints shortest distance from given source to// every other vertexvoid zeroOneBFS(int src){ // Initialize distances from given source int dist[V]; for (int i=0; i<V; i++) dist[i] = INT_MAX; // double ende queue to do BFS. deque <int> Q; dist[src] = 0; Q.push_back(src); while (!Q.empty()) { int v = Q.front(); Q.pop_front(); for (int i=0; i<edges[v].size(); i++) { // checking for the optimal distance if (dist[edges[v][i].to] > dist[v] + edges[v][i].weight) { dist[edges[v][i].to] = dist[v] + edges[v][i].weight; // Put 0 weight edges to front and 1 weight // edges to back so that vertices are processed // in increasing order of weights. if (edges[v][i].weight == 0) Q.push_front(edges[v][i].to); else Q.push_back(edges[v][i].to); } } } // printing the shortest distances for (int i=0; i<V; i++) cout << dist[i] << \" \";} void addEdge(int u, int v, int wt){ edges[u].push_back({v, wt}); edges[v].push_back({u, wt});} // Driver functionint main(){ addEdge(0, 1, 0); addEdge(0, 7, 1); addEdge(1, 7, 1); addEdge(1, 2, 1); addEdge(2, 3, 0); addEdge(2, 5, 0); addEdge(2, 8, 1); addEdge(3, 4, 1); addEdge(3, 5, 1); addEdge(4, 5, 1); addEdge(5, 6, 1); addEdge(6, 7, 1); addEdge(7, 8, 1); int src = 0;//source node zeroOneBFS(src); return 0;}",
"e": 28247,
"s": 26360,
"text": null
},
{
"code": "// Java Program to implement 0-1 BFSimport java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque; public class ZeroOneBFS { private static class Node { int to; // the ending vertex int weight; // the weight of the edge public Node(int to, int wt) { this.to = to; this.weight = wt; } } private static final int numVertex = 9; private ArrayList<Node>[] edges = new ArrayList[numVertex]; public ZeroOneBFS() { for (int i = 0; i < edges.length; i++) { edges[i] = new ArrayList<Node>(); } } public void addEdge(int u, int v, int wt) { edges[u].add(edges[u].size(), new Node(v, wt)); edges[v].add(edges[v].size(), new Node(u, wt)); } public void zeroOneBFS(int src) { // initialize distances from given source int[] dist = new int[numVertex]; for (int i = 0; i < numVertex; i++) { dist[i] = Integer.MAX_VALUE; } // double ended queue to do BFS Deque<Integer> queue = new ArrayDeque<Integer>(); dist[src] = 0; queue.addLast(src); while (!queue.isEmpty()) { int v = queue.removeFirst(); for (int i = 0; i < edges[v].size(); i++) { // checking for optimal distance if (dist[edges[v].get(i).to] > dist[v] + edges[v].get(i).weight) { // update the distance dist[edges[v].get(i).to] = dist[v] + edges[v].get(i).weight; // put 0 weight edges to front and 1 // weight edges to back so that vertices // are processed in increasing order of weight if (edges[v].get(i).weight == 0) { queue.addFirst(edges[v].get(i).to); } else { queue.addLast(edges[v].get(i).to); } } } } for (int i = 0; i < dist.length; i++) { System.out.print(dist[i] + \" \"); } } public static void main(String[] args) { ZeroOneBFS graph = new ZeroOneBFS(); graph.addEdge(0, 1, 0); graph.addEdge(0, 7, 1); graph.addEdge(1, 7, 1); graph.addEdge(1, 2, 1); graph.addEdge(2, 3, 0); graph.addEdge(2, 5, 0); graph.addEdge(2, 8, 1); graph.addEdge(3, 4, 1); graph.addEdge(3, 5, 1); graph.addEdge(4, 5, 1); graph.addEdge(5, 6, 1); graph.addEdge(6, 7, 1); graph.addEdge(7, 8, 1); int src = 0;//source node graph.zeroOneBFS(src); return; }}",
"e": 30985,
"s": 28247,
"text": null
},
{
"code": "# Python3 program to implement single source# shortest path for a Binary Graphfrom sys import maxsize as INT_MAXfrom collections import deque # no.of verticesV = 9 # a structure to represent edgesclass node: def __init__(self, to, weight): # two variable one denote the node # and other the weight self.to = to self.weight = weight # vector to store edgesedges = [0] * Vfor i in range(V): edges[i] = [] # Prints shortest distance from# given source to every other vertexdef zeroOneBFS(src: int): # Initialize distances from given source dist = [0] * V for i in range(V): dist[i] = INT_MAX # double ende queue to do BFS. Q = deque() dist[src] = 0 Q.append(src) while Q: v = Q[0] Q.popleft() for i in range(len(edges[v])): # checking for the optimal distance if (dist[edges[v][i].to] > dist[v] + edges[v][i].weight): dist[edges[v][i].to] = dist[v] + edges[v][i].weight # Put 0 weight edges to front and 1 weight # edges to back so that vertices are processed # in increasing order of weights. if edges[v][i].weight == 0: Q.appendleft(edges[v][i].to) else: Q.append(edges[v][i].to) # printing the shortest distances for i in range(V): print(dist[i], end = \" \") print() def addEdge(u: int, v: int, wt: int): edges[u].append(node(v, wt)) edges[u].append(node(v, wt)) # Driver Codeif __name__ == \"__main__\": addEdge(0, 1, 0) addEdge(0, 7, 1) addEdge(1, 7, 1) addEdge(1, 2, 1) addEdge(2, 3, 0) addEdge(2, 5, 0) addEdge(2, 8, 1) addEdge(3, 4, 1) addEdge(3, 5, 1) addEdge(4, 5, 1) addEdge(5, 6, 1) addEdge(6, 7, 1) addEdge(7, 8, 1) # source node src = 0 zeroOneBFS(src) # This code is contributed by# sanjeev2552",
"e": 32920,
"s": 30985,
"text": null
},
{
"code": "<script>// Javascript Program to implement 0-1 BFS class Node{ constructor(to,wt) { this.to = to; this.weight = wt; } } let numVertex = 9;let edges = new Array(numVertex); function _ZeroOneBFS(){ for (let i = 0; i < edges.length; i++) { edges[i] = []; }} function addEdge(u,v,wt){ edges[u].push(edges[u].length, new Node(v, wt)); edges[v].push(edges[v].length, new Node(u, wt));} function zeroOneBFS(src){ // initialize distances from given source let dist = new Array(numVertex); for (let i = 0; i < numVertex; i++) { dist[i] = Number.MAX_VALUE; } // double ended queue to do BFS let queue = []; dist[src] = 0; queue.push(src); while (queue.length!=0) { let v = queue.shift(); for (let i = 0; i < edges[v].length; i++) { // checking for optimal distance if (dist[edges[v][i].to] > dist[v] + edges[v][i].weight) { // update the distance dist[edges[v][i].to] = dist[v] + edges[v][i].weight; // put 0 weight edges to front and 1 // weight edges to back so that vertices // are processed in increasing order of weight if (edges[v][i].weight == 0) { queue.unshift(edges[v][i].to); } else { queue.push(edges[v][i].to); } } } } for (let i = 0; i < dist.length; i++) { document.write(dist[i] + \" \"); }} _ZeroOneBFS();addEdge(0, 1, 0);addEdge(0, 7, 1);addEdge(1, 7, 1);addEdge(1, 2, 1);addEdge(2, 3, 0);addEdge(2, 5, 0);addEdge(2, 8, 1);addEdge(3, 4, 1);addEdge(3, 5, 1);addEdge(4, 5, 1);addEdge(5, 6, 1);addEdge(6, 7, 1);addEdge(7, 8, 1);let src = 0;//source nodezeroOneBFS(src); // This code is contributed by avanitrachhadiya2155</script>",
"e": 34984,
"s": 32920,
"text": null
},
{
"code": null,
"e": 34994,
"s": 34984,
"text": "Output: "
},
{
"code": null,
"e": 35013,
"s": 34994,
"text": "0 0 1 1 2 1 2 1 2 "
},
{
"code": null,
"e": 35605,
"s": 35013,
"text": "This problem can also be solved by Dijkstra but the time complexity will be O(E + V Log V) whereas by BFS it will be O(V+E).Reference : http://codeforces.com/blog/entry/22276This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 35620,
"s": 35605,
"text": "Ankit Bansal 2"
},
{
"code": null,
"e": 35632,
"s": 35620,
"text": "sanjeev2552"
},
{
"code": null,
"e": 35653,
"s": 35632,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 35657,
"s": 35653,
"text": "BFS"
},
{
"code": null,
"e": 35663,
"s": 35657,
"text": "deque"
},
{
"code": null,
"e": 35677,
"s": 35663,
"text": "Shortest Path"
},
{
"code": null,
"e": 35683,
"s": 35677,
"text": "Graph"
},
{
"code": null,
"e": 35689,
"s": 35683,
"text": "Graph"
},
{
"code": null,
"e": 35703,
"s": 35689,
"text": "Shortest Path"
},
{
"code": null,
"e": 35707,
"s": 35703,
"text": "BFS"
},
{
"code": null,
"e": 35805,
"s": 35707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35814,
"s": 35805,
"text": "Comments"
},
{
"code": null,
"e": 35827,
"s": 35814,
"text": "Old Comments"
},
{
"code": null,
"e": 35847,
"s": 35827,
"text": "Topological Sorting"
},
{
"code": null,
"e": 35880,
"s": 35847,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 35911,
"s": 35880,
"text": "BellmanβFord Algorithm | DP-23"
},
{
"code": null,
"e": 35944,
"s": 35911,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 36012,
"s": 35944,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 36087,
"s": 36012,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 36123,
"s": 36087,
"text": "Detect cycle in an undirected graph"
},
{
"code": null,
"e": 36173,
"s": 36123,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 36221,
"s": 36173,
"text": "Traveling Salesman Problem (TSP) Implementation"
}
] |
How to Create Animated Visualizations with Plotly | by Soner YΔ±ldΔ±rΔ±m | Towards Data Science
|
We live in the era of big data. We can collect lots of data which allows to infer meaningful results and make informed business decisions. However, as the amount of data increases, it gets trickier to analyze and explore the data. There comes in the power of visualizations which are great tools in exploratory data analysis when used efficiently and appropriately. Visualizations also help to deliver a message to your audience or inform them about your findings. There is no one-fits-all kind of visualization method so certain tasks require different kinds of visualizations. In recents years, animated visualizations have gained more popularity as they make it possible to βtellβ much more than a statis visualization. Animated visualizations are great at showing how things change over time.
We will cover how to create animated visuzalizations with Plotly Python (plotly.py) which is an open-source plotting library built on plotly javascript (plotly.js). One of the things I like about plotly.py is that it offers a high-level API (plotly express) and a low level API (graph objects) to create visualizations. With plotly express, we can create a nice plot with very few lines of code. On the other hand, we need to write more code with graph objects but have more control on what we create.
In this post, we will use plotly express API. I will write up another post to cover animated visualizations with graph objects.
We will merge two different datasets. One is obesity rate dataset which available here on kaggle. The raw dataset needs to be cleaned and reformatted. If youβd like to go through the data cleaning steps, feel free to visit my post on that:
towardsdatascience.com
Here is the first five rows of the cleaned dataframe:
The other dataset that we will use is not separating gender. Thus, we need to eliminate gender on this dataset by grouping on βcountryβ and βyearβ and taking the mean of βobesity_rateβ:
import numpy as npimport pandas as pd# fixing data tytpesobesity_cleaned = df2.astype({'obesity_rate': 'float32', 'year': 'int32'})# eliminating genderobesity_cleaned = obesity_cleaned.groupby(['country','year']).mean().reset_index()obesity_cleaned.head()
The other dataset is available as built-in dataset of plotly express. It is called gapminder and includes life expectancy, gdp per capita, population of 142 countries from 1952 to 2007 (with 5-year-increments). We first import plotly express and the dataset:
import plotly.express as pxdf_gdp = px.data.gapminder()df_gdp.head()
We can combine these two dataframes using merge function of pandas. The shared columns are country and year so we pass them to on parameter:
df_merge = pd.merge(df_gdp, obesity_cleaned, on=['country','year'])df_merge.head()
We can now create our first animated visualizations. Here is the code to produce the animated scatter plot. I will explain each parameter and then show the plot.
px.scatter(df_merge, x="obesity_rate", y="gdpPercap",animation_frame="year",size="pop", color="continent", hover_name="country",size_max = 50,range_x=[0.1, 50], range_y=[100,60000],log_x=True, log_y=True)fig.show()
We first right the name of the dataframe and specify x-axis and y-axis. So our animated scatter plot will show how gdp per capita and obesity rate changes over time. To make the plot animated, we use animation_frame parameter. We use βyearβ as the animation frame so values will change based on the year. We assign population to size parameter so size of the points in scatter plot becomes proportional to the population of the country. For color parameter, we use continent column so that we have an idea about each continent in general. Size_max parameter allows to adjust the size of points in scatter plot. If not specified, points may look too small to distringuish for human-eye. Range_x and range_y parameter are used to specify ranges so that all points remain visible during the animation. Finally, log_x and log_y parameters adjusting axis ranges on log scale. If there is big difference in values, it is better to use log scale to make the plot look nicer.
Visualizations are great tools to deliver a message. Animated plots are even more powerful as they account for time as well. With the plot we just created, we gain information about:
Population of countries
Gdp per capita of countries
Obesity rate of countries
How these values change over time
How continents differ according to these measure
If there is a correlation among these measures
Letβs see the animated scatter plot we created:
Countries in Europe have both high gdp per capita and obesity rates in general.
In general, African and Asian countries are way behind in terms of both gpd per capita and obesity rate.
Throug the years, Asian countries have increased theire gdp per capita than African countries.
There seems to be a positive correlation between obesity rate and gdp per capita (we, ofcourse, need more measures to confirm)
Although it is hard notice due to very small population size, Kuwait has always been the country with highest obesity rate and in top 3 in terms of gdp per capita.
We can also create an animated bar plot. For instance, how obesity rate changes in time can be animated with bar plots. Letβs choose 5 countries (one from each continent) to show on the plot.
countries = ['China', 'Germany', 'Senegal', 'Brazil', 'New Zealand']df5 = obesity_cleaned[obesity_cleaned.country.isin(countries)].reset_index(drop=True)
We also add a title this time. Here is the code to create an animated bar plot with plotly express:
fig = px.bar(df5, x="country", y="obesity_rate",color="country",animation_frame="year", animation_group="country",range_y=[0.1, 50],title='Obesity Rate from 1975 to 2016')fig.show()
Unfortunately, obesity rate has been increasing all over the world.
We have covered how to create some basic animated plots with plotly express. Ofcourse, this is just a little of what can be done with this amazing library. There are many other plot types that we can dynamically create with plotly. I will also write about how to create animated plots using graph objects of plotly.py. The syntax is a little more complicated but it offers more flexibility. It is better to get familiar with both APIs and choose the one that fits your needs best.
Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 969,
"s": 172,
"text": "We live in the era of big data. We can collect lots of data which allows to infer meaningful results and make informed business decisions. However, as the amount of data increases, it gets trickier to analyze and explore the data. There comes in the power of visualizations which are great tools in exploratory data analysis when used efficiently and appropriately. Visualizations also help to deliver a message to your audience or inform them about your findings. There is no one-fits-all kind of visualization method so certain tasks require different kinds of visualizations. In recents years, animated visualizations have gained more popularity as they make it possible to βtellβ much more than a statis visualization. Animated visualizations are great at showing how things change over time."
},
{
"code": null,
"e": 1471,
"s": 969,
"text": "We will cover how to create animated visuzalizations with Plotly Python (plotly.py) which is an open-source plotting library built on plotly javascript (plotly.js). One of the things I like about plotly.py is that it offers a high-level API (plotly express) and a low level API (graph objects) to create visualizations. With plotly express, we can create a nice plot with very few lines of code. On the other hand, we need to write more code with graph objects but have more control on what we create."
},
{
"code": null,
"e": 1599,
"s": 1471,
"text": "In this post, we will use plotly express API. I will write up another post to cover animated visualizations with graph objects."
},
{
"code": null,
"e": 1839,
"s": 1599,
"text": "We will merge two different datasets. One is obesity rate dataset which available here on kaggle. The raw dataset needs to be cleaned and reformatted. If youβd like to go through the data cleaning steps, feel free to visit my post on that:"
},
{
"code": null,
"e": 1862,
"s": 1839,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1916,
"s": 1862,
"text": "Here is the first five rows of the cleaned dataframe:"
},
{
"code": null,
"e": 2102,
"s": 1916,
"text": "The other dataset that we will use is not separating gender. Thus, we need to eliminate gender on this dataset by grouping on βcountryβ and βyearβ and taking the mean of βobesity_rateβ:"
},
{
"code": null,
"e": 2358,
"s": 2102,
"text": "import numpy as npimport pandas as pd# fixing data tytpesobesity_cleaned = df2.astype({'obesity_rate': 'float32', 'year': 'int32'})# eliminating genderobesity_cleaned = obesity_cleaned.groupby(['country','year']).mean().reset_index()obesity_cleaned.head()"
},
{
"code": null,
"e": 2617,
"s": 2358,
"text": "The other dataset is available as built-in dataset of plotly express. It is called gapminder and includes life expectancy, gdp per capita, population of 142 countries from 1952 to 2007 (with 5-year-increments). We first import plotly express and the dataset:"
},
{
"code": null,
"e": 2686,
"s": 2617,
"text": "import plotly.express as pxdf_gdp = px.data.gapminder()df_gdp.head()"
},
{
"code": null,
"e": 2827,
"s": 2686,
"text": "We can combine these two dataframes using merge function of pandas. The shared columns are country and year so we pass them to on parameter:"
},
{
"code": null,
"e": 2930,
"s": 2827,
"text": "df_merge = pd.merge(df_gdp, obesity_cleaned, on=['country','year'])df_merge.head()"
},
{
"code": null,
"e": 3092,
"s": 2930,
"text": "We can now create our first animated visualizations. Here is the code to produce the animated scatter plot. I will explain each parameter and then show the plot."
},
{
"code": null,
"e": 3307,
"s": 3092,
"text": "px.scatter(df_merge, x=\"obesity_rate\", y=\"gdpPercap\",animation_frame=\"year\",size=\"pop\", color=\"continent\", hover_name=\"country\",size_max = 50,range_x=[0.1, 50], range_y=[100,60000],log_x=True, log_y=True)fig.show()"
},
{
"code": null,
"e": 4275,
"s": 3307,
"text": "We first right the name of the dataframe and specify x-axis and y-axis. So our animated scatter plot will show how gdp per capita and obesity rate changes over time. To make the plot animated, we use animation_frame parameter. We use βyearβ as the animation frame so values will change based on the year. We assign population to size parameter so size of the points in scatter plot becomes proportional to the population of the country. For color parameter, we use continent column so that we have an idea about each continent in general. Size_max parameter allows to adjust the size of points in scatter plot. If not specified, points may look too small to distringuish for human-eye. Range_x and range_y parameter are used to specify ranges so that all points remain visible during the animation. Finally, log_x and log_y parameters adjusting axis ranges on log scale. If there is big difference in values, it is better to use log scale to make the plot look nicer."
},
{
"code": null,
"e": 4458,
"s": 4275,
"text": "Visualizations are great tools to deliver a message. Animated plots are even more powerful as they account for time as well. With the plot we just created, we gain information about:"
},
{
"code": null,
"e": 4482,
"s": 4458,
"text": "Population of countries"
},
{
"code": null,
"e": 4510,
"s": 4482,
"text": "Gdp per capita of countries"
},
{
"code": null,
"e": 4536,
"s": 4510,
"text": "Obesity rate of countries"
},
{
"code": null,
"e": 4570,
"s": 4536,
"text": "How these values change over time"
},
{
"code": null,
"e": 4619,
"s": 4570,
"text": "How continents differ according to these measure"
},
{
"code": null,
"e": 4666,
"s": 4619,
"text": "If there is a correlation among these measures"
},
{
"code": null,
"e": 4714,
"s": 4666,
"text": "Letβs see the animated scatter plot we created:"
},
{
"code": null,
"e": 4794,
"s": 4714,
"text": "Countries in Europe have both high gdp per capita and obesity rates in general."
},
{
"code": null,
"e": 4899,
"s": 4794,
"text": "In general, African and Asian countries are way behind in terms of both gpd per capita and obesity rate."
},
{
"code": null,
"e": 4994,
"s": 4899,
"text": "Throug the years, Asian countries have increased theire gdp per capita than African countries."
},
{
"code": null,
"e": 5121,
"s": 4994,
"text": "There seems to be a positive correlation between obesity rate and gdp per capita (we, ofcourse, need more measures to confirm)"
},
{
"code": null,
"e": 5285,
"s": 5121,
"text": "Although it is hard notice due to very small population size, Kuwait has always been the country with highest obesity rate and in top 3 in terms of gdp per capita."
},
{
"code": null,
"e": 5477,
"s": 5285,
"text": "We can also create an animated bar plot. For instance, how obesity rate changes in time can be animated with bar plots. Letβs choose 5 countries (one from each continent) to show on the plot."
},
{
"code": null,
"e": 5631,
"s": 5477,
"text": "countries = ['China', 'Germany', 'Senegal', 'Brazil', 'New Zealand']df5 = obesity_cleaned[obesity_cleaned.country.isin(countries)].reset_index(drop=True)"
},
{
"code": null,
"e": 5731,
"s": 5631,
"text": "We also add a title this time. Here is the code to create an animated bar plot with plotly express:"
},
{
"code": null,
"e": 5913,
"s": 5731,
"text": "fig = px.bar(df5, x=\"country\", y=\"obesity_rate\",color=\"country\",animation_frame=\"year\", animation_group=\"country\",range_y=[0.1, 50],title='Obesity Rate from 1975 to 2016')fig.show()"
},
{
"code": null,
"e": 5981,
"s": 5913,
"text": "Unfortunately, obesity rate has been increasing all over the world."
},
{
"code": null,
"e": 6462,
"s": 5981,
"text": "We have covered how to create some basic animated plots with plotly express. Ofcourse, this is just a little of what can be done with this amazing library. There are many other plot types that we can dynamically create with plotly. I will also write about how to create animated plots using graph objects of plotly.py. The syntax is a little more complicated but it offers more flexibility. It is better to get familiar with both APIs and choose the one that fits your needs best."
},
{
"code": null,
"e": 6609,
"s": 6462,
"text": "Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills."
}
] |
Top SQL Interview Test Questions & Techniques (Part 1) | by Ian Ho | Towards Data Science
|
Check out Part 2 Here!
If youβre applying for a role in Data Science, Business Analytics or really any field that deals with data, thereβs a very high chance youβll be asked to take a coding test with a SQL component in it. The test is usually conducted on a platform like Codility or HackerRank and typically serves as the initial filter for candidates applying for data-oriented roles.
Despite the many possible scenarios and cases out there on these test platforms, there are certain tasks that appear repeatedly in these SQL tests. These tasks donβt always come in the exact same format, and are sometimes part of intermediate steps for a final solution. And no, Iβm not talking about basic queries like βDisplay the Maximum valueβ or βCount the number of distinct valuesβ. Weβre talking about the kind of tasks you will find on the medium-hard levels of LeetCode, for instance.
In my opinion, you could spend hours and days attempting all the different challenges on LeetCode and HackerRank, but ultimately many of these challenges are not representative of actual test questions that are asked in such recruitment tests. More often than not, the test tasks are geared towards actual business applications; take enough tests and you will soon notice a repetition of certain tasks.
The goal of this article is precisely to outline these tasks and present solutions so that you can be better prepared for these tests. In Part 1 of this post, I will be sharing about two very common types of tasks:
Select Top N of Values per CategorySelect Rows with Minimum number of Consecutive Rows meeting Condition(s)
Select Top N of Values per Category
Select Rows with Minimum number of Consecutive Rows meeting Condition(s)
Note: Depending on which version of SQL you are using, there may be some differences between the clauses and functions that can be used but in general there should not be that many differences. There are way too many minor differences to be covered, so if you are unsure about any of the functions just do a simple search and someone will usually have the answer!
In general, there are two key ways to assess a SQL solution: Accuracy and Efficiency. In my examples below, I focus primarily on Accuracy in order to demonstrate usages and applications of certain techniques or functions in SQL. However, I also recognise that Efficiency is very important in SQL, especially when it comes to querying huge amounts of data. In my solutions, I make sure to achieve a very reasonable level of efficiency given the assumed knowledge of basic-intermediate learners of SQL, and do my very best to present solutions that minimise as much redundancy as possible. If you would like to learn more about efficiency considering taking a look at this website or this book to learn more.
Without further ado, letβs dive into the questions!
For this type of question, you will be required to select the rows which contain the top N values within a category.
Task: Extract the names and classes for the top 2 test scores for each class in the school, ordered by class and then by score. If there are any tie breakers, use the lower student_id to break the tie.
The scores dataset contains the scores for all students in the school. Each student has a unique student_id, which is the primary key. The class dataset contains the classes for all students in the school. The foreign key here is student_id, which matches the primary key from scores. Similarly, the names dataset contains names for all students with student_id as the foreign key.
Note: A FOREIGN KEY is a field in one table that references a PRIMARY KEY in another table.
scores| student_id | scores |+------------+--------+| 1 | 90 || 2 | 83 || 3 | 79 || 4 | 97 || 5 | 90 || 6 | 92 || 7 | 94 |...classes| student_id | class |+------------+--------+| 1 | A || 2 | B || 3 | A | | 4 | B || 5 | D || 6 | B || 7 | A |...names| student_id | name |+------------+----------+| 1 | James || 2 | Michael || 3 | Valarie | | 4 | Jessie || 5 | Douglas || 6 | Shin || 7 | Joanne |...
Therefore, the expected result should look something like this:
EXPECTED RESULT:| class | name | score |+-------+--------+-------+| A | Joanne | 94 || A | James | 90 || B | Jessie | 97 || B | Shin | 92 |...
SOLUTION
WITH class_ranking AS (SELECT c.class, n.name, s.score, ROW_NUMBER() OVER (PARTITION BY c.class ORDER BY s.score DESC, s.student_id) AS rankFROM scores sJOIN classes c ON s.student_id = c.student_idJOIN names n ON s.student_id = c.student_id )SELECT class, name, scoreFROM class_rankingWHERE rank <= 2ORDER BY class ASC, score DESC;
The difficulty in this task lies in selecting top scores not for the entire dataset but for each category. If the task were for the entire dataset, we could have just used a combination of ORDER BY and LIMIT obtain the top scores.
To help us solve this task in an efficient and parsimonious manner, we can use COMMON TABLE EXPRESSIONS (CTE) to create a temporary result that can be subsequently referenced by clauses like SELECT and INSERT, UPDATE or DELETE.
First, we use a JOIN between scores, classes and names to obtain a complete dataset where each row contains all the relevant data for each individual. Then, in addition to selecting these three data points, we use the PARTITION BY clause to divide the result set according to c.class and to assign a ROW_NUMER(), starting from 1, according to the field after ORDER BY. In this case, within each partition of c.class, we order firstly in DESC by s.score to give the highest score in each class a rank of 1, and the second highest a rank of 2, and so on. In addition, we use s.student_id as the secondary field to order by, so as to achieve the objective of the task which is eliminate ties using the lower student_id.
For more details on how to use the PARTITION BY clause, check us this link here.
Next, we make use of CTE to store this partitioned ranking as a temporary result set known as class_ranking. In general, the CTEβs are used in the following manner:
WITH temp_table AS ( SELECT ...)SELECT _ FROM temp_table
You can also use a chain of CTEs to solve problems. This is very useful in cases where the solution requires sequential working on intermediate CTEs to derive a final CTE for the actual results. The format would look something like:
WITH temp_table AS ( SELECT ...),WITH temp_table_2 AS ( SELECT ...),SELECT _ FROM temp_table_2
For examples covering the use of multiple CTEs, stay tuned for future posts!
For this question, the CTE class_ranking is basically an extension of the original triple join, with an additional field rank to indicate the rank for each student within each partition or class.
With this CTE, we can then SELECT the relevant fields of class, name, score and use the WHERE clause to subset for rows that have rank β€ 2, effectively giving us the top 2 scores for each class with ties broken by lower student_id. We omit the rank in the final solution as this is not required. We also ORDER BY class ASC, score DESC to obtain the desired ordering using class by alphabetical order first, and with the higher score on top.
VARIATION: Alternatives to ROW_NUMBER()
In this particular task, the ties were to be broken using the student_id, and this was simply achieved by assigning ROW_NUMBER() for each partition and ordering by first the score and then the student_id. This would ensure that only one student would be ranked 1 and one student would be ranked 2.
However, what if the question specified: Let s1 and s2 be the top 2 scores achieved in each class. If there is more than one student who attained s1 and/or more than one student who attained s2, include all the names as long as they have attained one of the top two scores.
Practically this would mean that the modified result set may look something like:
MODIFIED RESULT:| class | name | score |+-------+--------+-------+| A | Joanne | 94 || A | James | 90 || A | Caleb | 90 || B | Jessie | 97 || B | Shin | 92 |...
In order to account for this variation, all we have to change is the ROW_NUMBER() window function to DENSE_RANK(). Assuming James has a lower student_id than Caleb, ROW_NUMBER() would assign rank=2 to James and rank=3 to Caleb. However, DENSE_RANK() would assign rank=2 to both James and Caleb. In addition ,the difference between DENSE_RANK() and RANK() is also noteworthy β DENSE_RANK() is βdenseβ in the sense that it will not skip ranks after identical rankings, but RANK() will. Therefore, the next highest score that comes after Caleb will be ranked as rank=3 under DENSE_RANK() but rank=4 under RANK(). Depending on the application case, one should be aware of the differences between these window applications.
For those of you wondering what a window function is and how it relates to other functions like the aggregate function, PostgreSQL provides quite a good explanation:
A window function performs a calculation across a set of table rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. But unlike regular aggregate functions, use of a window function does not cause rows to become grouped into a single output row β the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result.
If your SQL dialect does not support the ROW_NUMBER() function or the PARTITION BY clause, we can use a combination of equi join and non-equi join logic in a correlated subquery to obtain the desired result:
SELECT c.class, n.name, s.scoreFROM scores sJOIN classes c ON s.student_id = c.student_idJOIN names n ON s.student_id = n.student_itWHERE( SELECT COUNT(DISTINCT s.score) FROM scores s2 JOIN classes c2 ON s2.student_id = c2.student_id WHERE s2.score > s.score AND c2.class = c.class) < 2
An equi join is a join that joins tables according to matching values in columns. A non-equi join is a join with a condition other than equals.
A subquery is a query nested inside another query. A correlated subquery is a subquery which uses values from the outer query.
In this case the subquery uses s.score and c.class from the outer query to compare with values from the same table scores, but now with alias s2, and to count the number of scores which are greater than each row in the original table scores s. The condition is to select those with fewer than 2 corresponding matches because the top score would have 0 matches, and the second highest score would have 1 match.
And thatβs all! On to the next question ...
Select Rows with Minimum number of Consecutive Rows meeting Condition(s)
A common task in SQL Interviews is to select rows which not only meet a certain criteria but do so for a minimum number of rows in order, usually by date. Here we will look at an example that explains how we can go about using cross-joins to filter for such cases given the relation between consecutive rows that we are looking for.
The table cases contains the number of new COVID cases for each date.
Task: Display the rows which contain 3 or more consecutive days of more than 100 cases in those days.
cases+------+------------+-----------+| id | date | new |+------+------------+-----------+| 1 | 2021-01-01 | 20 || 2 | 2021-01-02 | 149 || 3 | 2021-01-03 | 150 || 4 | 2021-01-04 | 99 || 5 | 2021-01-05 | 145 || 6 | 2021-01-06 | 200 || 7 | 2021-01-07 | 199 || 8 | 2021-01-08 | 188 || 9 | 2021-01-09 | 88 |+------+------------+-----------+...
The expected result will look something like:
EXPECTED RESULT+------+------------+-----------+| id | date | new |+------+------------+-----------+| 5 | 2021-01-05 | 145 || 6 | 2021-01-06 | 200 || 7 | 2021-01-07 | 199 || 8 | 2021-01-08 | 188 |+------+------------+-----------+
SOLUTION
WITH cases_over_hundred AS ( SELECT * FROM cases WHERE new > 100)SELECT DISTINCT c1.* FROM cases_over_hundred as c1,FROM cases_over_hundred as c3,FROM cases_over_hundred as c2,WHERE (c1.id = c2.id - 1 AND c1.id = c3.id - 2) OR (c1.id = c2.id + 1 AND c1.id = c3.id - 1) OR (c1.id = c2.id + 2 AND c1.id = c3.id + 1)ORDER BY c1.id;
For efficiency purposes, we first create a CTE to choose the rows where there are more than a 100 cases. We call this CTE cases_over_hundred.
Next, we use a conditional cross-join to find all the rows which are part of 3 or more consecutive days with more than 100 cases. A cross-join, also known as a cartesian product, where each row from one table is combined with each row from another table.
In this case, we are cross-joining three tables because we want to compare the dates of the different combinations of three dates to check if they are consecutive. However, instead of having a full cross-join, we will use conditions to ensure that we only join dates that fall in any one of three of the following categories:
c1 date is one day before c2 date and two days before c3 date
c1 date is one day after c2 date and one day before c3 date
c1 date is two days after c2 date and one day after c3 date
Note: swapping c2 with c3 for any of these conditions will not matter because here we are using a cross-join, so all permutations will be considered anyway
These three possibilities are captured by the following three conditions respectively:
WHERE (c1.id = c2.id - 1 AND c1.id = c3.id - 2) OR (c1.id = c2.id + 1 AND c1.id = c3.id - 1) OR (c1.id = c2.id + 2 AND c1.id = c3.id + 1)
With this conditional cross-join, we successfully choose all the combinations of dates such that all three dates in the row are consecutive when arranged properly and they all have cases hundred and above.
Finally, we need to use SELECT ( DISTINCT (c1.*)) to remove all the repetitions. For each row subsetted, there will be two duplicates due to the conditional cross-join, and therefore all we need to do is to select the distinct values of the dates from c1 only to get the sequences of dates with more than 100 cases 3 or more days in a row.
ALTERNATIVE SOLUTION
In fact, there is another way to solve this problem that involves using window functions (again)! For this case, we can use the window function LAG() and LEAD(). As you might have already expected, LAG() allows us to obtain the previous values for a given field, where order is determined by another field. In this case, we get the previous values of new according to the order of id. Similarly, LEAD() returns us values ahead of the current row in reference.
The standard syntax is as such:
LAG(return_value ,offset [,default]) OVER ([PARTITION BY partition_expression, ... ] ORDER BY sort_expression [ASC | DESC], ... )
This syntax is very similar to the one which we used in the Question 1, with the ROW_NUMBER() window function.
For this question, we first construct a CTE which contains the values 1, 2 days before and after the date of each row using the LAG() and LEAD() window functions. Subsequently, we reference this CTE and condition for rows where the criteria of three consecutive days with over 100 cases is met.β
WITH interval_cases AS ( SELECT *, LAG(new, 2) OVER (ORDER BY id) AS before_2, LAG(new, 1) OVER (ORDER BY id) AS before_1, LEAD(new, 1) OVER (ORDER BY id) AS after_1, LEAD(new, 2) OVER (ORDER BY id) AS after_2FROM cases)SELECT id, date, newFROM casesWHERE new > 100AND ((before_2 > 100 AND before_1 > 100) OR (before_1 > 100 AND after_1 > 100) OR (after_1 > 100 AND after_2 > 100))ORDER BY id;
Letβs take a look at the query logic:
Firstly, the CTE interval_cases will produce a result set that will look something like this for each row:
+----+------------+-----+----------+----------+---------+---------+| id | date | new | before_2 | before_1 | after_1 | after_2 |+----+------------+-----+----------+----------+---------+---------+| 5 | 2021-01-05 | 145 | 150 | 99 | 200 | 199 |...
Subsequently, we filter for those rows where new is greater than 100 and where it belongs to a consecutive row of three days which are also all greater than 300. This can happen in one of three ways, which is why there are three alternative conditions that accompany the new>100 condition. This will get us the same result as the previous solution.
I hope these two questions have been useful in demonstrating how to approach some of the most common questions you would find in SQL coding tests. If you like what Iβve shared, do give me a clap and share the article!
If thereβs sufficient interest, Iβll also be doing a Part 2 with more questions, and if you have any comments or inputs on how you would tackle these problems (especially from an efficiency perspective), feel free to get in touch or comment!
Update: Check out Part 2 Here!
|
[
{
"code": null,
"e": 195,
"s": 172,
"text": "Check out Part 2 Here!"
},
{
"code": null,
"e": 560,
"s": 195,
"text": "If youβre applying for a role in Data Science, Business Analytics or really any field that deals with data, thereβs a very high chance youβll be asked to take a coding test with a SQL component in it. The test is usually conducted on a platform like Codility or HackerRank and typically serves as the initial filter for candidates applying for data-oriented roles."
},
{
"code": null,
"e": 1055,
"s": 560,
"text": "Despite the many possible scenarios and cases out there on these test platforms, there are certain tasks that appear repeatedly in these SQL tests. These tasks donβt always come in the exact same format, and are sometimes part of intermediate steps for a final solution. And no, Iβm not talking about basic queries like βDisplay the Maximum valueβ or βCount the number of distinct valuesβ. Weβre talking about the kind of tasks you will find on the medium-hard levels of LeetCode, for instance."
},
{
"code": null,
"e": 1458,
"s": 1055,
"text": "In my opinion, you could spend hours and days attempting all the different challenges on LeetCode and HackerRank, but ultimately many of these challenges are not representative of actual test questions that are asked in such recruitment tests. More often than not, the test tasks are geared towards actual business applications; take enough tests and you will soon notice a repetition of certain tasks."
},
{
"code": null,
"e": 1673,
"s": 1458,
"text": "The goal of this article is precisely to outline these tasks and present solutions so that you can be better prepared for these tests. In Part 1 of this post, I will be sharing about two very common types of tasks:"
},
{
"code": null,
"e": 1781,
"s": 1673,
"text": "Select Top N of Values per CategorySelect Rows with Minimum number of Consecutive Rows meeting Condition(s)"
},
{
"code": null,
"e": 1817,
"s": 1781,
"text": "Select Top N of Values per Category"
},
{
"code": null,
"e": 1890,
"s": 1817,
"text": "Select Rows with Minimum number of Consecutive Rows meeting Condition(s)"
},
{
"code": null,
"e": 2254,
"s": 1890,
"text": "Note: Depending on which version of SQL you are using, there may be some differences between the clauses and functions that can be used but in general there should not be that many differences. There are way too many minor differences to be covered, so if you are unsure about any of the functions just do a simple search and someone will usually have the answer!"
},
{
"code": null,
"e": 2961,
"s": 2254,
"text": "In general, there are two key ways to assess a SQL solution: Accuracy and Efficiency. In my examples below, I focus primarily on Accuracy in order to demonstrate usages and applications of certain techniques or functions in SQL. However, I also recognise that Efficiency is very important in SQL, especially when it comes to querying huge amounts of data. In my solutions, I make sure to achieve a very reasonable level of efficiency given the assumed knowledge of basic-intermediate learners of SQL, and do my very best to present solutions that minimise as much redundancy as possible. If you would like to learn more about efficiency considering taking a look at this website or this book to learn more."
},
{
"code": null,
"e": 3013,
"s": 2961,
"text": "Without further ado, letβs dive into the questions!"
},
{
"code": null,
"e": 3130,
"s": 3013,
"text": "For this type of question, you will be required to select the rows which contain the top N values within a category."
},
{
"code": null,
"e": 3332,
"s": 3130,
"text": "Task: Extract the names and classes for the top 2 test scores for each class in the school, ordered by class and then by score. If there are any tie breakers, use the lower student_id to break the tie."
},
{
"code": null,
"e": 3714,
"s": 3332,
"text": "The scores dataset contains the scores for all students in the school. Each student has a unique student_id, which is the primary key. The class dataset contains the classes for all students in the school. The foreign key here is student_id, which matches the primary key from scores. Similarly, the names dataset contains names for all students with student_id as the foreign key."
},
{
"code": null,
"e": 3806,
"s": 3714,
"text": "Note: A FOREIGN KEY is a field in one table that references a PRIMARY KEY in another table."
},
{
"code": null,
"e": 4467,
"s": 3806,
"text": "scores| student_id | scores |+------------+--------+| 1 | 90 || 2 | 83 || 3 | 79 || 4 | 97 || 5 | 90 || 6 | 92 || 7 | 94 |...classes| student_id | class |+------------+--------+| 1 | A || 2 | B || 3 | A | | 4 | B || 5 | D || 6 | B || 7 | A |...names| student_id | name |+------------+----------+| 1 | James || 2 | Michael || 3 | Valarie | | 4 | Jessie || 5 | Douglas || 6 | Shin || 7 | Joanne |..."
},
{
"code": null,
"e": 4531,
"s": 4467,
"text": "Therefore, the expected result should look something like this:"
},
{
"code": null,
"e": 4709,
"s": 4531,
"text": "EXPECTED RESULT:| class | name | score |+-------+--------+-------+| A | Joanne | 94 || A | James | 90 || B | Jessie | 97 || B | Shin | 92 |... "
},
{
"code": null,
"e": 4718,
"s": 4709,
"text": "SOLUTION"
},
{
"code": null,
"e": 5057,
"s": 4718,
"text": "WITH class_ranking AS (SELECT c.class, n.name, s.score, ROW_NUMBER() OVER (PARTITION BY c.class ORDER BY s.score DESC, s.student_id) AS rankFROM scores sJOIN classes c ON s.student_id = c.student_idJOIN names n ON s.student_id = c.student_id )SELECT class, name, scoreFROM class_rankingWHERE rank <= 2ORDER BY class ASC, score DESC;"
},
{
"code": null,
"e": 5288,
"s": 5057,
"text": "The difficulty in this task lies in selecting top scores not for the entire dataset but for each category. If the task were for the entire dataset, we could have just used a combination of ORDER BY and LIMIT obtain the top scores."
},
{
"code": null,
"e": 5516,
"s": 5288,
"text": "To help us solve this task in an efficient and parsimonious manner, we can use COMMON TABLE EXPRESSIONS (CTE) to create a temporary result that can be subsequently referenced by clauses like SELECT and INSERT, UPDATE or DELETE."
},
{
"code": null,
"e": 6233,
"s": 5516,
"text": "First, we use a JOIN between scores, classes and names to obtain a complete dataset where each row contains all the relevant data for each individual. Then, in addition to selecting these three data points, we use the PARTITION BY clause to divide the result set according to c.class and to assign a ROW_NUMER(), starting from 1, according to the field after ORDER BY. In this case, within each partition of c.class, we order firstly in DESC by s.score to give the highest score in each class a rank of 1, and the second highest a rank of 2, and so on. In addition, we use s.student_id as the secondary field to order by, so as to achieve the objective of the task which is eliminate ties using the lower student_id."
},
{
"code": null,
"e": 6314,
"s": 6233,
"text": "For more details on how to use the PARTITION BY clause, check us this link here."
},
{
"code": null,
"e": 6479,
"s": 6314,
"text": "Next, we make use of CTE to store this partitioned ranking as a temporary result set known as class_ranking. In general, the CTEβs are used in the following manner:"
},
{
"code": null,
"e": 6539,
"s": 6479,
"text": "WITH temp_table AS ( SELECT ...)SELECT _ FROM temp_table"
},
{
"code": null,
"e": 6772,
"s": 6539,
"text": "You can also use a chain of CTEs to solve problems. This is very useful in cases where the solution requires sequential working on intermediate CTEs to derive a final CTE for the actual results. The format would look something like:"
},
{
"code": null,
"e": 6873,
"s": 6772,
"text": "WITH temp_table AS ( SELECT ...),WITH temp_table_2 AS ( SELECT ...),SELECT _ FROM temp_table_2"
},
{
"code": null,
"e": 6950,
"s": 6873,
"text": "For examples covering the use of multiple CTEs, stay tuned for future posts!"
},
{
"code": null,
"e": 7146,
"s": 6950,
"text": "For this question, the CTE class_ranking is basically an extension of the original triple join, with an additional field rank to indicate the rank for each student within each partition or class."
},
{
"code": null,
"e": 7587,
"s": 7146,
"text": "With this CTE, we can then SELECT the relevant fields of class, name, score and use the WHERE clause to subset for rows that have rank β€ 2, effectively giving us the top 2 scores for each class with ties broken by lower student_id. We omit the rank in the final solution as this is not required. We also ORDER BY class ASC, score DESC to obtain the desired ordering using class by alphabetical order first, and with the higher score on top."
},
{
"code": null,
"e": 7627,
"s": 7587,
"text": "VARIATION: Alternatives to ROW_NUMBER()"
},
{
"code": null,
"e": 7925,
"s": 7627,
"text": "In this particular task, the ties were to be broken using the student_id, and this was simply achieved by assigning ROW_NUMBER() for each partition and ordering by first the score and then the student_id. This would ensure that only one student would be ranked 1 and one student would be ranked 2."
},
{
"code": null,
"e": 8199,
"s": 7925,
"text": "However, what if the question specified: Let s1 and s2 be the top 2 scores achieved in each class. If there is more than one student who attained s1 and/or more than one student who attained s2, include all the names as long as they have attained one of the top two scores."
},
{
"code": null,
"e": 8281,
"s": 8199,
"text": "Practically this would mean that the modified result set may look something like:"
},
{
"code": null,
"e": 8483,
"s": 8281,
"text": "MODIFIED RESULT:| class | name | score |+-------+--------+-------+| A | Joanne | 94 || A | James | 90 || A | Caleb | 90 || B | Jessie | 97 || B | Shin | 92 |..."
},
{
"code": null,
"e": 9202,
"s": 8483,
"text": "In order to account for this variation, all we have to change is the ROW_NUMBER() window function to DENSE_RANK(). Assuming James has a lower student_id than Caleb, ROW_NUMBER() would assign rank=2 to James and rank=3 to Caleb. However, DENSE_RANK() would assign rank=2 to both James and Caleb. In addition ,the difference between DENSE_RANK() and RANK() is also noteworthy β DENSE_RANK() is βdenseβ in the sense that it will not skip ranks after identical rankings, but RANK() will. Therefore, the next highest score that comes after Caleb will be ranked as rank=3 under DENSE_RANK() but rank=4 under RANK(). Depending on the application case, one should be aware of the differences between these window applications."
},
{
"code": null,
"e": 9368,
"s": 9202,
"text": "For those of you wondering what a window function is and how it relates to other functions like the aggregate function, PostgreSQL provides quite a good explanation:"
},
{
"code": null,
"e": 9854,
"s": 9368,
"text": "A window function performs a calculation across a set of table rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. But unlike regular aggregate functions, use of a window function does not cause rows to become grouped into a single output row β the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result."
},
{
"code": null,
"e": 10062,
"s": 9854,
"text": "If your SQL dialect does not support the ROW_NUMBER() function or the PARTITION BY clause, we can use a combination of equi join and non-equi join logic in a correlated subquery to obtain the desired result:"
},
{
"code": null,
"e": 10365,
"s": 10062,
"text": "SELECT c.class, n.name, s.scoreFROM scores sJOIN classes c ON s.student_id = c.student_idJOIN names n ON s.student_id = n.student_itWHERE( SELECT COUNT(DISTINCT s.score) FROM scores s2 JOIN classes c2 ON s2.student_id = c2.student_id WHERE s2.score > s.score AND c2.class = c.class) < 2"
},
{
"code": null,
"e": 10509,
"s": 10365,
"text": "An equi join is a join that joins tables according to matching values in columns. A non-equi join is a join with a condition other than equals."
},
{
"code": null,
"e": 10636,
"s": 10509,
"text": "A subquery is a query nested inside another query. A correlated subquery is a subquery which uses values from the outer query."
},
{
"code": null,
"e": 11046,
"s": 10636,
"text": "In this case the subquery uses s.score and c.class from the outer query to compare with values from the same table scores, but now with alias s2, and to count the number of scores which are greater than each row in the original table scores s. The condition is to select those with fewer than 2 corresponding matches because the top score would have 0 matches, and the second highest score would have 1 match."
},
{
"code": null,
"e": 11090,
"s": 11046,
"text": "And thatβs all! On to the next question ..."
},
{
"code": null,
"e": 11163,
"s": 11090,
"text": "Select Rows with Minimum number of Consecutive Rows meeting Condition(s)"
},
{
"code": null,
"e": 11496,
"s": 11163,
"text": "A common task in SQL Interviews is to select rows which not only meet a certain criteria but do so for a minimum number of rows in order, usually by date. Here we will look at an example that explains how we can go about using cross-joins to filter for such cases given the relation between consecutive rows that we are looking for."
},
{
"code": null,
"e": 11566,
"s": 11496,
"text": "The table cases contains the number of new COVID cases for each date."
},
{
"code": null,
"e": 11668,
"s": 11566,
"text": "Task: Display the rows which contain 3 or more consecutive days of more than 100 cases in those days."
},
{
"code": null,
"e": 12106,
"s": 11668,
"text": "cases+------+------------+-----------+| id | date | new |+------+------------+-----------+| 1 | 2021-01-01 | 20 || 2 | 2021-01-02 | 149 || 3 | 2021-01-03 | 150 || 4 | 2021-01-04 | 99 || 5 | 2021-01-05 | 145 || 6 | 2021-01-06 | 200 || 7 | 2021-01-07 | 199 || 8 | 2021-01-08 | 188 || 9 | 2021-01-09 | 88 |+------+------------+-----------+..."
},
{
"code": null,
"e": 12152,
"s": 12106,
"text": "The expected result will look something like:"
},
{
"code": null,
"e": 12432,
"s": 12152,
"text": "EXPECTED RESULT+------+------------+-----------+| id | date | new |+------+------------+-----------+| 5 | 2021-01-05 | 145 || 6 | 2021-01-06 | 200 || 7 | 2021-01-07 | 199 || 8 | 2021-01-08 | 188 |+------+------------+-----------+"
},
{
"code": null,
"e": 12441,
"s": 12432,
"text": "SOLUTION"
},
{
"code": null,
"e": 12775,
"s": 12441,
"text": "WITH cases_over_hundred AS ( SELECT * FROM cases WHERE new > 100)SELECT DISTINCT c1.* FROM cases_over_hundred as c1,FROM cases_over_hundred as c3,FROM cases_over_hundred as c2,WHERE (c1.id = c2.id - 1 AND c1.id = c3.id - 2) OR (c1.id = c2.id + 1 AND c1.id = c3.id - 1) OR (c1.id = c2.id + 2 AND c1.id = c3.id + 1)ORDER BY c1.id;"
},
{
"code": null,
"e": 12917,
"s": 12775,
"text": "For efficiency purposes, we first create a CTE to choose the rows where there are more than a 100 cases. We call this CTE cases_over_hundred."
},
{
"code": null,
"e": 13172,
"s": 12917,
"text": "Next, we use a conditional cross-join to find all the rows which are part of 3 or more consecutive days with more than 100 cases. A cross-join, also known as a cartesian product, where each row from one table is combined with each row from another table."
},
{
"code": null,
"e": 13498,
"s": 13172,
"text": "In this case, we are cross-joining three tables because we want to compare the dates of the different combinations of three dates to check if they are consecutive. However, instead of having a full cross-join, we will use conditions to ensure that we only join dates that fall in any one of three of the following categories:"
},
{
"code": null,
"e": 13560,
"s": 13498,
"text": "c1 date is one day before c2 date and two days before c3 date"
},
{
"code": null,
"e": 13620,
"s": 13560,
"text": "c1 date is one day after c2 date and one day before c3 date"
},
{
"code": null,
"e": 13680,
"s": 13620,
"text": "c1 date is two days after c2 date and one day after c3 date"
},
{
"code": null,
"e": 13836,
"s": 13680,
"text": "Note: swapping c2 with c3 for any of these conditions will not matter because here we are using a cross-join, so all permutations will be considered anyway"
},
{
"code": null,
"e": 13923,
"s": 13836,
"text": "These three possibilities are captured by the following three conditions respectively:"
},
{
"code": null,
"e": 14065,
"s": 13923,
"text": "WHERE (c1.id = c2.id - 1 AND c1.id = c3.id - 2) OR (c1.id = c2.id + 1 AND c1.id = c3.id - 1) OR (c1.id = c2.id + 2 AND c1.id = c3.id + 1)"
},
{
"code": null,
"e": 14271,
"s": 14065,
"text": "With this conditional cross-join, we successfully choose all the combinations of dates such that all three dates in the row are consecutive when arranged properly and they all have cases hundred and above."
},
{
"code": null,
"e": 14611,
"s": 14271,
"text": "Finally, we need to use SELECT ( DISTINCT (c1.*)) to remove all the repetitions. For each row subsetted, there will be two duplicates due to the conditional cross-join, and therefore all we need to do is to select the distinct values of the dates from c1 only to get the sequences of dates with more than 100 cases 3 or more days in a row."
},
{
"code": null,
"e": 14632,
"s": 14611,
"text": "ALTERNATIVE SOLUTION"
},
{
"code": null,
"e": 15092,
"s": 14632,
"text": "In fact, there is another way to solve this problem that involves using window functions (again)! For this case, we can use the window function LAG() and LEAD(). As you might have already expected, LAG() allows us to obtain the previous values for a given field, where order is determined by another field. In this case, we get the previous values of new according to the order of id. Similarly, LEAD() returns us values ahead of the current row in reference."
},
{
"code": null,
"e": 15124,
"s": 15092,
"text": "The standard syntax is as such:"
},
{
"code": null,
"e": 15261,
"s": 15124,
"text": "LAG(return_value ,offset [,default]) OVER ([PARTITION BY partition_expression, ... ] ORDER BY sort_expression [ASC | DESC], ... )"
},
{
"code": null,
"e": 15372,
"s": 15261,
"text": "This syntax is very similar to the one which we used in the Question 1, with the ROW_NUMBER() window function."
},
{
"code": null,
"e": 15668,
"s": 15372,
"text": "For this question, we first construct a CTE which contains the values 1, 2 days before and after the date of each row using the LAG() and LEAD() window functions. Subsequently, we reference this CTE and condition for rows where the criteria of three consecutive days with over 100 cases is met.β"
},
{
"code": null,
"e": 16085,
"s": 15668,
"text": "WITH interval_cases AS ( SELECT *, LAG(new, 2) OVER (ORDER BY id) AS before_2, LAG(new, 1) OVER (ORDER BY id) AS before_1, LEAD(new, 1) OVER (ORDER BY id) AS after_1, LEAD(new, 2) OVER (ORDER BY id) AS after_2FROM cases)SELECT id, date, newFROM casesWHERE new > 100AND ((before_2 > 100 AND before_1 > 100) OR (before_1 > 100 AND after_1 > 100) OR (after_1 > 100 AND after_2 > 100))ORDER BY id;"
},
{
"code": null,
"e": 16123,
"s": 16085,
"text": "Letβs take a look at the query logic:"
},
{
"code": null,
"e": 16230,
"s": 16123,
"text": "Firstly, the CTE interval_cases will produce a result set that will look something like this for each row:"
},
{
"code": null,
"e": 16502,
"s": 16230,
"text": "+----+------------+-----+----------+----------+---------+---------+| id | date | new | before_2 | before_1 | after_1 | after_2 |+----+------------+-----+----------+----------+---------+---------+| 5 | 2021-01-05 | 145 | 150 | 99 | 200 | 199 |..."
},
{
"code": null,
"e": 16851,
"s": 16502,
"text": "Subsequently, we filter for those rows where new is greater than 100 and where it belongs to a consecutive row of three days which are also all greater than 300. This can happen in one of three ways, which is why there are three alternative conditions that accompany the new>100 condition. This will get us the same result as the previous solution."
},
{
"code": null,
"e": 17069,
"s": 16851,
"text": "I hope these two questions have been useful in demonstrating how to approach some of the most common questions you would find in SQL coding tests. If you like what Iβve shared, do give me a clap and share the article!"
},
{
"code": null,
"e": 17311,
"s": 17069,
"text": "If thereβs sufficient interest, Iβll also be doing a Part 2 with more questions, and if you have any comments or inputs on how you would tackle these problems (especially from an efficiency perspective), feel free to get in touch or comment!"
}
] |
Can Place Flowers in C++
|
Suppose we have a long flowerbed in which some of the plots are planted and some are empty. Now there is a constraint, flowers cannot be planted in adjacent plots, they would compete for water and both would die. So if we have a flowerbed, represented by an array containing 0 and 1, 0 indicates empty and 1 indicates fill, and a number n is also given, we have to check whether n new flowers can be planted in it without violating the no-adjacent-flowers rule or not.
So, if the input is like flowerbed = [1,0,0,0,1], n = 1, then the output will be True
To solve this, we will follow these steps β
if the size of flowerbed < n, then βreturn false
if the size of flowerbed < n, then β
return false
return false
if size of flowerbed is same as 1 and flowerbed[0] is same as 0 and n is same as 1, then βreturn true
if size of flowerbed is same as 1 and flowerbed[0] is same as 0 and n is same as 1, then β
return true
return true
for initialize i := 0, when i < size of flowerbed, update (increase i by 1), do βif n > 0, then βif i is same as 0, then βif flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then βflowerbed[0] := 1(decrease n by 1)otherwise when i is same as size of flowerbed - 1, then βif flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then βflowerbed[i] := 1(decrease n by 1)otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then βflowerbed[i] := 1(decrease n by 1)if n is same as 0, then βreturn true
for initialize i := 0, when i < size of flowerbed, update (increase i by 1), do β
if n > 0, then βif i is same as 0, then βif flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then βflowerbed[0] := 1(decrease n by 1)otherwise when i is same as size of flowerbed - 1, then βif flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then βflowerbed[i] := 1(decrease n by 1)otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then βflowerbed[i] := 1(decrease n by 1)
if n > 0, then β
if i is same as 0, then βif flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then βflowerbed[0] := 1(decrease n by 1)
if i is same as 0, then β
if flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then βflowerbed[0] := 1(decrease n by 1)
if flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then β
flowerbed[0] := 1
flowerbed[0] := 1
(decrease n by 1)
(decrease n by 1)
otherwise when i is same as size of flowerbed - 1, then βif flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then βflowerbed[i] := 1(decrease n by 1)
otherwise when i is same as size of flowerbed - 1, then β
if flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then βflowerbed[i] := 1(decrease n by 1)
if flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then β
flowerbed[i] := 1
flowerbed[i] := 1
(decrease n by 1)
(decrease n by 1)
otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then βflowerbed[i] := 1(decrease n by 1)
otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then β
flowerbed[i] := 1
flowerbed[i] := 1
(decrease n by 1)
(decrease n by 1)
if n is same as 0, then βreturn true
if n is same as 0, then β
return true
return true
if n is same as 0, then βreturn true
if n is same as 0, then β
return true
return true
return false
return false
Let us see the following implementation to get a better understanding β
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
if (flowerbed.size() < n)
return false;
if (flowerbed.size() == 1 && flowerbed[0] == 0 && n == 1)
return true;
for (int i = 0; i < flowerbed.size(); i++) {
if (n > 0) {
if (i == 0) {
if (flowerbed[i] == 0 && flowerbed[1] == 0) {
flowerbed[0] = 1;
n--;
}
}
else if (i == flowerbed.size() - 1) {
if (flowerbed[i] == 0 && flowerbed[i - 1] != 1) {
flowerbed[i] = 1;
n--;
}
}
else if (flowerbed[i] == 0 && flowerbed[i + 1] == 0 && flowerbed[i - 1] == 0) {
flowerbed[i] = 1;
n--;
}
}
if (n == 0) {
return true;
}
}
if (n == 0) {
return true;
}
return false;
}
};
main(){
Solution ob;
vector<int> v = {1,0,0,0,1};
cout << (ob.canPlaceFlowers(v, 1));
}
{1,0,0,0,1}, 1
1
|
[
{
"code": null,
"e": 1531,
"s": 1062,
"text": "Suppose we have a long flowerbed in which some of the plots are planted and some are empty. Now there is a constraint, flowers cannot be planted in adjacent plots, they would compete for water and both would die. So if we have a flowerbed, represented by an array containing 0 and 1, 0 indicates empty and 1 indicates fill, and a number n is also given, we have to check whether n new flowers can be planted in it without violating the no-adjacent-flowers rule or not."
},
{
"code": null,
"e": 1617,
"s": 1531,
"text": "So, if the input is like flowerbed = [1,0,0,0,1], n = 1, then the output will be True"
},
{
"code": null,
"e": 1661,
"s": 1617,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1710,
"s": 1661,
"text": "if the size of flowerbed < n, then βreturn false"
},
{
"code": null,
"e": 1747,
"s": 1710,
"text": "if the size of flowerbed < n, then β"
},
{
"code": null,
"e": 1760,
"s": 1747,
"text": "return false"
},
{
"code": null,
"e": 1773,
"s": 1760,
"text": "return false"
},
{
"code": null,
"e": 1875,
"s": 1773,
"text": "if size of flowerbed is same as 1 and flowerbed[0] is same as 0 and n is same as 1, then βreturn true"
},
{
"code": null,
"e": 1966,
"s": 1875,
"text": "if size of flowerbed is same as 1 and flowerbed[0] is same as 0 and n is same as 1, then β"
},
{
"code": null,
"e": 1978,
"s": 1966,
"text": "return true"
},
{
"code": null,
"e": 1990,
"s": 1978,
"text": "return true"
},
{
"code": null,
"e": 2565,
"s": 1990,
"text": "for initialize i := 0, when i < size of flowerbed, update (increase i by 1), do βif n > 0, then βif i is same as 0, then βif flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then βflowerbed[0] := 1(decrease n by 1)otherwise when i is same as size of flowerbed - 1, then βif flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then βflowerbed[i] := 1(decrease n by 1)otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then βflowerbed[i] := 1(decrease n by 1)if n is same as 0, then βreturn true"
},
{
"code": null,
"e": 2647,
"s": 2565,
"text": "for initialize i := 0, when i < size of flowerbed, update (increase i by 1), do β"
},
{
"code": null,
"e": 3105,
"s": 2647,
"text": "if n > 0, then βif i is same as 0, then βif flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then βflowerbed[0] := 1(decrease n by 1)otherwise when i is same as size of flowerbed - 1, then βif flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then βflowerbed[i] := 1(decrease n by 1)otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then βflowerbed[i] := 1(decrease n by 1)"
},
{
"code": null,
"e": 3122,
"s": 3105,
"text": "if n > 0, then β"
},
{
"code": null,
"e": 3248,
"s": 3122,
"text": "if i is same as 0, then βif flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then βflowerbed[0] := 1(decrease n by 1)"
},
{
"code": null,
"e": 3274,
"s": 3248,
"text": "if i is same as 0, then β"
},
{
"code": null,
"e": 3375,
"s": 3274,
"text": "if flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then βflowerbed[0] := 1(decrease n by 1)"
},
{
"code": null,
"e": 3442,
"s": 3375,
"text": "if flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then β"
},
{
"code": null,
"e": 3460,
"s": 3442,
"text": "flowerbed[0] := 1"
},
{
"code": null,
"e": 3478,
"s": 3460,
"text": "flowerbed[0] := 1"
},
{
"code": null,
"e": 3496,
"s": 3478,
"text": "(decrease n by 1)"
},
{
"code": null,
"e": 3514,
"s": 3496,
"text": "(decrease n by 1)"
},
{
"code": null,
"e": 3681,
"s": 3514,
"text": "otherwise when i is same as size of flowerbed - 1, then βif flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then βflowerbed[i] := 1(decrease n by 1)"
},
{
"code": null,
"e": 3739,
"s": 3681,
"text": "otherwise when i is same as size of flowerbed - 1, then β"
},
{
"code": null,
"e": 3849,
"s": 3739,
"text": "if flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then βflowerbed[i] := 1(decrease n by 1)"
},
{
"code": null,
"e": 3925,
"s": 3849,
"text": "if flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then β"
},
{
"code": null,
"e": 3943,
"s": 3925,
"text": "flowerbed[i] := 1"
},
{
"code": null,
"e": 3961,
"s": 3943,
"text": "flowerbed[i] := 1"
},
{
"code": null,
"e": 3979,
"s": 3961,
"text": "(decrease n by 1)"
},
{
"code": null,
"e": 3997,
"s": 3979,
"text": "(decrease n by 1)"
},
{
"code": null,
"e": 4148,
"s": 3997,
"text": "otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then βflowerbed[i] := 1(decrease n by 1)"
},
{
"code": null,
"e": 4265,
"s": 4148,
"text": "otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then β"
},
{
"code": null,
"e": 4283,
"s": 4265,
"text": "flowerbed[i] := 1"
},
{
"code": null,
"e": 4301,
"s": 4283,
"text": "flowerbed[i] := 1"
},
{
"code": null,
"e": 4319,
"s": 4301,
"text": "(decrease n by 1)"
},
{
"code": null,
"e": 4337,
"s": 4319,
"text": "(decrease n by 1)"
},
{
"code": null,
"e": 4374,
"s": 4337,
"text": "if n is same as 0, then βreturn true"
},
{
"code": null,
"e": 4400,
"s": 4374,
"text": "if n is same as 0, then β"
},
{
"code": null,
"e": 4412,
"s": 4400,
"text": "return true"
},
{
"code": null,
"e": 4424,
"s": 4412,
"text": "return true"
},
{
"code": null,
"e": 4461,
"s": 4424,
"text": "if n is same as 0, then βreturn true"
},
{
"code": null,
"e": 4487,
"s": 4461,
"text": "if n is same as 0, then β"
},
{
"code": null,
"e": 4499,
"s": 4487,
"text": "return true"
},
{
"code": null,
"e": 4511,
"s": 4499,
"text": "return true"
},
{
"code": null,
"e": 4524,
"s": 4511,
"text": "return false"
},
{
"code": null,
"e": 4537,
"s": 4524,
"text": "return false"
},
{
"code": null,
"e": 4609,
"s": 4537,
"text": "Let us see the following implementation to get a better understanding β"
},
{
"code": null,
"e": 4620,
"s": 4609,
"text": " Live Demo"
},
{
"code": null,
"e": 5741,
"s": 4620,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n bool canPlaceFlowers(vector<int>& flowerbed, int n) {\n if (flowerbed.size() < n)\n return false;\n if (flowerbed.size() == 1 && flowerbed[0] == 0 && n == 1)\n return true;\n for (int i = 0; i < flowerbed.size(); i++) {\n if (n > 0) {\n if (i == 0) {\n if (flowerbed[i] == 0 && flowerbed[1] == 0) {\n flowerbed[0] = 1;\n n--;\n }\n }\n else if (i == flowerbed.size() - 1) {\n if (flowerbed[i] == 0 && flowerbed[i - 1] != 1) {\n flowerbed[i] = 1;\n n--;\n }\n }\n else if (flowerbed[i] == 0 && flowerbed[i + 1] == 0 && flowerbed[i - 1] == 0) {\nflowerbed[i] = 1;\n n--;\n }\n }\n if (n == 0) {\n return true;\n }\n }\n if (n == 0) {\n return true;\n }\n return false;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,0,0,0,1};\n cout << (ob.canPlaceFlowers(v, 1));\n}"
},
{
"code": null,
"e": 5756,
"s": 5741,
"text": "{1,0,0,0,1}, 1"
},
{
"code": null,
"e": 5758,
"s": 5756,
"text": "1"
}
] |
Tweets, Emoji Sentiment Analysis using Q Blocks | by Michelangiolo Mazzeschi | Towards Data Science
|
In the following article, I will rent the Q Blocks GPU to run a computational demanding AI model. I will run a deep learning model called DeepMoji that, given a sentence, will estimate the top n emotions that can describe it (click not the link to have a try). The platform I will be renting the GPU from is still in early access, so you can try it (this platform gives you 20 Hours of GPU for FREE, an excellent start) out even before making a purchase and see if you are comfortable with it.
To proceed with this experiment, I wanted to rent GPU from an alternative provider rather than Amazon AWS, I have been told it is expensive., and it only becomes convenient if you run gigantic models.
So far, I found a good offer trying Q Blocks GPU. GPU is bought not by usage, but by time. The offer cost as little as .05$ per hour. Is a very reasonable price, you would be essentially paying a GPU at the same cost of a CPU. The distributed computing technology used by Q Blocks allows this provider to maintain prices down without diminishing quality.
If you are a beginner, definitely not. Common online compilers such as Google Colab or Kaggle offer a FREE (but not powerful) computational power. If you are working on small datasets as every beginner does, it does not require high computational power, and you can use FREE versions.
Instead, if you need to tune your model (like every professional need to) you will have to wait countless hours in front of the PC waiting for the results that will likely disappoint you. The step forward to build more challenging models is increasing your computational power.
For example, running this algorithm without using a GPU would have taken me several hours to complete. My experiment consists in reaching the completion of the project faster.
I will use the screenshots for this service to facilitate things. However, I am assuming every provider has different offers depending on your needs. Because I wonβt need excessive computational power I can start using 100 Blocks per hour, the equivalent of .10$ per hour.
If this is your first time renting GPU, you might find it frustrating. When you initiate the model, it will start consuming. Therefore, it is of vital importance that you know what you are doing and you do not experiment in the notebook provided by the service. If there are bugs and you need to debug your code inside a paid workbook, your time will cost money. At the point when you have realized how much money that debugging time costed you, you will likely move to another GPU provider.
***Make sure you have a copy of your working model inside another workbook. You can simply import that copy and run it without wasting precious time.
Q Blocks has a connection to an online Jupyter Notebook. There could be some issues if you start your models in Google Colab, for example. Accessing files or downloading libraries has a slightly different syntax, and you could waste time searching for the solutions online, while your notebook is running. Because I encountered similar issues in the making of this model, I will explain how to overcome the solutions in detail.
Therefore, before code your model in a FREE Jupyter Workbook, then, if it is working, import that model on the platform you are using (in my case Q Blocks) to save time.
The provider will likely start an empty notebook with the GPU loaded. We can start coding...
The first thing you want to do is import a dataset that you can access. Every notebook has a section where to upload documents, I will later create a connection to that document importing it with pandas.
Probably, the tough thing to do when attempting this experiment will be installing torchMoji. I will divide the installation into two parts. First, I will be installing the required libraries that will allow torchMoji to run:
!pip3 install torch==1.0.1 -f https://download.pytorch.org/whl/cpu/stable !git clone https://github.com/huggingface/torchMojiimport osos.chdir('torchMoji')!pip3 install -e .#if you restart the package, the notebook risks to crash on a loop#if you managed to be curious and to make it stuck, just clic on RunTime, Factory Reset Runtime#I did not restart and worked fine#se questo funziona, poi crasha in future linee di codice, anche se chiudiamo e riapriamo dovrebbe essere a posto per 12 ore
In the second step, I will download and install the weights that will allow the Neural Network to select the emoji based on any text.
***Be very careful, there is a bug (I do not know if I could classify it as such) in Jupyter Notebook that prevents you from inputting an answer such as yes or no. To solve this issue and prevent your GPU to iterate on a loop eating your available processing power, use the following line of code that should solve the issue on Jupyter Notebook.
#!python3 scripts/download_weights.py! yes | python3 scripts/download_weights.py
In a conventional notebook, you should be allowed to choose between the options yes and no. However, Jupyter Notebook does not offer you any possibility of inputting a choice. I have bypassed it using the code above, and immediately stating the yes choice.
I will now create a function that as an input will take one string of text and, depending on the number of emotions we want to extract, will output the corresponding emojis.
#si connette a DeepMoji per una request, non posso modificare i parametri, credo!python3 examples/text_emojize.py --text f" {Stay safe from the virus} "!pip3 install --upgrade numpy!pip install numpy==1.18!pip install scipy==1.1.0!pip install scikit-learn==0.21.3import numpy as npimport emoji, jsonfrom torchmoji.global_variables import PRETRAINED_PATH, VOCAB_PATHfrom torchmoji.sentence_tokenizer import SentenceTokenizerfrom torchmoji.model_def import torchmoji_emojis EMOJIS = ":joy: :unamused: :weary: :sob: :heart_eyes: :pensive: :ok_hand: :blush: :heart: :smirk: :grin: :notes: :flushed: :100: :sleeping: :relieved: :relaxed: :raised_hands: :two_hearts: :expressionless: :sweat_smile: :pray: :confused: :kissing_heart: :heartbeat: :neutral_face: :information_desk_person: :disappointed: :see_no_evil: :tired_face: :v: :sunglasses: :rage: :thumbsup: :cry: :sleepy: :yum: :triumph: :hand: :mask: :clap: :eyes: :gun: :persevere: :smiling_imp: :sweat: :broken_heart: :yellow_heart: :musical_note: :speak_no_evil: :wink: :skull: :confounded: :smile: :stuck_out_tongue_winking_eye: :angry: :no_good: :muscle: :facepunch: :purple_heart: :sparkling_heart: :blue_heart: :grimacing: :sparkles:".split(' ')model = torchmoji_emojis(PRETRAINED_PATH)with open(VOCAB_PATH, 'r') as f: vocabulary = json.load(f)st = SentenceTokenizer(vocabulary, 30)def deepmojify(sentence, top_n=5, return_emoji=True, return_prob=False): #converte lista probabilitaΜ in emoticon piuΜ probabili def top_elements(array, k): ind = np.argpartition(array, -k)[-k:] return ind[np.argsort(array[ind])][::-1]tokenized, _, _ = st.tokenize_sentences([sentence]) #print(tokenized) #lista di probabilitaΜ prob = model(tokenized)[0] #se ci sono errori parte da qui: too many values to unpack (expected 2), non riesce a trovare prob #trova le n emoticono piuΜ alte emoji_ids = top_elements(prob, top_n)#converte questi numeri in emoticons emojis = map(lambda x: EMOJIS[x], emoji_ids) if return_emoji == False and return_prob == False: return None elif return_emoji == True and return_prob == False: return emoji.emojize(f"{sentence} {' '.join(emojis)}", use_aliases=True) elif return_emoji == True and return_prob == True: return emoji.emojize(f"{sentence} {' '.join(emojis)}", use_aliases=True), prob elif return_emoji == False and return_prob == True: return probdeepmojify('ciao, come stai?', top_n=3, return_emoji=True, return_prob=False)
The output of the inputted string will be the following:
'ciao, come stai? π π β€'
I will now create a function that converts a list into a dataset with its estimated emoji in different columns. As you can see from the string above, the function concatenated the emoji with the input string, I will break them and place each one in a different column of the dataset.
def emoji_dataset(list1, n_emoji=3, only_prob=False): emoji_list = [[x] for x in list1]for _ in range(len(list1)): for n_emo in range(1, n_emoji+1): print(_) if only_prob == False: emoji_list[_].append(deepmojify(list1[_], top_n=n_emoji, return_emoji=True, return_prob=False)[2*-n_emo+1]) else: emoji_list[_].append(deepmojify(list1[_], top_n=1, return_emoji=False, return_prob=True))emoji_list = pd.DataFrame(emoji_list) return emoji_listdf_ = emoji_dataset(list1, 3)df_
Now that I am all set, I can run the entire project. I will download the dataset, quickly preprocess it, and then initiate the algorithm.
import pandas as pdX = pd.read_csv(open('tweets.csv'))
If you havenβt noticed yet, I am using the function open inside read_csv. Without this function, the code will return an error. This behavior is peculiar to Jupyter Notebook.
X.pop('Unnamed: 0')X = pd.DataFrame(X)X.columns = ['tweets']Xdf = X.copy()df
As a final step, I will turn the list of 25,000 tweets into a list. I can use the list as an input for the main function.
list1 = df['tweets'].to_list()
I can finally start the model. As a result, I will have a list of 25,000 tweets with corresponding emotions.
list1 = list1[0:25000]df_.to_csv('25k_emotions.csv')df_
When your model is set, do not forget to delete the Notebook to save your remaining credits.
The model performed relatively faster. Compared with the GPU of the FREE cloud compilers can reach a speed 10x faster. Running this algorithm on Google Colab required a bit more than 1 hour, by comparison, took me approximately 10 minutes to reach the same result using Q Blocks. If you are going to rent more powerful GPUs, depending on your needs, this number will only increase.
Cloud Computing is soon going to be the new norm. With revolutionary innovations such as blockchains and pixel streaming technology, people wonβt need to buy GPU hardware anymore. Providers such as Q Blocks, who use a peer to peer computing, contribute by making computing power more accessible, accelerating innovation.
|
[
{
"code": null,
"e": 666,
"s": 172,
"text": "In the following article, I will rent the Q Blocks GPU to run a computational demanding AI model. I will run a deep learning model called DeepMoji that, given a sentence, will estimate the top n emotions that can describe it (click not the link to have a try). The platform I will be renting the GPU from is still in early access, so you can try it (this platform gives you 20 Hours of GPU for FREE, an excellent start) out even before making a purchase and see if you are comfortable with it."
},
{
"code": null,
"e": 867,
"s": 666,
"text": "To proceed with this experiment, I wanted to rent GPU from an alternative provider rather than Amazon AWS, I have been told it is expensive., and it only becomes convenient if you run gigantic models."
},
{
"code": null,
"e": 1222,
"s": 867,
"text": "So far, I found a good offer trying Q Blocks GPU. GPU is bought not by usage, but by time. The offer cost as little as .05$ per hour. Is a very reasonable price, you would be essentially paying a GPU at the same cost of a CPU. The distributed computing technology used by Q Blocks allows this provider to maintain prices down without diminishing quality."
},
{
"code": null,
"e": 1507,
"s": 1222,
"text": "If you are a beginner, definitely not. Common online compilers such as Google Colab or Kaggle offer a FREE (but not powerful) computational power. If you are working on small datasets as every beginner does, it does not require high computational power, and you can use FREE versions."
},
{
"code": null,
"e": 1785,
"s": 1507,
"text": "Instead, if you need to tune your model (like every professional need to) you will have to wait countless hours in front of the PC waiting for the results that will likely disappoint you. The step forward to build more challenging models is increasing your computational power."
},
{
"code": null,
"e": 1961,
"s": 1785,
"text": "For example, running this algorithm without using a GPU would have taken me several hours to complete. My experiment consists in reaching the completion of the project faster."
},
{
"code": null,
"e": 2234,
"s": 1961,
"text": "I will use the screenshots for this service to facilitate things. However, I am assuming every provider has different offers depending on your needs. Because I wonβt need excessive computational power I can start using 100 Blocks per hour, the equivalent of .10$ per hour."
},
{
"code": null,
"e": 2726,
"s": 2234,
"text": "If this is your first time renting GPU, you might find it frustrating. When you initiate the model, it will start consuming. Therefore, it is of vital importance that you know what you are doing and you do not experiment in the notebook provided by the service. If there are bugs and you need to debug your code inside a paid workbook, your time will cost money. At the point when you have realized how much money that debugging time costed you, you will likely move to another GPU provider."
},
{
"code": null,
"e": 2876,
"s": 2726,
"text": "***Make sure you have a copy of your working model inside another workbook. You can simply import that copy and run it without wasting precious time."
},
{
"code": null,
"e": 3304,
"s": 2876,
"text": "Q Blocks has a connection to an online Jupyter Notebook. There could be some issues if you start your models in Google Colab, for example. Accessing files or downloading libraries has a slightly different syntax, and you could waste time searching for the solutions online, while your notebook is running. Because I encountered similar issues in the making of this model, I will explain how to overcome the solutions in detail."
},
{
"code": null,
"e": 3474,
"s": 3304,
"text": "Therefore, before code your model in a FREE Jupyter Workbook, then, if it is working, import that model on the platform you are using (in my case Q Blocks) to save time."
},
{
"code": null,
"e": 3567,
"s": 3474,
"text": "The provider will likely start an empty notebook with the GPU loaded. We can start coding..."
},
{
"code": null,
"e": 3771,
"s": 3567,
"text": "The first thing you want to do is import a dataset that you can access. Every notebook has a section where to upload documents, I will later create a connection to that document importing it with pandas."
},
{
"code": null,
"e": 3997,
"s": 3771,
"text": "Probably, the tough thing to do when attempting this experiment will be installing torchMoji. I will divide the installation into two parts. First, I will be installing the required libraries that will allow torchMoji to run:"
},
{
"code": null,
"e": 4490,
"s": 3997,
"text": "!pip3 install torch==1.0.1 -f https://download.pytorch.org/whl/cpu/stable !git clone https://github.com/huggingface/torchMojiimport osos.chdir('torchMoji')!pip3 install -e .#if you restart the package, the notebook risks to crash on a loop#if you managed to be curious and to make it stuck, just clic on RunTime, Factory Reset Runtime#I did not restart and worked fine#se questo funziona, poi crasha in future linee di codice, anche se chiudiamo e riapriamo dovrebbe essere a posto per 12 ore"
},
{
"code": null,
"e": 4624,
"s": 4490,
"text": "In the second step, I will download and install the weights that will allow the Neural Network to select the emoji based on any text."
},
{
"code": null,
"e": 4970,
"s": 4624,
"text": "***Be very careful, there is a bug (I do not know if I could classify it as such) in Jupyter Notebook that prevents you from inputting an answer such as yes or no. To solve this issue and prevent your GPU to iterate on a loop eating your available processing power, use the following line of code that should solve the issue on Jupyter Notebook."
},
{
"code": null,
"e": 5051,
"s": 4970,
"text": "#!python3 scripts/download_weights.py! yes | python3 scripts/download_weights.py"
},
{
"code": null,
"e": 5308,
"s": 5051,
"text": "In a conventional notebook, you should be allowed to choose between the options yes and no. However, Jupyter Notebook does not offer you any possibility of inputting a choice. I have bypassed it using the code above, and immediately stating the yes choice."
},
{
"code": null,
"e": 5482,
"s": 5308,
"text": "I will now create a function that as an input will take one string of text and, depending on the number of emotions we want to extract, will output the corresponding emojis."
},
{
"code": null,
"e": 7921,
"s": 5482,
"text": "#si connette a DeepMoji per una request, non posso modificare i parametri, credo!python3 examples/text_emojize.py --text f\" {Stay safe from the virus} \"!pip3 install --upgrade numpy!pip install numpy==1.18!pip install scipy==1.1.0!pip install scikit-learn==0.21.3import numpy as npimport emoji, jsonfrom torchmoji.global_variables import PRETRAINED_PATH, VOCAB_PATHfrom torchmoji.sentence_tokenizer import SentenceTokenizerfrom torchmoji.model_def import torchmoji_emojis EMOJIS = \":joy: :unamused: :weary: :sob: :heart_eyes: :pensive: :ok_hand: :blush: :heart: :smirk: :grin: :notes: :flushed: :100: :sleeping: :relieved: :relaxed: :raised_hands: :two_hearts: :expressionless: :sweat_smile: :pray: :confused: :kissing_heart: :heartbeat: :neutral_face: :information_desk_person: :disappointed: :see_no_evil: :tired_face: :v: :sunglasses: :rage: :thumbsup: :cry: :sleepy: :yum: :triumph: :hand: :mask: :clap: :eyes: :gun: :persevere: :smiling_imp: :sweat: :broken_heart: :yellow_heart: :musical_note: :speak_no_evil: :wink: :skull: :confounded: :smile: :stuck_out_tongue_winking_eye: :angry: :no_good: :muscle: :facepunch: :purple_heart: :sparkling_heart: :blue_heart: :grimacing: :sparkles:\".split(' ')model = torchmoji_emojis(PRETRAINED_PATH)with open(VOCAB_PATH, 'r') as f: vocabulary = json.load(f)st = SentenceTokenizer(vocabulary, 30)def deepmojify(sentence, top_n=5, return_emoji=True, return_prob=False): #converte lista probabilitaΜ in emoticon piuΜ probabili def top_elements(array, k): ind = np.argpartition(array, -k)[-k:] return ind[np.argsort(array[ind])][::-1]tokenized, _, _ = st.tokenize_sentences([sentence]) #print(tokenized) #lista di probabilitaΜ prob = model(tokenized)[0] #se ci sono errori parte da qui: too many values to unpack (expected 2), non riesce a trovare prob #trova le n emoticono piuΜ alte emoji_ids = top_elements(prob, top_n)#converte questi numeri in emoticons emojis = map(lambda x: EMOJIS[x], emoji_ids) if return_emoji == False and return_prob == False: return None elif return_emoji == True and return_prob == False: return emoji.emojize(f\"{sentence} {' '.join(emojis)}\", use_aliases=True) elif return_emoji == True and return_prob == True: return emoji.emojize(f\"{sentence} {' '.join(emojis)}\", use_aliases=True), prob elif return_emoji == False and return_prob == True: return probdeepmojify('ciao, come stai?', top_n=3, return_emoji=True, return_prob=False)"
},
{
"code": null,
"e": 7978,
"s": 7921,
"text": "The output of the inputted string will be the following:"
},
{
"code": null,
"e": 8003,
"s": 7978,
"text": "'ciao, come stai? π π β€'"
},
{
"code": null,
"e": 8287,
"s": 8003,
"text": "I will now create a function that converts a list into a dataset with its estimated emoji in different columns. As you can see from the string above, the function concatenated the emoji with the input string, I will break them and place each one in a different column of the dataset."
},
{
"code": null,
"e": 8793,
"s": 8287,
"text": "def emoji_dataset(list1, n_emoji=3, only_prob=False): emoji_list = [[x] for x in list1]for _ in range(len(list1)): for n_emo in range(1, n_emoji+1): print(_) if only_prob == False: emoji_list[_].append(deepmojify(list1[_], top_n=n_emoji, return_emoji=True, return_prob=False)[2*-n_emo+1]) else: emoji_list[_].append(deepmojify(list1[_], top_n=1, return_emoji=False, return_prob=True))emoji_list = pd.DataFrame(emoji_list) return emoji_listdf_ = emoji_dataset(list1, 3)df_"
},
{
"code": null,
"e": 8931,
"s": 8793,
"text": "Now that I am all set, I can run the entire project. I will download the dataset, quickly preprocess it, and then initiate the algorithm."
},
{
"code": null,
"e": 8986,
"s": 8931,
"text": "import pandas as pdX = pd.read_csv(open('tweets.csv'))"
},
{
"code": null,
"e": 9161,
"s": 8986,
"text": "If you havenβt noticed yet, I am using the function open inside read_csv. Without this function, the code will return an error. This behavior is peculiar to Jupyter Notebook."
},
{
"code": null,
"e": 9238,
"s": 9161,
"text": "X.pop('Unnamed: 0')X = pd.DataFrame(X)X.columns = ['tweets']Xdf = X.copy()df"
},
{
"code": null,
"e": 9360,
"s": 9238,
"text": "As a final step, I will turn the list of 25,000 tweets into a list. I can use the list as an input for the main function."
},
{
"code": null,
"e": 9391,
"s": 9360,
"text": "list1 = df['tweets'].to_list()"
},
{
"code": null,
"e": 9500,
"s": 9391,
"text": "I can finally start the model. As a result, I will have a list of 25,000 tweets with corresponding emotions."
},
{
"code": null,
"e": 9556,
"s": 9500,
"text": "list1 = list1[0:25000]df_.to_csv('25k_emotions.csv')df_"
},
{
"code": null,
"e": 9649,
"s": 9556,
"text": "When your model is set, do not forget to delete the Notebook to save your remaining credits."
},
{
"code": null,
"e": 10031,
"s": 9649,
"text": "The model performed relatively faster. Compared with the GPU of the FREE cloud compilers can reach a speed 10x faster. Running this algorithm on Google Colab required a bit more than 1 hour, by comparison, took me approximately 10 minutes to reach the same result using Q Blocks. If you are going to rent more powerful GPUs, depending on your needs, this number will only increase."
}
] |
Count the divisors or multiples present in the Array for each element - GeeksforGeeks
|
15 Sep, 2021
Given an array A[] with N integers, for each integer A[i] in the array, the task is to find the number of integers A[j] (j != i) in the array such that A[i] % A[j] = 0 or A[j] % A[i] = 0.
Examples:
Input: A = {2, 3, 4, 5, 6}Output: 2 1 1 0 2Explanation: For i=0, the valid indices are 2 and 4 as 4%2 = 0 and 6%2 = 0.For i=1, the only valid index is 4 as 6%3 = 0.For i=2, the only valid index is 0 as 4%2 = 0.For i=3, there are no valid indices.For i=0, the valid indices are 0 and 1 as 6%2 = 0 and 6%3 = 0.
Input: A = {6, 6, 6, 6, 6}Output: 4 4 4 4 4
Approach: The given problem can be solved by using the observation that the number of integers that satisfies the given condition can be categorized into two cases. Suppose the current integer is P and Q is an integer that satisfies the given conditions.
Case 1 where Q is a multiple of P. Therefore, the count of integers in the given array that are divisible by P is the required answer. This case can be handled using a simple modification of Sieve of Eratosthenes which is discussed here.
Case 2 where P is a multiple of Q. Therefore, the count of integers in the given array that Q divides P is the required answer. This case can be handled similarly using sieve as that of 1st Case.
So, the required answer for any integer is the sum of resulting integers of Case 1 and Case 2. In cases where P = Q, both Case 1 and Case 2 represents the same value and should be considered only once.
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 find the count of integers// such that A[i]%A[j] = 0 or A[j]%A[i] = 0// for each index of the array A[]void countIndex(int A[], int N){ // Stores the maximum integer in A[] int MAX = *max_element(A, A + N); // Stores the frequency of each // element in the array A[] vector<int> freq(MAX + 1, 0); for (int i = 0; i < N; i++) freq[A[i]]++; // Stores the valid integers in A[] // for all integers from 1 to MAX vector<int> res(MAX + 1, 0); for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) { // Case where P = Q if (i == j) { // Subtract 1 because P & Q // cannot have same index res[i] += (freq[j] - 1); } else { // Case 1 res[i] += freq[j]; // Case 2 res[j] += freq[i]; } } } // Loop to print answer for // each index of array A[] for (int i = 0; i < N; i++) { cout << res[A[i]] << " "; }} // Driver Codeint main(){ int A[] = { 2, 3, 4, 5, 6 }; int N = sizeof(A) / sizeof(int); // Function Call countIndex(A, N); return 0;}
// Java Program for the above approachimport java.util.*; class GFG{ // Function to find the count of integers// such that A[i]%A[j] = 0 or A[j]%A[i] = 0// for each index of the array []Astatic void countIndex(int []A, int N){ // Stores the maximum integer in []A int MAX = Arrays.stream(A).max().getAsInt(); // Stores the frequency of each // element in the array []A int []freq = new int[MAX + 1]; for (int i = 0; i < N; i++) freq[A[i]]++; // Stores the valid integers in []A // for all integers from 1 to MAX int []res = new int[MAX + 1]; for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) { // Case where P = Q if (i == j) { // Subtract 1 because P & Q // cannot have same index res[i] += (freq[j] - 1); } else { // Case 1 res[i] += freq[j]; // Case 2 res[j] += freq[i]; } } } // Loop to print answer for // each index of array []A for (int i = 0; i < N; i++) { System.out.print(res[A[i]]+ " "); }} // Driver Codepublic static void main(String[] args){ int []A = { 2, 3, 4, 5, 6 }; int N = A.length; // Function Call countIndex(A, N);}} // This code is contributed by Princi Singh
# Python 3 Program for the above approach # Function to find the count of integers# such that A[i]%A[j] = 0 or A[j]%A[i] = 0# for each index of the array A[]def countIndex(A, N): # Stores the maximum integer in A[] MAX = max(A) # Stores the frequency of each # element in the array A[] freq = [0 for i in range(MAX+1)] for i in range(N): if A[i] in freq: freq[A[i]] += 1 else: freq[A[i]] = 1 # Stores the valid integers in A[] # for all integers from 1 to MAX res = [0 for i in range(MAX+1)] for i in range(1, MAX + 1, 1): for j in range(i, MAX + 1, i): # Case where P = Q if (i == j): # Subtract 1 because P & Q # cannot have same index res[i] += (freq[j] - 1) else: # Case 1 res[i] += freq[j] # Case 2 res[j] += freq[i] # Loop to print answer for # each index of array A[] for i in range(N): print(res[A[i]],end = " ") # Driver Codeif __name__ == '__main__': A = [2, 3, 4, 5, 6] N = len(A) # Function Call countIndex(A, N) # This code is contributed by SURENDRA_GANGWAR.
// C# program of above approachusing System; public class GFG { static void countIndex(int[] A, int N) { // Stores the maximum integer in []A int MAX = A[0]; for (int i = 1; i < N; i++) { if (A[i] > MAX) { MAX = A[i]; } } // Stores the frequency of each // element in the array []A int[] freq = new int[MAX + 1]; for (int i = 0; i < N; i++) freq[A[i]]++; // Stores the valid integers in []A // for all integers from 1 to MAX int[] res = new int[MAX + 1]; for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) { // Case where P = Q if (i == j) { // Subtract 1 because P & Q // cannot have same index res[i] += (freq[j] - 1); } else { // Case 1 res[i] += freq[j]; // Case 2 res[j] += freq[i]; } } } // Loop to print answer for // each index of array []A for (int i = 0; i < N; i++) { Console.Write(res[A[i]] + " "); } } // Driver Code static public void Main() { int[] A = { 2, 3, 4, 5, 6 }; int N = A.Length; // Function Call countIndex(A, N); }} // This code is contributed by maddler.
<script> // JavaScript program for the above approach; // Function to find the count of integers // such that A[i]%A[j] = 0 or A[j]%A[i] = 0 // for each index of the array A[] function max_element(A, N) { let MAX = Number.MIN_VALUE; for (let i = 0; i < A.length; i++) { if (A[i] > MAX) { MAX = A[i]; } } return MAX; } function countIndex(A, N) { // Stores the maximum integer in A[] let MAX = max_element(A, A + N); // Stores the frequency of each // element in the array A[] let freq = new Array(MAX + 1).fill(0); for (let i = 0; i < N; i++) freq[A[i]]++; // Stores the valid integers in A[] // for all integers from 1 to MAX let res = new Array(MAX + 1).fill(0); for (let i = 1; i <= MAX; ++i) { for (let j = i; j <= MAX; j += i) { // Case where P = Q if (i == j) { // Subtract 1 because P & Q // cannot have same index res[i] += (freq[j] - 1); } else { // Case 1 res[i] += freq[j]; // Case 2 res[j] += freq[i]; } } } // Loop to print answer for // each index of array A[] for (let i = 0; i < N; i++) { document.write(res[A[i]] + " "); } } // Driver Code let A = [2, 3, 4, 5, 6]; let N = A.length; // Function Call countIndex(A, N); // This code is contributed by Potta Lokesh </script>
2 1 1 0 2
Time Complexity: O(N*log N)Auxiliary Space: O(MAX) where MAX represents the maximum integer in the given array.
lokeshpotta20
princi singh
maddler
SURENDRA_GANGWAR
singghakshay
khushboogoyal499
divisors
sieve
Arrays
Mathematical
Arrays
Mathematical
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Building Heap from Array
Program to find sum of elements in a given array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 24984,
"s": 24796,
"text": "Given an array A[] with N integers, for each integer A[i] in the array, the task is to find the number of integers A[j] (j != i) in the array such that A[i] % A[j] = 0 or A[j] % A[i] = 0."
},
{
"code": null,
"e": 24994,
"s": 24984,
"text": "Examples:"
},
{
"code": null,
"e": 25303,
"s": 24994,
"text": "Input: A = {2, 3, 4, 5, 6}Output: 2 1 1 0 2Explanation: For i=0, the valid indices are 2 and 4 as 4%2 = 0 and 6%2 = 0.For i=1, the only valid index is 4 as 6%3 = 0.For i=2, the only valid index is 0 as 4%2 = 0.For i=3, there are no valid indices.For i=0, the valid indices are 0 and 1 as 6%2 = 0 and 6%3 = 0."
},
{
"code": null,
"e": 25347,
"s": 25303,
"text": "Input: A = {6, 6, 6, 6, 6}Output: 4 4 4 4 4"
},
{
"code": null,
"e": 25603,
"s": 25347,
"text": " Approach: The given problem can be solved by using the observation that the number of integers that satisfies the given condition can be categorized into two cases. Suppose the current integer is P and Q is an integer that satisfies the given conditions."
},
{
"code": null,
"e": 25841,
"s": 25603,
"text": "Case 1 where Q is a multiple of P. Therefore, the count of integers in the given array that are divisible by P is the required answer. This case can be handled using a simple modification of Sieve of Eratosthenes which is discussed here."
},
{
"code": null,
"e": 26037,
"s": 25841,
"text": "Case 2 where P is a multiple of Q. Therefore, the count of integers in the given array that Q divides P is the required answer. This case can be handled similarly using sieve as that of 1st Case."
},
{
"code": null,
"e": 26239,
"s": 26037,
"text": "So, the required answer for any integer is the sum of resulting integers of Case 1 and Case 2. In cases where P = Q, both Case 1 and Case 2 represents the same value and should be considered only once."
},
{
"code": null,
"e": 26290,
"s": 26239,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26294,
"s": 26290,
"text": "C++"
},
{
"code": null,
"e": 26299,
"s": 26294,
"text": "Java"
},
{
"code": null,
"e": 26307,
"s": 26299,
"text": "Python3"
},
{
"code": null,
"e": 26310,
"s": 26307,
"text": "C#"
},
{
"code": null,
"e": 26321,
"s": 26310,
"text": "Javascript"
},
{
"code": "// C++ Program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of integers// such that A[i]%A[j] = 0 or A[j]%A[i] = 0// for each index of the array A[]void countIndex(int A[], int N){ // Stores the maximum integer in A[] int MAX = *max_element(A, A + N); // Stores the frequency of each // element in the array A[] vector<int> freq(MAX + 1, 0); for (int i = 0; i < N; i++) freq[A[i]]++; // Stores the valid integers in A[] // for all integers from 1 to MAX vector<int> res(MAX + 1, 0); for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) { // Case where P = Q if (i == j) { // Subtract 1 because P & Q // cannot have same index res[i] += (freq[j] - 1); } else { // Case 1 res[i] += freq[j]; // Case 2 res[j] += freq[i]; } } } // Loop to print answer for // each index of array A[] for (int i = 0; i < N; i++) { cout << res[A[i]] << \" \"; }} // Driver Codeint main(){ int A[] = { 2, 3, 4, 5, 6 }; int N = sizeof(A) / sizeof(int); // Function Call countIndex(A, N); return 0;}",
"e": 27618,
"s": 26321,
"text": null
},
{
"code": "// Java Program for the above approachimport java.util.*; class GFG{ // Function to find the count of integers// such that A[i]%A[j] = 0 or A[j]%A[i] = 0// for each index of the array []Astatic void countIndex(int []A, int N){ // Stores the maximum integer in []A int MAX = Arrays.stream(A).max().getAsInt(); // Stores the frequency of each // element in the array []A int []freq = new int[MAX + 1]; for (int i = 0; i < N; i++) freq[A[i]]++; // Stores the valid integers in []A // for all integers from 1 to MAX int []res = new int[MAX + 1]; for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) { // Case where P = Q if (i == j) { // Subtract 1 because P & Q // cannot have same index res[i] += (freq[j] - 1); } else { // Case 1 res[i] += freq[j]; // Case 2 res[j] += freq[i]; } } } // Loop to print answer for // each index of array []A for (int i = 0; i < N; i++) { System.out.print(res[A[i]]+ \" \"); }} // Driver Codepublic static void main(String[] args){ int []A = { 2, 3, 4, 5, 6 }; int N = A.length; // Function Call countIndex(A, N);}} // This code is contributed by Princi Singh",
"e": 28975,
"s": 27618,
"text": null
},
{
"code": "# Python 3 Program for the above approach # Function to find the count of integers# such that A[i]%A[j] = 0 or A[j]%A[i] = 0# for each index of the array A[]def countIndex(A, N): # Stores the maximum integer in A[] MAX = max(A) # Stores the frequency of each # element in the array A[] freq = [0 for i in range(MAX+1)] for i in range(N): if A[i] in freq: freq[A[i]] += 1 else: freq[A[i]] = 1 # Stores the valid integers in A[] # for all integers from 1 to MAX res = [0 for i in range(MAX+1)] for i in range(1, MAX + 1, 1): for j in range(i, MAX + 1, i): # Case where P = Q if (i == j): # Subtract 1 because P & Q # cannot have same index res[i] += (freq[j] - 1) else: # Case 1 res[i] += freq[j] # Case 2 res[j] += freq[i] # Loop to print answer for # each index of array A[] for i in range(N): print(res[A[i]],end = \" \") # Driver Codeif __name__ == '__main__': A = [2, 3, 4, 5, 6] N = len(A) # Function Call countIndex(A, N) # This code is contributed by SURENDRA_GANGWAR.",
"e": 30231,
"s": 28975,
"text": null
},
{
"code": "// C# program of above approachusing System; public class GFG { static void countIndex(int[] A, int N) { // Stores the maximum integer in []A int MAX = A[0]; for (int i = 1; i < N; i++) { if (A[i] > MAX) { MAX = A[i]; } } // Stores the frequency of each // element in the array []A int[] freq = new int[MAX + 1]; for (int i = 0; i < N; i++) freq[A[i]]++; // Stores the valid integers in []A // for all integers from 1 to MAX int[] res = new int[MAX + 1]; for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) { // Case where P = Q if (i == j) { // Subtract 1 because P & Q // cannot have same index res[i] += (freq[j] - 1); } else { // Case 1 res[i] += freq[j]; // Case 2 res[j] += freq[i]; } } } // Loop to print answer for // each index of array []A for (int i = 0; i < N; i++) { Console.Write(res[A[i]] + \" \"); } } // Driver Code static public void Main() { int[] A = { 2, 3, 4, 5, 6 }; int N = A.Length; // Function Call countIndex(A, N); }} // This code is contributed by maddler.",
"e": 31698,
"s": 30231,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach; // Function to find the count of integers // such that A[i]%A[j] = 0 or A[j]%A[i] = 0 // for each index of the array A[] function max_element(A, N) { let MAX = Number.MIN_VALUE; for (let i = 0; i < A.length; i++) { if (A[i] > MAX) { MAX = A[i]; } } return MAX; } function countIndex(A, N) { // Stores the maximum integer in A[] let MAX = max_element(A, A + N); // Stores the frequency of each // element in the array A[] let freq = new Array(MAX + 1).fill(0); for (let i = 0; i < N; i++) freq[A[i]]++; // Stores the valid integers in A[] // for all integers from 1 to MAX let res = new Array(MAX + 1).fill(0); for (let i = 1; i <= MAX; ++i) { for (let j = i; j <= MAX; j += i) { // Case where P = Q if (i == j) { // Subtract 1 because P & Q // cannot have same index res[i] += (freq[j] - 1); } else { // Case 1 res[i] += freq[j]; // Case 2 res[j] += freq[i]; } } } // Loop to print answer for // each index of array A[] for (let i = 0; i < N; i++) { document.write(res[A[i]] + \" \"); } } // Driver Code let A = [2, 3, 4, 5, 6]; let N = A.length; // Function Call countIndex(A, N); // This code is contributed by Potta Lokesh </script>",
"e": 33571,
"s": 31698,
"text": null
},
{
"code": null,
"e": 33582,
"s": 33571,
"text": "2 1 1 0 2 "
},
{
"code": null,
"e": 33694,
"s": 33582,
"text": "Time Complexity: O(N*log N)Auxiliary Space: O(MAX) where MAX represents the maximum integer in the given array."
},
{
"code": null,
"e": 33708,
"s": 33694,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 33721,
"s": 33708,
"text": "princi singh"
},
{
"code": null,
"e": 33729,
"s": 33721,
"text": "maddler"
},
{
"code": null,
"e": 33746,
"s": 33729,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 33759,
"s": 33746,
"text": "singghakshay"
},
{
"code": null,
"e": 33776,
"s": 33759,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 33785,
"s": 33776,
"text": "divisors"
},
{
"code": null,
"e": 33791,
"s": 33785,
"text": "sieve"
},
{
"code": null,
"e": 33798,
"s": 33791,
"text": "Arrays"
},
{
"code": null,
"e": 33811,
"s": 33798,
"text": "Mathematical"
},
{
"code": null,
"e": 33818,
"s": 33811,
"text": "Arrays"
},
{
"code": null,
"e": 33831,
"s": 33818,
"text": "Mathematical"
},
{
"code": null,
"e": 33837,
"s": 33831,
"text": "sieve"
},
{
"code": null,
"e": 33935,
"s": 33837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33960,
"s": 33935,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33980,
"s": 33960,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 34018,
"s": 33980,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34043,
"s": 34018,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 34092,
"s": 34043,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34122,
"s": 34092,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34182,
"s": 34122,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34197,
"s": 34182,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34240,
"s": 34197,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to Build a Scalable Big Data Analytics Pipeline | by Nam Nguyen | Towards Data Science
|
Data is a vital element of todayβs innovative enterprise. Data-driven decision making allows corporations to adapt to an unpredictable world. The ability to report on the data is the spine of business analytics. With the unprecedented growth of data in the 21st century, big data is no longer a buzzword but a reality that companies have to face.
Thou shalt love thy data as thyself
Data expands exponentially and it requires at all times the scalability of data systems. Building a big data pipeline at scale along with the integration into existing analytics ecosystems would become a big challenge for those who are not familiar with either.
To build a scalable big data analytics pipeline, you must first identify three critical factors:
Input data
Either they are time-series or non-time-series, you must know the nature of your pipelineβs input data. It would determine under what format you store your data, what you do when data is missing, and what technology you use in the rest of the pipeline.
Output data
When building an analytics pipeline, you need to care about the end-users. Data Analysts use your pipeline to build a reporting dashboard or visualization. The output data needs to be accessible and manipulable given end-usersβ possible lack of strong technical expertise in data engineering. Nowadays, famous analytics engines ease the integration between big data ecosystems and analytics warehouses.
How much data can the pipeline ingest?
The scalability of your data system can decide the long-term viability of the business. Thereβs nothing much alike between handling 100 GB and 1 TB a day. The hardware and software infrastructure must keep up with a sudden change in data volume. You donβt want to overload your data system due to the organic growth of your business. Scale your data pipeline for the best!
Data collection is the first and foremost module of a data pipeline where you have to assess the origin of your data. Are they coming from another data source or top-level applications? Will the data be structured or unstructured? Do you need to perform any data cleaning? We might think of big data as a chaotic volume of data, but actually, most big data are structured. Unstructured data will require additional techniques to build a data pipeline upon it.
Your pipelineβs architecture will vary in the method you choose to collect the data: either in batch or via streaming service. A batch processing pipeline demands an efficient storage system for I/O operations whilst a streaming processing one prefers a fault-intolerant transmission protocol.
When it comes to structured data, either they are texts, numbers, images, to feed them into the pipeline, they must go through a requisite process: data serialization. Data serialization is the process of converting structured data to a format that allows the sharing or storage of the data in a form that allows the recovery of its original structure.
Data serialization leads to a homogeneous data structure across the pipeline, thus keeping the consistency for all the data processing modules. XML, CSV, YAML, JSON are some of the most popular formats in data serialization. Serialized data is more optimized in terms of storage and transmission. Transferring data from one system to another might encounter incompatible problems, so a bit-wise communication ensures there is no information loss.
JSON is quite handy to handle both flat and nested data structures across the Internet. It offers a human-readable format and high integrity with JVM systems. However, in big data processing, the use of JSON is less favored than others due to its unoptimized storage and lack of structure validation.
Protocol buffers (or protobuf) is Googleβs internal mechanism for serializing structured data. With protobuf, you can define a generic schema and then perform the read/write operations with your favorite programming language. Think about a language-neural format like XML, but faster and smaller. Apart from the non-human-readable disadvantage, protobuf performs up to 6 times faster than JSON.
Key takeaways:- Storage is essential for batch processing while the transmission is critical for streaming service- Serialization maintains a stable communication transferring between systems- Use protobuf to serialize data for a better performance
Suppose you have the data collection modules up and running, where will you store all those data? It depends on many things: hardware resources, data management expertise, maintenance budget, etc. You need to make up your mind before deciding where to spend your money because this is a long-term play.
Data is the new oil, so itβs best to keep the oil in your backyard
If you have big money, the best thing is setting up your own data infrastructure. Data is the new oil, so itβs best to keep the oil in your backyard. Hire the best hardware engineers, assemble a proper data center, and build your pipeline upon it. Hadoop File System (HDFS) has always been the number one choice for in-house data architecture. It offers a tightly-integrated ecosystem with all tools and platforms available for data storage and ETL. It requires a minimum effort to set up a viable Hadoop stack. Its power lies in the capacity of horizontal scaling, which means bundling commodity hardware side by side to maximize performance and minimize costs.
You can even go the extra mile by optimizing the storage format. Storing files under .txt or .csv format might not be the brightest idea under HDFS. Apache Parquet is a columnar format available to any project in Hadoop, and it is recommended by every single data engineer out there. Being a column-based storage format, Parquet offers better compression and therefore optimized I/O operations. Its only drawback is the constraint in schema modification, for example, adding or removing a column takes more effort with parquet.
Coming from a SQL background, you can also set up a more accessible query system. The Apache Hive data warehouse software facilitates reading, writing, and managing large datasets residing in distributed storage using SQL. Hive provides a SQL-like queries language (HiveQL) to execute queries directly on HDFS. Even though it does not follow all the SQL standards, HiveQL still eases the querying process for those who donβt speak Hadoop. Another common query engine is Presto which was largely developed by Facebook engineers.
Again, if you donβt have enough resources to build your own data warehouse, you can outsource the whole system to a cloud-based platform. Many famous tech companies offer all-in-one big data architectures such as Google Big Query, Amazon AWS, Microsoft Azure. By out-sourcing, you donβt have to bother setting up or maintaining the ecosystem, but that brings the risks of not being able to control your pipeline. There is a compromise between high-cost, low-maintenance, and low-cost, high-maintenance. Nevertheless, you can place your bet on the expertise of tech giants in managing your pipeline.
Key takeaways:- If you have big money, go for DIY data architecture, if not, our-sourcing is your answer- Use parquet to store files in Hadoop ecosystem- Setup a query system upon Hadoop for easy access
Hadoop ecosystem and its alternatives are favorable for a big data storage system, but they donβt fit to be an analytics engine. They arenβt built to execute fast queries. For analytics purposes, we execute frequently ad hoc queries thus demand a system that returns quick results. Subordinate storage needs to be built on an analytics engine.
Vertica is a database management system designed for analytics at scale and fast query performance. It stores data in a columnar format and creates projections to distribute data across its nodes for high-speed queries. Vertica is widely used by many tech companies thanks to its reputation for providing a robust analytics engine and efficient querying system. Vertica can play the role of a database for numerous data-related external applications thanks to its easy integration using Java, Scala, Python, C++.
However, Vertica shows some disadvantages of working with real-time data or high-latency analytics. Its constraints on changing schemas or modifying projections limit its use on data with rapid transformation. Druid is an open-source analytics database specifically designed for Online Analytics Processing (OLAP). Time-series data requires an optimized storage mechanism and fast aggregators. It contains mostly timestamps and metrics. Druid stores metrics as columns and partitions data based on indexes and metrics altogether for quick access, therefore, provides agile aggregation operations.
Key takeaways:- Vertica is great for low-latency analytics but requires much expertise to scale- Druid is built for time series data and provide a fast access system- Choose analytics database with maximum integration to visualization tools
After finishing data collection, storage, and visualization integration, you might want to plug and play. But thereβs one last thing is what to do in case of incidents. Where do you turn to when your pipeline crashes for no reason? Thatβs the purpose of the whole monitoring process. It helps you to track, log, and observe your systemβs health and performance. Some tools even allow you to debug on the fly. With that said, a proper monitoring system is a must if you want to build a data pipeline that lasts. Here we distinguish between two kinds: IT monitoring and data monitoring.
IT monitoring is necessary for any software development. It shows various system-related metrics such as CPU, disk usage, resource consumption, memory allocated, etc. You can look at an IT monitoring and say whether you can double, or triple the pipelineβs capacity. With pre-optimized ecosystems like Hadoop or Vertica, we donβt need to worry much about IT performance. You can choose any basic IT monitoring tools like Grafana or Datadog to set up a simple dashboard keeping track of your metrics.
Data monitoring is as crucial as other modules in your big data analytics pipeline. It detects data-related issues like latency, missing data, inconsistent dataset. The quality of your data pipeline reflects the integrity of data circulating within your system. These metrics ensure a minimum or zero data loss transferring from one place to another without affecting the business outcomes. We cannot name all the metrics logged by data monitoring tools because each data pipeline has its specific needs hence specific tracking. If you are building a time-series data pipeline, focus on latency-sensitive metrics. In case your data comes in batches, make sure you track properly the transmission processes. Some data monitoring tools can help you to build a straightforward data monitoring dashboard, but to suit your particular uses, itβs best to build one yourself.
Key takeaway:- Monitoring tools are indispensable in a data pipeline, but not all metrics are equally important- Data pipeline quality means the integrity of your data
We spend quite some time talking about a basic end-to-end big data analytics pipeline, and I hope you have acquired some useful knowledge. There is no all-in-one formula for building a pipeline as such, but you can base on the fundamental blueprint to craft your own.
|
[
{
"code": null,
"e": 519,
"s": 172,
"text": "Data is a vital element of todayβs innovative enterprise. Data-driven decision making allows corporations to adapt to an unpredictable world. The ability to report on the data is the spine of business analytics. With the unprecedented growth of data in the 21st century, big data is no longer a buzzword but a reality that companies have to face."
},
{
"code": null,
"e": 555,
"s": 519,
"text": "Thou shalt love thy data as thyself"
},
{
"code": null,
"e": 817,
"s": 555,
"text": "Data expands exponentially and it requires at all times the scalability of data systems. Building a big data pipeline at scale along with the integration into existing analytics ecosystems would become a big challenge for those who are not familiar with either."
},
{
"code": null,
"e": 914,
"s": 817,
"text": "To build a scalable big data analytics pipeline, you must first identify three critical factors:"
},
{
"code": null,
"e": 925,
"s": 914,
"text": "Input data"
},
{
"code": null,
"e": 1178,
"s": 925,
"text": "Either they are time-series or non-time-series, you must know the nature of your pipelineβs input data. It would determine under what format you store your data, what you do when data is missing, and what technology you use in the rest of the pipeline."
},
{
"code": null,
"e": 1190,
"s": 1178,
"text": "Output data"
},
{
"code": null,
"e": 1593,
"s": 1190,
"text": "When building an analytics pipeline, you need to care about the end-users. Data Analysts use your pipeline to build a reporting dashboard or visualization. The output data needs to be accessible and manipulable given end-usersβ possible lack of strong technical expertise in data engineering. Nowadays, famous analytics engines ease the integration between big data ecosystems and analytics warehouses."
},
{
"code": null,
"e": 1632,
"s": 1593,
"text": "How much data can the pipeline ingest?"
},
{
"code": null,
"e": 2005,
"s": 1632,
"text": "The scalability of your data system can decide the long-term viability of the business. Thereβs nothing much alike between handling 100 GB and 1 TB a day. The hardware and software infrastructure must keep up with a sudden change in data volume. You donβt want to overload your data system due to the organic growth of your business. Scale your data pipeline for the best!"
},
{
"code": null,
"e": 2465,
"s": 2005,
"text": "Data collection is the first and foremost module of a data pipeline where you have to assess the origin of your data. Are they coming from another data source or top-level applications? Will the data be structured or unstructured? Do you need to perform any data cleaning? We might think of big data as a chaotic volume of data, but actually, most big data are structured. Unstructured data will require additional techniques to build a data pipeline upon it."
},
{
"code": null,
"e": 2759,
"s": 2465,
"text": "Your pipelineβs architecture will vary in the method you choose to collect the data: either in batch or via streaming service. A batch processing pipeline demands an efficient storage system for I/O operations whilst a streaming processing one prefers a fault-intolerant transmission protocol."
},
{
"code": null,
"e": 3112,
"s": 2759,
"text": "When it comes to structured data, either they are texts, numbers, images, to feed them into the pipeline, they must go through a requisite process: data serialization. Data serialization is the process of converting structured data to a format that allows the sharing or storage of the data in a form that allows the recovery of its original structure."
},
{
"code": null,
"e": 3559,
"s": 3112,
"text": "Data serialization leads to a homogeneous data structure across the pipeline, thus keeping the consistency for all the data processing modules. XML, CSV, YAML, JSON are some of the most popular formats in data serialization. Serialized data is more optimized in terms of storage and transmission. Transferring data from one system to another might encounter incompatible problems, so a bit-wise communication ensures there is no information loss."
},
{
"code": null,
"e": 3860,
"s": 3559,
"text": "JSON is quite handy to handle both flat and nested data structures across the Internet. It offers a human-readable format and high integrity with JVM systems. However, in big data processing, the use of JSON is less favored than others due to its unoptimized storage and lack of structure validation."
},
{
"code": null,
"e": 4255,
"s": 3860,
"text": "Protocol buffers (or protobuf) is Googleβs internal mechanism for serializing structured data. With protobuf, you can define a generic schema and then perform the read/write operations with your favorite programming language. Think about a language-neural format like XML, but faster and smaller. Apart from the non-human-readable disadvantage, protobuf performs up to 6 times faster than JSON."
},
{
"code": null,
"e": 4504,
"s": 4255,
"text": "Key takeaways:- Storage is essential for batch processing while the transmission is critical for streaming service- Serialization maintains a stable communication transferring between systems- Use protobuf to serialize data for a better performance"
},
{
"code": null,
"e": 4807,
"s": 4504,
"text": "Suppose you have the data collection modules up and running, where will you store all those data? It depends on many things: hardware resources, data management expertise, maintenance budget, etc. You need to make up your mind before deciding where to spend your money because this is a long-term play."
},
{
"code": null,
"e": 4874,
"s": 4807,
"text": "Data is the new oil, so itβs best to keep the oil in your backyard"
},
{
"code": null,
"e": 5537,
"s": 4874,
"text": "If you have big money, the best thing is setting up your own data infrastructure. Data is the new oil, so itβs best to keep the oil in your backyard. Hire the best hardware engineers, assemble a proper data center, and build your pipeline upon it. Hadoop File System (HDFS) has always been the number one choice for in-house data architecture. It offers a tightly-integrated ecosystem with all tools and platforms available for data storage and ETL. It requires a minimum effort to set up a viable Hadoop stack. Its power lies in the capacity of horizontal scaling, which means bundling commodity hardware side by side to maximize performance and minimize costs."
},
{
"code": null,
"e": 6065,
"s": 5537,
"text": "You can even go the extra mile by optimizing the storage format. Storing files under .txt or .csv format might not be the brightest idea under HDFS. Apache Parquet is a columnar format available to any project in Hadoop, and it is recommended by every single data engineer out there. Being a column-based storage format, Parquet offers better compression and therefore optimized I/O operations. Its only drawback is the constraint in schema modification, for example, adding or removing a column takes more effort with parquet."
},
{
"code": null,
"e": 6593,
"s": 6065,
"text": "Coming from a SQL background, you can also set up a more accessible query system. The Apache Hive data warehouse software facilitates reading, writing, and managing large datasets residing in distributed storage using SQL. Hive provides a SQL-like queries language (HiveQL) to execute queries directly on HDFS. Even though it does not follow all the SQL standards, HiveQL still eases the querying process for those who donβt speak Hadoop. Another common query engine is Presto which was largely developed by Facebook engineers."
},
{
"code": null,
"e": 7192,
"s": 6593,
"text": "Again, if you donβt have enough resources to build your own data warehouse, you can outsource the whole system to a cloud-based platform. Many famous tech companies offer all-in-one big data architectures such as Google Big Query, Amazon AWS, Microsoft Azure. By out-sourcing, you donβt have to bother setting up or maintaining the ecosystem, but that brings the risks of not being able to control your pipeline. There is a compromise between high-cost, low-maintenance, and low-cost, high-maintenance. Nevertheless, you can place your bet on the expertise of tech giants in managing your pipeline."
},
{
"code": null,
"e": 7395,
"s": 7192,
"text": "Key takeaways:- If you have big money, go for DIY data architecture, if not, our-sourcing is your answer- Use parquet to store files in Hadoop ecosystem- Setup a query system upon Hadoop for easy access"
},
{
"code": null,
"e": 7739,
"s": 7395,
"text": "Hadoop ecosystem and its alternatives are favorable for a big data storage system, but they donβt fit to be an analytics engine. They arenβt built to execute fast queries. For analytics purposes, we execute frequently ad hoc queries thus demand a system that returns quick results. Subordinate storage needs to be built on an analytics engine."
},
{
"code": null,
"e": 8252,
"s": 7739,
"text": "Vertica is a database management system designed for analytics at scale and fast query performance. It stores data in a columnar format and creates projections to distribute data across its nodes for high-speed queries. Vertica is widely used by many tech companies thanks to its reputation for providing a robust analytics engine and efficient querying system. Vertica can play the role of a database for numerous data-related external applications thanks to its easy integration using Java, Scala, Python, C++."
},
{
"code": null,
"e": 8849,
"s": 8252,
"text": "However, Vertica shows some disadvantages of working with real-time data or high-latency analytics. Its constraints on changing schemas or modifying projections limit its use on data with rapid transformation. Druid is an open-source analytics database specifically designed for Online Analytics Processing (OLAP). Time-series data requires an optimized storage mechanism and fast aggregators. It contains mostly timestamps and metrics. Druid stores metrics as columns and partitions data based on indexes and metrics altogether for quick access, therefore, provides agile aggregation operations."
},
{
"code": null,
"e": 9090,
"s": 8849,
"text": "Key takeaways:- Vertica is great for low-latency analytics but requires much expertise to scale- Druid is built for time series data and provide a fast access system- Choose analytics database with maximum integration to visualization tools"
},
{
"code": null,
"e": 9675,
"s": 9090,
"text": "After finishing data collection, storage, and visualization integration, you might want to plug and play. But thereβs one last thing is what to do in case of incidents. Where do you turn to when your pipeline crashes for no reason? Thatβs the purpose of the whole monitoring process. It helps you to track, log, and observe your systemβs health and performance. Some tools even allow you to debug on the fly. With that said, a proper monitoring system is a must if you want to build a data pipeline that lasts. Here we distinguish between two kinds: IT monitoring and data monitoring."
},
{
"code": null,
"e": 10175,
"s": 9675,
"text": "IT monitoring is necessary for any software development. It shows various system-related metrics such as CPU, disk usage, resource consumption, memory allocated, etc. You can look at an IT monitoring and say whether you can double, or triple the pipelineβs capacity. With pre-optimized ecosystems like Hadoop or Vertica, we donβt need to worry much about IT performance. You can choose any basic IT monitoring tools like Grafana or Datadog to set up a simple dashboard keeping track of your metrics."
},
{
"code": null,
"e": 11043,
"s": 10175,
"text": "Data monitoring is as crucial as other modules in your big data analytics pipeline. It detects data-related issues like latency, missing data, inconsistent dataset. The quality of your data pipeline reflects the integrity of data circulating within your system. These metrics ensure a minimum or zero data loss transferring from one place to another without affecting the business outcomes. We cannot name all the metrics logged by data monitoring tools because each data pipeline has its specific needs hence specific tracking. If you are building a time-series data pipeline, focus on latency-sensitive metrics. In case your data comes in batches, make sure you track properly the transmission processes. Some data monitoring tools can help you to build a straightforward data monitoring dashboard, but to suit your particular uses, itβs best to build one yourself."
},
{
"code": null,
"e": 11211,
"s": 11043,
"text": "Key takeaway:- Monitoring tools are indispensable in a data pipeline, but not all metrics are equally important- Data pipeline quality means the integrity of your data"
}
] |
How to create a high resolution timer with C++ and Linux?
|
To create high resolution timer we can use the chrono library. This library has high resolution clock. This can count in nanoseconds.
In this program we will see the execution time in nanoseconds. We will take the time value at first, then another time value at the last, then find the difference to get elapsed time. Here we are using blank loop to pause the effect for sometimes.
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
main(){
auto start_time = Clock::now();
for(int i = 0; i<200000000; i++) {
//create one empty loop ;
}
auto end_time = Clock::now();
std::cout << "Time difference:"
<< std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count() << " nanoseconds" << std::endl;
}
Time difference: 536395307 nanoseconds
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "To create high resolution timer we can use the chrono library. This library has high resolution clock. This can count in nanoseconds."
},
{
"code": null,
"e": 1444,
"s": 1196,
"text": "In this program we will see the execution time in nanoseconds. We will take the time value at first, then another time value at the last, then find the difference to get elapsed time. Here we are using blank loop to pause the effect for sometimes."
},
{
"code": null,
"e": 1845,
"s": 1444,
"text": "#include <iostream>\n#include <chrono>\ntypedef std::chrono::high_resolution_clock Clock;\nmain(){\n auto start_time = Clock::now();\n for(int i = 0; i<200000000; i++) {\n //create one empty loop ;\n }\n auto end_time = Clock::now();\n std::cout << \"Time difference:\"\n << std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count() << \" nanoseconds\" << std::endl;\n}"
},
{
"code": null,
"e": 1884,
"s": 1845,
"text": "Time difference: 536395307 nanoseconds"
}
] |
p5.js | Mouse | mouseDragged() Function - GeeksforGeeks
|
22 Apr, 2019
The mouseDragged() function in p5.js is used to check the mouse drags (mouse moves and mouse button pressed). It is invoked each time when the mouse drags. If mouseDragged() function is not defined, then touchMoved() function will be used instead of mouseDragged() function.
Syntax:
mouseDragged(Event)
Below programs illustrate the mouseDragged() function in p5.js:
Example 1: This example uses mouseDragged() function to change the background color.
function setup() { // Create Canvas createCanvas(500, 500);} let value = 0; function draw() { // Set background color background(200); // Set filled color fill(value); // Create rectangle rect(25, 25, 460, 440); // Set text color fill('lightgreen'); // Set font size textSize(15); // Display result text('Drag Mouse Across the page to change its value.', windowHeight/6, windowWidth/4);} function mouseDragged() { value = value + 5; if (value > 255) { value = 0; }}
Output:
Example 2: This example uses mouseDragged() function to change the mouse cursor circle color.
let value; function setup() { // Create Canvas createCanvas(500, 500);} function draw() { // Set background color background(200); // Set filled color fill('green'); // Set text and text size textSize(25); text('Drag mouse to change color', 30, 30); // Fill color according to // mouseMoved() function fill(value, 255-value, 255-value); // Draw ellipse ellipse(mouseX, mouseY, 115, 115);} function mouseDragged() { value = mouseX%255;}
Output:
Reference: https://p5js.org/reference/#/p5/mouseDragged
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 43301,
"s": 43273,
"text": "\n22 Apr, 2019"
},
{
"code": null,
"e": 43576,
"s": 43301,
"text": "The mouseDragged() function in p5.js is used to check the mouse drags (mouse moves and mouse button pressed). It is invoked each time when the mouse drags. If mouseDragged() function is not defined, then touchMoved() function will be used instead of mouseDragged() function."
},
{
"code": null,
"e": 43584,
"s": 43576,
"text": "Syntax:"
},
{
"code": null,
"e": 43604,
"s": 43584,
"text": "mouseDragged(Event)"
},
{
"code": null,
"e": 43668,
"s": 43604,
"text": "Below programs illustrate the mouseDragged() function in p5.js:"
},
{
"code": null,
"e": 43753,
"s": 43668,
"text": "Example 1: This example uses mouseDragged() function to change the background color."
},
{
"code": "function setup() { // Create Canvas createCanvas(500, 500);} let value = 0; function draw() { // Set background color background(200); // Set filled color fill(value); // Create rectangle rect(25, 25, 460, 440); // Set text color fill('lightgreen'); // Set font size textSize(15); // Display result text('Drag Mouse Across the page to change its value.', windowHeight/6, windowWidth/4);} function mouseDragged() { value = value + 5; if (value > 255) { value = 0; }}",
"e": 44332,
"s": 43753,
"text": null
},
{
"code": null,
"e": 44340,
"s": 44332,
"text": "Output:"
},
{
"code": null,
"e": 44434,
"s": 44340,
"text": "Example 2: This example uses mouseDragged() function to change the mouse cursor circle color."
},
{
"code": "let value; function setup() { // Create Canvas createCanvas(500, 500);} function draw() { // Set background color background(200); // Set filled color fill('green'); // Set text and text size textSize(25); text('Drag mouse to change color', 30, 30); // Fill color according to // mouseMoved() function fill(value, 255-value, 255-value); // Draw ellipse ellipse(mouseX, mouseY, 115, 115);} function mouseDragged() { value = mouseX%255;}",
"e": 44964,
"s": 44434,
"text": null
},
{
"code": null,
"e": 44972,
"s": 44964,
"text": "Output:"
},
{
"code": null,
"e": 45028,
"s": 44972,
"text": "Reference: https://p5js.org/reference/#/p5/mouseDragged"
},
{
"code": null,
"e": 45045,
"s": 45028,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 45056,
"s": 45045,
"text": "JavaScript"
},
{
"code": null,
"e": 45073,
"s": 45056,
"text": "Web Technologies"
},
{
"code": null,
"e": 45171,
"s": 45073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45180,
"s": 45171,
"text": "Comments"
},
{
"code": null,
"e": 45193,
"s": 45180,
"text": "Old Comments"
},
{
"code": null,
"e": 45254,
"s": 45193,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 45299,
"s": 45254,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 45371,
"s": 45299,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 45440,
"s": 45371,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 45467,
"s": 45440,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 45523,
"s": 45467,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 45556,
"s": 45523,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 45618,
"s": 45556,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 45661,
"s": 45618,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
GeoPandas: A Practical Guide. Mapping earthquakes from 1965 to 2016 | by Soner YΔ±ldΔ±rΔ±m | Towards Data Science
|
GeoPandas is a Python library designed to work with geospatial data. It makes it fairly easy to create visualizations based on geographical locations.
In this post, we will visualize the significant earthquakes that occurred between 1965 and 2016. The dataset is available on Kaggle.
GeoPandas has two main data structures which are GeoDataFrame and GeoSeries. They can be considered as subclasses of the Series and DataFrame of Pandas.
Letβs start by installing and importing GeoPandas along with the other libraries we will use.
pip install geopandasimport geopandasimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline
A GeoDataFrame can be created by modifying a pandas DataFrame. Thus, we will first read the dataset into a pandas DataFrame.
eq = pd.read_csv("/content/earthquakes.csv")eq.shape(23412, 21)
The dataset contains over 23412 events most of which are earthquakes. We will filter the DataFrame so that it only contains earthquake data.
eq = eq[eq['Type'] == 'Earthquake']
There are also some redundant columns for our analysis so I will also filter out those columns.
eq = eq[['Date', 'Time', 'Latitude', 'Longitude', 'Depth', 'Magnitude']]eq.head()
We have a DataFrame that contains the data, location, depth, and magnitude of over 20 thousand earthquakes. In order to use GeoPandas, we need to convert this pandas DataFrame to a GeoDataFrame.
We will use the GeoDataFrame function as follows:
gdf = geopandas.GeoDataFrame(eq, geometry=geopandas.points_from_xy(eq.Longitude, eq.Latitude))gdf.head()
The difference between the GeoDataFrame and pandas DataFrame is a GeoSeries called βgeometryβ. When a spatial method is applied on a GeoDataFrame, it will act on the geometry column.
Think of the βgeometryβ column as a re-formatted version of the latitude and longitude values.
We now have the earthquake data stored in a GeoDataFrame. The next step is to draw a map of the world which can easily be done using the βworldβ GeoDataFrame.
world = geopandas\.read_file(geopandas.datasets.get_path('naturalearth_lowres'))world.columnsIndex(['pop_est', 'continent', 'name', 'iso_a3', 'gdp_md_est', 'geometry'], dtype='object')
It contains basic information about countries and their locations. Letβs draw an empty world map now.
world.plot(color='white', edgecolor='black', figsize=(12,8))
In order to draw the earthquake map, we will create an Axes object of the world map and then draw the earthquakes based on the βgeometryβ column.
ax = world.plot(color='white', edgecolor='black', figsize=(16,12))gdf.plot(ax=ax, color='red', markersize=2)plt.show()
This map contains all the significant earthquakes that occurred between 1965 and 2016. If you do a quick google search of earthquake fault lines, you will see that they overlap with the map above.
The markersize parameter adjusts the size of the markers that locate the earthquakes. You can also pass a column name and the size of the marker will be adjusted based on the value in that column. I thought about using the magnitude to resize the markers but the differences did not seem to be distinguishable.
We can also draw a map of earthquakes in a specific location. For instance, there have been lots of earthquakes in Japan. Iβm not sure but it may even be the country that had the most earthquakes in the world.
One way to focus on a specific country is to filter the earthquakes based on latitude and longitude values. The latitude and longitude values for Japan are given as:
latitude = 36.204824
longitude = 138.252924
We can create a range around these values to be used as filtering ranges.
japan_lat = 36.204824japan_long = 138.252924japan_eq = eq[(eq.Latitude > 30) & (eq.Latitude < 42) & (eq.Longitude > 130) & (eq.Longitude < 145)]japan_eq = japan_eq.reset_index(drop=True)
I adjusted the range so that the location occupies the area of Japan. Please note that these values are not the borders of Japan.
Letβs create a GeoDataFrame that only contains the earthquakes that occurred in or around Japan.
japan_gdf = geopandas.GeoDataFrame(japan_eq, geometry=geopandas.points_from_xy(japan_eq.Longitude, japan_eq.Latitude))
We will plot the map of Japan and mark the earthquakes in japan_gdf.
ax = world[world.name == 'Japan'].plot(color='white', edgecolor='black', figsize=(12,8))japan_gdf.plot(ax=ax, color='blue', markersize=japan_gdf['Magnitude']*4)plt.title("Earthquakes, 1965-2016", fontsize=16)plt.show()
In order to filter the map, we used the βnameβ column of the world GeoDataFrame.
Here is the resulting map of Japan's earthquakes.
Lots of earthquakes had occurred in Japan. The density of the markers indicates that most of them are around the east coast.
GeoPandas is a functional library that expedites the process of creating geospatial visualizations. It provides many functions and methods to enrich the maps.
If you are working or plan to work with geospatial data, I highly recommend checking the documentation of GeoPandas. They also provide examples that will help to adapt the functions and methods more easily.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 322,
"s": 171,
"text": "GeoPandas is a Python library designed to work with geospatial data. It makes it fairly easy to create visualizations based on geographical locations."
},
{
"code": null,
"e": 455,
"s": 322,
"text": "In this post, we will visualize the significant earthquakes that occurred between 1965 and 2016. The dataset is available on Kaggle."
},
{
"code": null,
"e": 608,
"s": 455,
"text": "GeoPandas has two main data structures which are GeoDataFrame and GeoSeries. They can be considered as subclasses of the Series and DataFrame of Pandas."
},
{
"code": null,
"e": 702,
"s": 608,
"text": "Letβs start by installing and importing GeoPandas along with the other libraries we will use."
},
{
"code": null,
"e": 808,
"s": 702,
"text": "pip install geopandasimport geopandasimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 933,
"s": 808,
"text": "A GeoDataFrame can be created by modifying a pandas DataFrame. Thus, we will first read the dataset into a pandas DataFrame."
},
{
"code": null,
"e": 997,
"s": 933,
"text": "eq = pd.read_csv(\"/content/earthquakes.csv\")eq.shape(23412, 21)"
},
{
"code": null,
"e": 1138,
"s": 997,
"text": "The dataset contains over 23412 events most of which are earthquakes. We will filter the DataFrame so that it only contains earthquake data."
},
{
"code": null,
"e": 1174,
"s": 1138,
"text": "eq = eq[eq['Type'] == 'Earthquake']"
},
{
"code": null,
"e": 1270,
"s": 1174,
"text": "There are also some redundant columns for our analysis so I will also filter out those columns."
},
{
"code": null,
"e": 1352,
"s": 1270,
"text": "eq = eq[['Date', 'Time', 'Latitude', 'Longitude', 'Depth', 'Magnitude']]eq.head()"
},
{
"code": null,
"e": 1547,
"s": 1352,
"text": "We have a DataFrame that contains the data, location, depth, and magnitude of over 20 thousand earthquakes. In order to use GeoPandas, we need to convert this pandas DataFrame to a GeoDataFrame."
},
{
"code": null,
"e": 1597,
"s": 1547,
"text": "We will use the GeoDataFrame function as follows:"
},
{
"code": null,
"e": 1702,
"s": 1597,
"text": "gdf = geopandas.GeoDataFrame(eq, geometry=geopandas.points_from_xy(eq.Longitude, eq.Latitude))gdf.head()"
},
{
"code": null,
"e": 1885,
"s": 1702,
"text": "The difference between the GeoDataFrame and pandas DataFrame is a GeoSeries called βgeometryβ. When a spatial method is applied on a GeoDataFrame, it will act on the geometry column."
},
{
"code": null,
"e": 1980,
"s": 1885,
"text": "Think of the βgeometryβ column as a re-formatted version of the latitude and longitude values."
},
{
"code": null,
"e": 2139,
"s": 1980,
"text": "We now have the earthquake data stored in a GeoDataFrame. The next step is to draw a map of the world which can easily be done using the βworldβ GeoDataFrame."
},
{
"code": null,
"e": 2324,
"s": 2139,
"text": "world = geopandas\\.read_file(geopandas.datasets.get_path('naturalearth_lowres'))world.columnsIndex(['pop_est', 'continent', 'name', 'iso_a3', 'gdp_md_est', 'geometry'], dtype='object')"
},
{
"code": null,
"e": 2426,
"s": 2324,
"text": "It contains basic information about countries and their locations. Letβs draw an empty world map now."
},
{
"code": null,
"e": 2487,
"s": 2426,
"text": "world.plot(color='white', edgecolor='black', figsize=(12,8))"
},
{
"code": null,
"e": 2633,
"s": 2487,
"text": "In order to draw the earthquake map, we will create an Axes object of the world map and then draw the earthquakes based on the βgeometryβ column."
},
{
"code": null,
"e": 2752,
"s": 2633,
"text": "ax = world.plot(color='white', edgecolor='black', figsize=(16,12))gdf.plot(ax=ax, color='red', markersize=2)plt.show()"
},
{
"code": null,
"e": 2949,
"s": 2752,
"text": "This map contains all the significant earthquakes that occurred between 1965 and 2016. If you do a quick google search of earthquake fault lines, you will see that they overlap with the map above."
},
{
"code": null,
"e": 3260,
"s": 2949,
"text": "The markersize parameter adjusts the size of the markers that locate the earthquakes. You can also pass a column name and the size of the marker will be adjusted based on the value in that column. I thought about using the magnitude to resize the markers but the differences did not seem to be distinguishable."
},
{
"code": null,
"e": 3470,
"s": 3260,
"text": "We can also draw a map of earthquakes in a specific location. For instance, there have been lots of earthquakes in Japan. Iβm not sure but it may even be the country that had the most earthquakes in the world."
},
{
"code": null,
"e": 3636,
"s": 3470,
"text": "One way to focus on a specific country is to filter the earthquakes based on latitude and longitude values. The latitude and longitude values for Japan are given as:"
},
{
"code": null,
"e": 3657,
"s": 3636,
"text": "latitude = 36.204824"
},
{
"code": null,
"e": 3680,
"s": 3657,
"text": "longitude = 138.252924"
},
{
"code": null,
"e": 3754,
"s": 3680,
"text": "We can create a range around these values to be used as filtering ranges."
},
{
"code": null,
"e": 3941,
"s": 3754,
"text": "japan_lat = 36.204824japan_long = 138.252924japan_eq = eq[(eq.Latitude > 30) & (eq.Latitude < 42) & (eq.Longitude > 130) & (eq.Longitude < 145)]japan_eq = japan_eq.reset_index(drop=True)"
},
{
"code": null,
"e": 4071,
"s": 3941,
"text": "I adjusted the range so that the location occupies the area of Japan. Please note that these values are not the borders of Japan."
},
{
"code": null,
"e": 4168,
"s": 4071,
"text": "Letβs create a GeoDataFrame that only contains the earthquakes that occurred in or around Japan."
},
{
"code": null,
"e": 4287,
"s": 4168,
"text": "japan_gdf = geopandas.GeoDataFrame(japan_eq, geometry=geopandas.points_from_xy(japan_eq.Longitude, japan_eq.Latitude))"
},
{
"code": null,
"e": 4356,
"s": 4287,
"text": "We will plot the map of Japan and mark the earthquakes in japan_gdf."
},
{
"code": null,
"e": 4575,
"s": 4356,
"text": "ax = world[world.name == 'Japan'].plot(color='white', edgecolor='black', figsize=(12,8))japan_gdf.plot(ax=ax, color='blue', markersize=japan_gdf['Magnitude']*4)plt.title(\"Earthquakes, 1965-2016\", fontsize=16)plt.show()"
},
{
"code": null,
"e": 4656,
"s": 4575,
"text": "In order to filter the map, we used the βnameβ column of the world GeoDataFrame."
},
{
"code": null,
"e": 4706,
"s": 4656,
"text": "Here is the resulting map of Japan's earthquakes."
},
{
"code": null,
"e": 4831,
"s": 4706,
"text": "Lots of earthquakes had occurred in Japan. The density of the markers indicates that most of them are around the east coast."
},
{
"code": null,
"e": 4990,
"s": 4831,
"text": "GeoPandas is a functional library that expedites the process of creating geospatial visualizations. It provides many functions and methods to enrich the maps."
},
{
"code": null,
"e": 5197,
"s": 4990,
"text": "If you are working or plan to work with geospatial data, I highly recommend checking the documentation of GeoPandas. They also provide examples that will help to adapt the functions and methods more easily."
}
] |
Static vs Dynamic Binding in Java
|
07 Jan, 2022
There are certain key points that are needed to be remembered before adhering forward where we will be discussing and implementing static and dynamic bindings in Java later concluding out the differences.
private, final and static members (methods and variables) use static binding while for virtual methods (In Java methods are virtual by default) binding is done during run time based upon the run time object.
The static binding uses Type information for binding while Dynamic binding uses Objects to resolve to bind.
Overloaded methods are resolved (deciding which method to be called when there are multiple methods with the same name) using static binding while overridden methods use dynamic binding, i.e, at run time.
The binding which can be resolved at compile time by the compiler is known as static or early binding. The binding of all the static, private, and final methods is done at compile-time.
Example:
Java
// Java Program to Illustrate Static Binding // Main classclass NewClass { // Static nested inner class // Class 1 public static class superclass { // Method of inner class static void print() { // Print statement System.out.println( "print() in superclass is called"); } } // Static nested inner class // Class 2 public static class subclass extends superclass { // Method of inner class static void print() { // print statement System.out.println( "print() in subclass is called"); } } // Method of main class // Main driver method public static void main(String[] args) { // Creating objects of static inner classes // inside main() method superclass A = new superclass(); superclass B = new subclass(); // Calling method over above objects A.print(); B.print(); }}
print() in superclass is called
print() in superclass is called
Output Explanation: As you can see, in both cases the print method of the superclass is called. Let us discuss how this happens
We have created one object of subclass and one object of the superclass with the reference of the superclass.
Since the print method of the superclass is static, the compiler knows that it will not be overridden in subclasses and hence compiler knows during compile time which print method to call and hence no ambiguity.
As an exercise, the reader can change the reference of object B to subclass and then check the output.
In Dynamic binding compiler doesnβt decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method.
Example:
Java
// Java Program to Illustrate Dynamic Binding // Main classpublic class GFG { // Static nested inner class // Class 1 public static class superclass { // Method of inner class 1 void print() { // Print statement System.out.println( "print in superclass is called"); } } // Static nested inner class // Class 2 public static class subclass extends superclass { // Method of inner class 2 @Override void print() { // Print statement System.out.println( "print in subclass is called"); } } // Method inside main class public static void main(String[] args) { // Creating object of inner class 1 // with reference to constructor of super class superclass A = new superclass(); // Creating object of inner class 1 // with reference to constructor of sub class superclass B = new subclass(); // Calling print() method over above objects A.print(); B.print(); }}
print in superclass is called
print in subclass is called
Output Explanation: Here the output differs. But why? Letβs break down the code and understand it thoroughly.
Methods are not static in this code.
During compilation, the compiler has no idea as to which print has to be called since the compiler goes only by referencing variable not by the type of object, and therefore the binding would be delayed to runtime and therefore the corresponding version of the print will be called based on type on an object.
Tip: Geeks, now the question arises why binding of static, final, and private methods is always static binding?
Static binding is better performance-wise (no extra overhead is required). The compiler knows that all such methods cannot be overridden and will always be accessed by objects of the local class. Hence compiler doesnβt have any difficulty determining the object of the class (local class for sure). Thatβs the reason binding for such methods is static.
Let us now finally see the differences between static and dynamic binding that is as follows:
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
solankimayank
arorakashish0911
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": "\n07 Jan, 2022"
},
{
"code": null,
"e": 259,
"s": 52,
"text": "There are certain key points that are needed to be remembered before adhering forward where we will be discussing and implementing static and dynamic bindings in Java later concluding out the differences. "
},
{
"code": null,
"e": 467,
"s": 259,
"text": "private, final and static members (methods and variables) use static binding while for virtual methods (In Java methods are virtual by default) binding is done during run time based upon the run time object."
},
{
"code": null,
"e": 575,
"s": 467,
"text": "The static binding uses Type information for binding while Dynamic binding uses Objects to resolve to bind."
},
{
"code": null,
"e": 780,
"s": 575,
"text": "Overloaded methods are resolved (deciding which method to be called when there are multiple methods with the same name) using static binding while overridden methods use dynamic binding, i.e, at run time."
},
{
"code": null,
"e": 966,
"s": 780,
"text": "The binding which can be resolved at compile time by the compiler is known as static or early binding. The binding of all the static, private, and final methods is done at compile-time."
},
{
"code": null,
"e": 975,
"s": 966,
"text": "Example:"
},
{
"code": null,
"e": 980,
"s": 975,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Static Binding // Main classclass NewClass { // Static nested inner class // Class 1 public static class superclass { // Method of inner class static void print() { // Print statement System.out.println( \"print() in superclass is called\"); } } // Static nested inner class // Class 2 public static class subclass extends superclass { // Method of inner class static void print() { // print statement System.out.println( \"print() in subclass is called\"); } } // Method of main class // Main driver method public static void main(String[] args) { // Creating objects of static inner classes // inside main() method superclass A = new superclass(); superclass B = new subclass(); // Calling method over above objects A.print(); B.print(); }}",
"e": 1976,
"s": 980,
"text": null
},
{
"code": null,
"e": 2040,
"s": 1976,
"text": "print() in superclass is called\nprint() in superclass is called"
},
{
"code": null,
"e": 2169,
"s": 2040,
"text": "Output Explanation: As you can see, in both cases the print method of the superclass is called. Let us discuss how this happens "
},
{
"code": null,
"e": 2279,
"s": 2169,
"text": "We have created one object of subclass and one object of the superclass with the reference of the superclass."
},
{
"code": null,
"e": 2491,
"s": 2279,
"text": "Since the print method of the superclass is static, the compiler knows that it will not be overridden in subclasses and hence compiler knows during compile time which print method to call and hence no ambiguity."
},
{
"code": null,
"e": 2595,
"s": 2491,
"text": "As an exercise, the reader can change the reference of object B to subclass and then check the output. "
},
{
"code": null,
"e": 2781,
"s": 2595,
"text": "In Dynamic binding compiler doesnβt decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method."
},
{
"code": null,
"e": 2790,
"s": 2781,
"text": "Example:"
},
{
"code": null,
"e": 2795,
"s": 2790,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Dynamic Binding // Main classpublic class GFG { // Static nested inner class // Class 1 public static class superclass { // Method of inner class 1 void print() { // Print statement System.out.println( \"print in superclass is called\"); } } // Static nested inner class // Class 2 public static class subclass extends superclass { // Method of inner class 2 @Override void print() { // Print statement System.out.println( \"print in subclass is called\"); } } // Method inside main class public static void main(String[] args) { // Creating object of inner class 1 // with reference to constructor of super class superclass A = new superclass(); // Creating object of inner class 1 // with reference to constructor of sub class superclass B = new subclass(); // Calling print() method over above objects A.print(); B.print(); }}",
"e": 3890,
"s": 2795,
"text": null
},
{
"code": null,
"e": 3948,
"s": 3890,
"text": "print in superclass is called\nprint in subclass is called"
},
{
"code": null,
"e": 4059,
"s": 3948,
"text": "Output Explanation: Here the output differs. But why? Letβs break down the code and understand it thoroughly. "
},
{
"code": null,
"e": 4096,
"s": 4059,
"text": "Methods are not static in this code."
},
{
"code": null,
"e": 4406,
"s": 4096,
"text": "During compilation, the compiler has no idea as to which print has to be called since the compiler goes only by referencing variable not by the type of object, and therefore the binding would be delayed to runtime and therefore the corresponding version of the print will be called based on type on an object."
},
{
"code": null,
"e": 4519,
"s": 4406,
"text": "Tip: Geeks, now the question arises why binding of static, final, and private methods is always static binding? "
},
{
"code": null,
"e": 4873,
"s": 4519,
"text": "Static binding is better performance-wise (no extra overhead is required). The compiler knows that all such methods cannot be overridden and will always be accessed by objects of the local class. Hence compiler doesnβt have any difficulty determining the object of the class (local class for sure). Thatβs the reason binding for such methods is static. "
},
{
"code": null,
"e": 4968,
"s": 4873,
"text": "Let us now finally see the differences between static and dynamic binding that is as follows: "
},
{
"code": null,
"e": 5238,
"s": 4968,
"text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5252,
"s": 5238,
"text": "solankimayank"
},
{
"code": null,
"e": 5269,
"s": 5252,
"text": "arorakashish0911"
},
{
"code": null,
"e": 5274,
"s": 5269,
"text": "Java"
},
{
"code": null,
"e": 5279,
"s": 5274,
"text": "Java"
}
] |
C# Program to Implement Multiple Interfaces in the Same Class
|
21 Oct, 2021
Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interfaceβs members will be given by the class that implements the interface implicitly or explicitly. C# allows that a single class can implement multiple interfaces at a time, and also define methods and variables in that interface.
Approach
1. To implement three interfaces along with some methods in all the interfaces in the same class follow the following steps:
2. Create three Interfaces named as firstinterface, secondinterface, and thirdinterface with the declaration of methods in it.
interface firstinterface
{
// Declaration of method
void myfun1();
}
3. Now we create a, Int_Class that will implement all these interfaces like this:
class Int_Class : firstinterface, secondinterface, thirdinterface
After that in Int_Class, we define the definition of Method1, Method2, and Method3.
Now, create the objects named obj1, obj2, obj3 of Int_class in the main function.
After creating objects, call the methods by using the objects of Int_Class in the main function.
Example:
C#
// C# program to implement multiple interfaces // in the same class.using System; // Creating interfacesinterface firstinterface{ // Declaring Method void myfun1();} interface secondinterface{ // Declaring Method void myfun2();} interface thirdinterface{ // Declaring Method void myfun3();} // Here Int_Class implements three interfacesclass Int_Class : firstinterface, secondinterface, thirdinterface{ // Definition of Method public void myfun1() { Console.WriteLine("Hello! i am method of firstinterface"); } // Definition of Method public void myfun2() { Console.WriteLine("Hello! i am method of secondinterface"); } // Definition of Method public void myfun3() { Console.WriteLine("Hello! i am method of thirdinterface"); }} class GFG{ // Driver codepublic static void Main(String[] args){ // Creating the objects of Int_Class class firstinterface obj1; secondinterface obj2; thirdinterface obj3; obj1 = new Int_Class(); obj2 = new Int_Class(); obj3 = new Int_Class(); // Call the methods from firstinterface, // secondinterface, and thirdinterface obj1.myfun1(); obj2.myfun2(); obj3.myfun3();}}
Output:
Hello! i am method of firstinterface
Hello! i am method of secondinterface
Hello! i am method of thirdinterface
Explanation: In the above code, first we create three interfaces named firstinterface, secondinterface, and thirdinterface along with one method in each interface named myfun1, myfun2, and myfun3. Now we create an Int_Class that will implement all these three interfaces. Now in the main function, we create three objects of Int_class, i.e., obj1, obj2, and obj3, and using these objects we will call the methods of firstinterface, secondinterface, and thirdinterface.
CSharp-Interfaces
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Lambda Expressions in C#
Switch Statement in C#
Partial Classes in C#
Hello World in C#
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 440,
"s": 28,
"text": "Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interfaceβs members will be given by the class that implements the interface implicitly or explicitly. C# allows that a single class can implement multiple interfaces at a time, and also define methods and variables in that interface."
},
{
"code": null,
"e": 449,
"s": 440,
"text": "Approach"
},
{
"code": null,
"e": 574,
"s": 449,
"text": "1. To implement three interfaces along with some methods in all the interfaces in the same class follow the following steps:"
},
{
"code": null,
"e": 701,
"s": 574,
"text": "2. Create three Interfaces named as firstinterface, secondinterface, and thirdinterface with the declaration of methods in it."
},
{
"code": null,
"e": 778,
"s": 701,
"text": "interface firstinterface\n{\n // Declaration of method\n void myfun1();\n}"
},
{
"code": null,
"e": 860,
"s": 778,
"text": "3. Now we create a, Int_Class that will implement all these interfaces like this:"
},
{
"code": null,
"e": 926,
"s": 860,
"text": "class Int_Class : firstinterface, secondinterface, thirdinterface"
},
{
"code": null,
"e": 1010,
"s": 926,
"text": "After that in Int_Class, we define the definition of Method1, Method2, and Method3."
},
{
"code": null,
"e": 1092,
"s": 1010,
"text": "Now, create the objects named obj1, obj2, obj3 of Int_class in the main function."
},
{
"code": null,
"e": 1189,
"s": 1092,
"text": "After creating objects, call the methods by using the objects of Int_Class in the main function."
},
{
"code": null,
"e": 1198,
"s": 1189,
"text": "Example:"
},
{
"code": null,
"e": 1201,
"s": 1198,
"text": "C#"
},
{
"code": "// C# program to implement multiple interfaces // in the same class.using System; // Creating interfacesinterface firstinterface{ // Declaring Method void myfun1();} interface secondinterface{ // Declaring Method void myfun2();} interface thirdinterface{ // Declaring Method void myfun3();} // Here Int_Class implements three interfacesclass Int_Class : firstinterface, secondinterface, thirdinterface{ // Definition of Method public void myfun1() { Console.WriteLine(\"Hello! i am method of firstinterface\"); } // Definition of Method public void myfun2() { Console.WriteLine(\"Hello! i am method of secondinterface\"); } // Definition of Method public void myfun3() { Console.WriteLine(\"Hello! i am method of thirdinterface\"); }} class GFG{ // Driver codepublic static void Main(String[] args){ // Creating the objects of Int_Class class firstinterface obj1; secondinterface obj2; thirdinterface obj3; obj1 = new Int_Class(); obj2 = new Int_Class(); obj3 = new Int_Class(); // Call the methods from firstinterface, // secondinterface, and thirdinterface obj1.myfun1(); obj2.myfun2(); obj3.myfun3();}}",
"e": 2479,
"s": 1201,
"text": null
},
{
"code": null,
"e": 2487,
"s": 2479,
"text": "Output:"
},
{
"code": null,
"e": 2599,
"s": 2487,
"text": "Hello! i am method of firstinterface\nHello! i am method of secondinterface\nHello! i am method of thirdinterface"
},
{
"code": null,
"e": 3068,
"s": 2599,
"text": "Explanation: In the above code, first we create three interfaces named firstinterface, secondinterface, and thirdinterface along with one method in each interface named myfun1, myfun2, and myfun3. Now we create an Int_Class that will implement all these three interfaces. Now in the main function, we create three objects of Int_class, i.e., obj1, obj2, and obj3, and using these objects we will call the methods of firstinterface, secondinterface, and thirdinterface."
},
{
"code": null,
"e": 3086,
"s": 3068,
"text": "CSharp-Interfaces"
},
{
"code": null,
"e": 3102,
"s": 3086,
"text": "CSharp-programs"
},
{
"code": null,
"e": 3109,
"s": 3102,
"text": "Picked"
},
{
"code": null,
"e": 3112,
"s": 3109,
"text": "C#"
},
{
"code": null,
"e": 3210,
"s": 3112,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3253,
"s": 3210,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 3302,
"s": 3253,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 3325,
"s": 3302,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 3341,
"s": 3325,
"text": "C# | List Class"
},
{
"code": null,
"e": 3402,
"s": 3341,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 3430,
"s": 3402,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 3455,
"s": 3430,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 3478,
"s": 3455,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 3500,
"s": 3478,
"text": "Partial Classes in C#"
}
] |
Correcting EOF error in python in Codechef
|
24 Nov, 2020
EOF stands for End Of File. Well, technically it is not an error, rather an exception. This exception is raised when one of the built-in functions, most commonly input() returns End-Of-File (EOF) without reading any data.
EOF error is raised in Python in some specific scenarios:
Sometimes all program tries to do is to fetch something and modify it. But when it is unable to fetch, it will raise this exception.
When the input() function is interrupted in both Python 2.7 and Python 3.6+, or when the input() reaches the end of a file unexpectedly in Python 2.7.
All Built-in Exceptions in Python inherit from the BaseException class or extend from an inherited class therein. The full exception hierarchy of this error is:
BaseException -> Exception -> EOFError
The best practice to avoid EOF in python while coding on any platform is to catch the exception, and we donβt need to perform any action so, we just pass the exception using the keyword βpassβ in the βexceptβ block.
Consider the following code for the question in CodeChef K-Foldable String (KFOLD):
C++
#Python program for the above question #Function to reorder the characters#of the stringdef main(): t = int(input()) while t: # Input variables n, k = map(int, input().split()) s = input() ans = "" # Initialize dictionary s_dict = dict() for ch in s: s_dict[ch] = s_dict.get(ch, 0) + 1 q = n// k a1 = s_dict['1']// q a0 = s_dict['0']// q # Check for valid conditions if(s_dict['1']%2!=0 or s_dict['0']%2!=0 \\ or s_dict['1']%q!=0 or s_dict['0']%q!=0): ans = "Impossible" # Otherwise update the result else: st = ('0'*a0) + ('1'*a1) st = ('1'*a1) + ('0'*a0) part1 = st + st_rev ans = part1*(q// 2) # Print the result for the # current test case print(ans) t -= 1 return # Driver Codeif __name__=="__main__": main()
Output:
It gives the EOF error as shown below:
The solution to the above EOF error is to enclose the code in try and except block and deal with exception accordingly, the approach to handle this exception is shown below:
C++
# Python program for the above question # Function to reorder the characters#of the stringtry : t = int(input()) # Input test cases while t: # Input Variables n, k = map(int, input().split()) s = input() ans = "" # Initialize dictionary s_dict = dict() for ch in s: s_dict[ch] = s_dict.get(ch, 0) + 1 q = n// k a1 = s_dict['1']// q a0 = s_dict['0']// q # Check for valid conditions if(s_dict['1']%2!=0 or s_dict['0']%2!=0 \\ or s_dict['1']%q!=0 or s_dict['0']%q!=0): ans = "Impossible" # Otherwise update the result else: st = ('0'*a0) + ('1'*a1) st = ('1'*a1) + ('0'*a0) part1 = st + st_rev ans = part1*(q// 2) # Print the result for the # current test case print(ans) t -= 1 except: pass
Output:
python
Python-exceptions
Articles
Programming Language
Python
python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 250,
"s": 28,
"text": "EOF stands for End Of File. Well, technically it is not an error, rather an exception. This exception is raised when one of the built-in functions, most commonly input() returns End-Of-File (EOF) without reading any data."
},
{
"code": null,
"e": 308,
"s": 250,
"text": "EOF error is raised in Python in some specific scenarios:"
},
{
"code": null,
"e": 441,
"s": 308,
"text": "Sometimes all program tries to do is to fetch something and modify it. But when it is unable to fetch, it will raise this exception."
},
{
"code": null,
"e": 592,
"s": 441,
"text": "When the input() function is interrupted in both Python 2.7 and Python 3.6+, or when the input() reaches the end of a file unexpectedly in Python 2.7."
},
{
"code": null,
"e": 753,
"s": 592,
"text": "All Built-in Exceptions in Python inherit from the BaseException class or extend from an inherited class therein. The full exception hierarchy of this error is:"
},
{
"code": null,
"e": 792,
"s": 753,
"text": "BaseException -> Exception -> EOFError"
},
{
"code": null,
"e": 1008,
"s": 792,
"text": "The best practice to avoid EOF in python while coding on any platform is to catch the exception, and we donβt need to perform any action so, we just pass the exception using the keyword βpassβ in the βexceptβ block."
},
{
"code": null,
"e": 1092,
"s": 1008,
"text": "Consider the following code for the question in CodeChef K-Foldable String (KFOLD):"
},
{
"code": null,
"e": 1096,
"s": 1092,
"text": "C++"
},
{
"code": "#Python program for the above question #Function to reorder the characters#of the stringdef main(): t = int(input()) while t: # Input variables n, k = map(int, input().split()) s = input() ans = \"\" # Initialize dictionary s_dict = dict() for ch in s: s_dict[ch] = s_dict.get(ch, 0) + 1 q = n// k a1 = s_dict['1']// q a0 = s_dict['0']// q # Check for valid conditions if(s_dict['1']%2!=0 or s_dict['0']%2!=0 \\\\ or s_dict['1']%q!=0 or s_dict['0']%q!=0): ans = \"Impossible\" # Otherwise update the result else: st = ('0'*a0) + ('1'*a1) st = ('1'*a1) + ('0'*a0) part1 = st + st_rev ans = part1*(q// 2) # Print the result for the # current test case print(ans) t -= 1 return # Driver Codeif __name__==\"__main__\": main()",
"e": 2036,
"s": 1096,
"text": null
},
{
"code": null,
"e": 2044,
"s": 2036,
"text": "Output:"
},
{
"code": null,
"e": 2083,
"s": 2044,
"text": "It gives the EOF error as shown below:"
},
{
"code": null,
"e": 2257,
"s": 2083,
"text": "The solution to the above EOF error is to enclose the code in try and except block and deal with exception accordingly, the approach to handle this exception is shown below:"
},
{
"code": null,
"e": 2261,
"s": 2257,
"text": "C++"
},
{
"code": "# Python program for the above question # Function to reorder the characters#of the stringtry : t = int(input()) # Input test cases while t: # Input Variables n, k = map(int, input().split()) s = input() ans = \"\" # Initialize dictionary s_dict = dict() for ch in s: s_dict[ch] = s_dict.get(ch, 0) + 1 q = n// k a1 = s_dict['1']// q a0 = s_dict['0']// q # Check for valid conditions if(s_dict['1']%2!=0 or s_dict['0']%2!=0 \\\\ or s_dict['1']%q!=0 or s_dict['0']%q!=0): ans = \"Impossible\" # Otherwise update the result else: st = ('0'*a0) + ('1'*a1) st = ('1'*a1) + ('0'*a0) part1 = st + st_rev ans = part1*(q// 2) # Print the result for the # current test case print(ans) t -= 1 except: pass",
"e": 3177,
"s": 2261,
"text": null
},
{
"code": null,
"e": 3185,
"s": 3177,
"text": "Output:"
},
{
"code": null,
"e": 3192,
"s": 3185,
"text": "python"
},
{
"code": null,
"e": 3210,
"s": 3192,
"text": "Python-exceptions"
},
{
"code": null,
"e": 3219,
"s": 3210,
"text": "Articles"
},
{
"code": null,
"e": 3240,
"s": 3219,
"text": "Programming Language"
},
{
"code": null,
"e": 3247,
"s": 3240,
"text": "Python"
},
{
"code": null,
"e": 3254,
"s": 3247,
"text": "python"
}
] |
Python | Count occurrences of an element in a list
|
05 Jul, 2022
Given a list in Python and a number x, count the number of occurrences of x in the given list.
Examples:
Input : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10]
x = 10
Output : 3
10 appears three times in given list.
Input : lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 16
Output : 0
We keep a counter that keeps on increasing if the required element is found in the list.
Python3
# Python code to count the number of occurrencesdef countX(lst, x): count = 0 for ele in lst: if (ele == x): count = count + 1 return count # Driver Codelst = [8, 6, 8, 10, 8, 20, 10, 8, 8]x = 8print('{} has occurred {} times'.format(x, countX(lst, x)))
Output:
8 has occurred 5 times
The idea is to use the list method count() to count the number of occurrences.
Python3
# Python code to count the number of occurrencesdef countX(lst, x): return lst.count(x) # Driver Codelst = [8, 6, 8, 10, 8, 20, 10, 8, 8]x = 8print('{} has occurred {} times'.format(x, countX(lst, x)))
Output:
8 has occurred 5 times
The counter method returns a dictionary with occurrences of all elements as a key-value pair, where the key is the element and the value is the number of times that element has occurred.
Python3
from collections import Counter # declaring the listl = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5] # driver programx = 3d = Counter(l)print('{} has occurred {} times'.format(x, d[x]))
Output:
3 has occurred 2 times
Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.
Python3
import operator as op # declaring the listl = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5] # driver programx = 2print(f"{x} has occurred {op.countOf(l, x)} times")
Output:
2 has occurred 3 times
Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}
Python3
lis = ['a', 'd', 'd', 'c', 'a', 'b', 'b', 'a', 'c', 'd', 'e']occurrence = {item: lis.count(item) for item in lis}print(occurrence.get('e'))
Output:
1
Pandas Series.value_counts() function return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element.
Python3
import pandas as pd # declaring the listl = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5] count = pd.Series(l).value_counts()print ("Element Count")print(count)
Output:
Element Count
2 3
1 2
3 2
4 2
5 2
dtype: int64
BhushanBorole
Akanksha_Rai
nidhi_biet
simranarora5sos
surajkumarguptaintern
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 147,
"s": 52,
"text": "Given a list in Python and a number x, count the number of occurrences of x in the given list."
},
{
"code": null,
"e": 158,
"s": 147,
"text": "Examples: "
},
{
"code": null,
"e": 345,
"s": 158,
"text": "Input : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10]\n x = 10\nOutput : 3 \n10 appears three times in given list.\n\nInput : lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]\n x = 16\nOutput : 0"
},
{
"code": null,
"e": 434,
"s": 345,
"text": "We keep a counter that keeps on increasing if the required element is found in the list."
},
{
"code": null,
"e": 442,
"s": 434,
"text": "Python3"
},
{
"code": "# Python code to count the number of occurrencesdef countX(lst, x): count = 0 for ele in lst: if (ele == x): count = count + 1 return count # Driver Codelst = [8, 6, 8, 10, 8, 20, 10, 8, 8]x = 8print('{} has occurred {} times'.format(x, countX(lst, x)))",
"e": 723,
"s": 442,
"text": null
},
{
"code": null,
"e": 731,
"s": 723,
"text": "Output:"
},
{
"code": null,
"e": 754,
"s": 731,
"text": "8 has occurred 5 times"
},
{
"code": null,
"e": 834,
"s": 754,
"text": "The idea is to use the list method count() to count the number of occurrences. "
},
{
"code": null,
"e": 842,
"s": 834,
"text": "Python3"
},
{
"code": "# Python code to count the number of occurrencesdef countX(lst, x): return lst.count(x) # Driver Codelst = [8, 6, 8, 10, 8, 20, 10, 8, 8]x = 8print('{} has occurred {} times'.format(x, countX(lst, x)))",
"e": 1047,
"s": 842,
"text": null
},
{
"code": null,
"e": 1055,
"s": 1047,
"text": "Output:"
},
{
"code": null,
"e": 1079,
"s": 1055,
"text": "8 has occurred 5 times "
},
{
"code": null,
"e": 1267,
"s": 1079,
"text": "The counter method returns a dictionary with occurrences of all elements as a key-value pair, where the key is the element and the value is the number of times that element has occurred. "
},
{
"code": null,
"e": 1275,
"s": 1267,
"text": "Python3"
},
{
"code": "from collections import Counter # declaring the listl = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5] # driver programx = 3d = Counter(l)print('{} has occurred {} times'.format(x, d[x]))",
"e": 1447,
"s": 1275,
"text": null
},
{
"code": null,
"e": 1455,
"s": 1447,
"text": "Output:"
},
{
"code": null,
"e": 1478,
"s": 1455,
"text": "3 has occurred 2 times"
},
{
"code": null,
"e": 1659,
"s": 1478,
"text": "Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value."
},
{
"code": null,
"e": 1667,
"s": 1659,
"text": "Python3"
},
{
"code": "import operator as op # declaring the listl = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5] # driver programx = 2print(f\"{x} has occurred {op.countOf(l, x)} times\")",
"e": 1820,
"s": 1667,
"text": null
},
{
"code": null,
"e": 1828,
"s": 1820,
"text": "Output:"
},
{
"code": null,
"e": 1851,
"s": 1828,
"text": "2 has occurred 3 times"
},
{
"code": null,
"e": 2029,
"s": 1851,
"text": "Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}"
},
{
"code": null,
"e": 2037,
"s": 2029,
"text": "Python3"
},
{
"code": "lis = ['a', 'd', 'd', 'c', 'a', 'b', 'b', 'a', 'c', 'd', 'e']occurrence = {item: lis.count(item) for item in lis}print(occurrence.get('e'))",
"e": 2177,
"s": 2037,
"text": null
},
{
"code": null,
"e": 2185,
"s": 2177,
"text": "Output:"
},
{
"code": null,
"e": 2187,
"s": 2185,
"text": "1"
},
{
"code": null,
"e": 2394,
"s": 2187,
"text": "Pandas Series.value_counts() function return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element."
},
{
"code": null,
"e": 2402,
"s": 2394,
"text": "Python3"
},
{
"code": "import pandas as pd # declaring the listl = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5] count = pd.Series(l).value_counts()print (\"Element Count\")print(count)",
"e": 2554,
"s": 2402,
"text": null
},
{
"code": null,
"e": 2562,
"s": 2554,
"text": "Output:"
},
{
"code": null,
"e": 2627,
"s": 2562,
"text": "Element Count\n2 3\n1 2\n3 2\n4 2\n5 2\ndtype: int64"
},
{
"code": null,
"e": 2641,
"s": 2627,
"text": "BhushanBorole"
},
{
"code": null,
"e": 2654,
"s": 2641,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2665,
"s": 2654,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2681,
"s": 2665,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2703,
"s": 2681,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 2724,
"s": 2703,
"text": "Python list-programs"
},
{
"code": null,
"e": 2736,
"s": 2724,
"text": "python-list"
},
{
"code": null,
"e": 2743,
"s": 2736,
"text": "Python"
},
{
"code": null,
"e": 2755,
"s": 2743,
"text": "python-list"
},
{
"code": null,
"e": 2853,
"s": 2755,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2871,
"s": 2853,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2913,
"s": 2871,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2935,
"s": 2913,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2961,
"s": 2935,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2993,
"s": 2961,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3022,
"s": 2993,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3052,
"s": 3022,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3079,
"s": 3052,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3102,
"s": 3079,
"text": "Introduction To PYTHON"
}
] |
Algorithms | Graph Traversals | Question 12
|
28 Jun, 2021
What are the appropriate data structures for following algorithms?
1) Breadth First Search
2) Depth First Search
3) Prim's Minimum Spanning Tree
4) Kruskal' Minimum Spanning Tree
(A)
1) Stack
2) Queue
3) Priority Queue
4) Union Find
(B)
1) Queue
2) Stack
3) Priority Queue
4) Union Find
(C)
1) Stack
2) Queue
3) Union Find
4) Priority Queue
(D)
1) Priority Queue
2) Queue
3) Stack
4) Union Find
Answer: (B)Explanation: 1) Breadth First Search uses Queue2) Depth First Search uses Stack3) Primβs Minimum Spanning Tree uses Priority Queue.4) Kruskalβ Minimum Spanning Tree uses Union Find.Quiz of this Question
Algorithms-Graph Traversals
Graph Traversals
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 119,
"s": 52,
"text": "What are the appropriate data structures for following algorithms?"
},
{
"code": null,
"e": 320,
"s": 119,
"text": "1) Breadth First Search \n2) Depth First Search \n3) Prim's Minimum Spanning Tree \n4) Kruskal' Minimum Spanning Tree \n"
},
{
"code": null,
"e": 324,
"s": 320,
"text": "(A)"
},
{
"code": null,
"e": 374,
"s": 324,
"text": "1) Stack\n2) Queue\n3) Priority Queue\n4) Union Find"
},
{
"code": null,
"e": 378,
"s": 374,
"text": "(B)"
},
{
"code": null,
"e": 429,
"s": 378,
"text": "1) Queue\n2) Stack\n3) Priority Queue\n4) Union Find\n"
},
{
"code": null,
"e": 433,
"s": 429,
"text": "(C)"
},
{
"code": null,
"e": 484,
"s": 433,
"text": "1) Stack\n2) Queue\n3) Union Find\n4) Priority Queue "
},
{
"code": null,
"e": 488,
"s": 484,
"text": "(D)"
},
{
"code": null,
"e": 538,
"s": 488,
"text": "1) Priority Queue\n2) Queue\n3) Stack\n4) Union Find"
},
{
"code": null,
"e": 752,
"s": 538,
"text": "Answer: (B)Explanation: 1) Breadth First Search uses Queue2) Depth First Search uses Stack3) Primβs Minimum Spanning Tree uses Priority Queue.4) Kruskalβ Minimum Spanning Tree uses Union Find.Quiz of this Question"
},
{
"code": null,
"e": 780,
"s": 752,
"text": "Algorithms-Graph Traversals"
},
{
"code": null,
"e": 797,
"s": 780,
"text": "Graph Traversals"
},
{
"code": null,
"e": 813,
"s": 797,
"text": "Algorithms Quiz"
}
] |
URL getHost() method in Java with Examples
|
27 Dec, 2018
getHost() function is a part of URL class. The function getHost() returns the Host of a specified URL. The Host part of the URL is the host name of the URL. The format of the host conforms to RFC 2732.
Function Signature
public String getHost()
Syntax
url.getHost()
Parameter: This function does not require any parameter
Return Type: The function returns String Type
Below programs illustrates the use of getHost() function:
Example 1:
// Java program to show the use// of the function getHost() import java.net.*; class GFG { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL("https:// www.geeksforgeeks.org"); // get the Host String Host = url.getHost(); // display the URL System.out.println("URL = " + url); // display the Host System.out.println("Host = " + Host); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}
URL = https:// www.geeksforgeeks.org
Host = www.geeksforgeeks.org
Example 2:
// Java program to show the// use of the function getHost() import java.net.*; class GFG { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL( "https:// www.geeksforgeeks.org:80/url-samefile-method-in-java-with-examples/"); // get the Authority String authority = url.getAuthority(); // get the Host String host = url.getHost(); // display the URL System.out.println("URL = " + url); // display the Host System.out.println("Authority = " + authority); // display the Host System.out.println("Host = " + host); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}
URL = https:// www.geeksforgeeks.org:80/url-samefile-method-in-java-with-examples/
Authority = www.geeksforgeeks.org:80
Host = www.geeksforgeeks.org
Example 3: If we create a URL with no host name and ask for the host using the getHost() function the function returns blank String.
// Java program to show the// use of the function getHost() import java.net.*; class GFG { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL("https://"); // get the Host String Host = url.getHost(); // display the URL System.out.println("URL = " + url); // display the Host System.out.println("Host = " + Host); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}
URL = https:
Host =
Java-Functions
Java-net-package
Java-URL
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "getHost() function is a part of URL class. The function getHost() returns the Host of a specified URL. The Host part of the URL is the host name of the URL. The format of the host conforms to RFC 2732."
},
{
"code": null,
"e": 249,
"s": 230,
"text": "Function Signature"
},
{
"code": null,
"e": 274,
"s": 249,
"text": "public String getHost()\n"
},
{
"code": null,
"e": 281,
"s": 274,
"text": "Syntax"
},
{
"code": null,
"e": 296,
"s": 281,
"text": "url.getHost()\n"
},
{
"code": null,
"e": 352,
"s": 296,
"text": "Parameter: This function does not require any parameter"
},
{
"code": null,
"e": 398,
"s": 352,
"text": "Return Type: The function returns String Type"
},
{
"code": null,
"e": 456,
"s": 398,
"text": "Below programs illustrates the use of getHost() function:"
},
{
"code": null,
"e": 467,
"s": 456,
"text": "Example 1:"
},
{
"code": "// Java program to show the use// of the function getHost() import java.net.*; class GFG { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL(\"https:// www.geeksforgeeks.org\"); // get the Host String Host = url.getHost(); // display the URL System.out.println(\"URL = \" + url); // display the Host System.out.println(\"Host = \" + Host); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}",
"e": 1154,
"s": 467,
"text": null
},
{
"code": null,
"e": 1222,
"s": 1154,
"text": "URL = https:// www.geeksforgeeks.org\nHost = www.geeksforgeeks.org\n"
},
{
"code": null,
"e": 1233,
"s": 1222,
"text": "Example 2:"
},
{
"code": "// Java program to show the// use of the function getHost() import java.net.*; class GFG { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL( \"https:// www.geeksforgeeks.org:80/url-samefile-method-in-java-with-examples/\"); // get the Authority String authority = url.getAuthority(); // get the Host String host = url.getHost(); // display the URL System.out.println(\"URL = \" + url); // display the Host System.out.println(\"Authority = \" + authority); // display the Host System.out.println(\"Host = \" + host); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}",
"e": 2203,
"s": 1233,
"text": null
},
{
"code": null,
"e": 2355,
"s": 2203,
"text": "URL = https:// www.geeksforgeeks.org:80/url-samefile-method-in-java-with-examples/\nAuthority = www.geeksforgeeks.org:80\nHost = www.geeksforgeeks.org\n"
},
{
"code": null,
"e": 2488,
"s": 2355,
"text": "Example 3: If we create a URL with no host name and ask for the host using the getHost() function the function returns blank String."
},
{
"code": "// Java program to show the// use of the function getHost() import java.net.*; class GFG { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL(\"https://\"); // get the Host String Host = url.getHost(); // display the URL System.out.println(\"URL = \" + url); // display the Host System.out.println(\"Host = \" + Host); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}",
"e": 3136,
"s": 2488,
"text": null
},
{
"code": null,
"e": 3157,
"s": 3136,
"text": "URL = https:\nHost =\n"
},
{
"code": null,
"e": 3172,
"s": 3157,
"text": "Java-Functions"
},
{
"code": null,
"e": 3189,
"s": 3172,
"text": "Java-net-package"
},
{
"code": null,
"e": 3198,
"s": 3189,
"text": "Java-URL"
},
{
"code": null,
"e": 3203,
"s": 3198,
"text": "Java"
},
{
"code": null,
"e": 3208,
"s": 3203,
"text": "Java"
}
] |
Find the sum of elements of the Matrix generated by the given rules
|
28 May, 2022
Given three integers A, B, and R, the task is to find the sum of all the elements of the matrix generated by the given rules:
The first row will contain a single element which is A and the rest of the elements will be 0.The next row will contain two elements all of which are (A + B) and the rest are 0s.Third row will contain (A + B + B) three times and the rest are 0s and so on.The matrix will contain only R rows.
The first row will contain a single element which is A and the rest of the elements will be 0.
The next row will contain two elements all of which are (A + B) and the rest are 0s.
Third row will contain (A + B + B) three times and the rest are 0s and so on.
The matrix will contain only R rows.
For example, if A = 5, B = 3 and R = 3 then the matrix will be: 5 0 0 8 8 0 11 11 11Examples:
Input: A = 5, B = 3, R = 3 Output: 54 5 + 8 + 8 + 11 + 11 + 11 = 54Input: A = 7, B = 56, R = 1 Output: 7
Approach: Initialize sum = 0 and for every 1 β€ i β€ R update sum = sum + (i * A). After every iteration update A = A + B. Print the final sum in the end.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the required sumint sum(int A, int B, int R){ // To store the sum int sum = 0; // For every row for (int i = 1; i <= R; i++) { // Update the sum as A appears i number // of times in the current row sum = sum + (i * A); // Update A for the next row A = A + B; } // Return the sum return sum;} // Driver codeint main(){ int A = 5, B = 3, R = 3; cout << sum(A, B, R); return 0;}
// JAVA implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to return the required sumstatic int sum(int A, int B, int R){ // To store the sum int sum = 0; // For every row for (int i = 1; i <= R; i++) { // Update the sum as A appears i number // of times in the current row sum = sum + (i * A); // Update A for the next row A = A + B; } // Return the sum return sum;} // Driver codepublic static void main (String[] args) throws java.lang.Exception{ int A = 5, B = 3, R = 3; System.out.print(sum(A, B, R));}} // This code is contributed by nidhiva
# Python3 implementation of the approach # Function to return the required sumdef Sum(A, B, R): # To store the sum ssum = 0 # For every row for i in range(1, R + 1): # Update the sum as A appears i number # of times in the current row sum = sum + (i * A) # Update A for the next row A = A + B # Return the sum return sum # Driver codeA, B, R = 5, 3, 3print(Sum(A, B, R)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ // Function to return the required sumstatic int sum(int A, int B, int R){ // To store the sum int sum = 0; // For every row for (int i = 1; i <= R; i++) { // Update the sum as A appears i number // of times in the current row sum = sum + (i * A); // Update A for the next row A = A + B; } // Return the sum return sum;} // Driver codepublic static void Main (){ int A = 5, B = 3, R = 3; Console.Write(sum(A, B, R));}} // This code is contributed by anuj_67..
<script>// JAVA SCRIPT implementation of the approach// Function to return the required sumfunction sum( A, B, R){ // To store the sum let sum = 0; // For every row for (let i = 1; i <= R; i++) { // Update the sum as A appears i number // of times in the current row sum = sum + (i * A); // Update A for the next row A = A + B; } // Return the sum return sum;} // Driver code let A = 5, B = 3, R = 3; document.write(sum(A, B, R)); //contributed by bobby </script>
54
Time Complexity: O(R), since there runs a loop for once from 1 to R.
Auxiliary Space: O(1), since no extra space has been taken.
mohit kumar 29
nidhiva
vt_m
aditya7409
gottumukkalabobby
simmytarika5
subhammahato348
Mathematical
Matrix
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2022"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "Given three integers A, B, and R, the task is to find the sum of all the elements of the matrix generated by the given rules: "
},
{
"code": null,
"e": 447,
"s": 155,
"text": "The first row will contain a single element which is A and the rest of the elements will be 0.The next row will contain two elements all of which are (A + B) and the rest are 0s.Third row will contain (A + B + B) three times and the rest are 0s and so on.The matrix will contain only R rows."
},
{
"code": null,
"e": 542,
"s": 447,
"text": "The first row will contain a single element which is A and the rest of the elements will be 0."
},
{
"code": null,
"e": 627,
"s": 542,
"text": "The next row will contain two elements all of which are (A + B) and the rest are 0s."
},
{
"code": null,
"e": 705,
"s": 627,
"text": "Third row will contain (A + B + B) three times and the rest are 0s and so on."
},
{
"code": null,
"e": 742,
"s": 705,
"text": "The matrix will contain only R rows."
},
{
"code": null,
"e": 838,
"s": 742,
"text": "For example, if A = 5, B = 3 and R = 3 then the matrix will be: 5 0 0 8 8 0 11 11 11Examples: "
},
{
"code": null,
"e": 944,
"s": 838,
"text": "Input: A = 5, B = 3, R = 3 Output: 54 5 + 8 + 8 + 11 + 11 + 11 = 54Input: A = 7, B = 56, R = 1 Output: 7 "
},
{
"code": null,
"e": 1149,
"s": 944,
"text": "Approach: Initialize sum = 0 and for every 1 β€ i β€ R update sum = sum + (i * A). After every iteration update A = A + B. Print the final sum in the end.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1153,
"s": 1149,
"text": "C++"
},
{
"code": null,
"e": 1158,
"s": 1153,
"text": "Java"
},
{
"code": null,
"e": 1166,
"s": 1158,
"text": "Python3"
},
{
"code": null,
"e": 1169,
"s": 1166,
"text": "C#"
},
{
"code": null,
"e": 1180,
"s": 1169,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the required sumint sum(int A, int B, int R){ // To store the sum int sum = 0; // For every row for (int i = 1; i <= R; i++) { // Update the sum as A appears i number // of times in the current row sum = sum + (i * A); // Update A for the next row A = A + B; } // Return the sum return sum;} // Driver codeint main(){ int A = 5, B = 3, R = 3; cout << sum(A, B, R); return 0;}",
"e": 1727,
"s": 1180,
"text": null
},
{
"code": "// JAVA implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to return the required sumstatic int sum(int A, int B, int R){ // To store the sum int sum = 0; // For every row for (int i = 1; i <= R; i++) { // Update the sum as A appears i number // of times in the current row sum = sum + (i * A); // Update A for the next row A = A + B; } // Return the sum return sum;} // Driver codepublic static void main (String[] args) throws java.lang.Exception{ int A = 5, B = 3, R = 3; System.out.print(sum(A, B, R));}} // This code is contributed by nidhiva",
"e": 2421,
"s": 1727,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the required sumdef Sum(A, B, R): # To store the sum ssum = 0 # For every row for i in range(1, R + 1): # Update the sum as A appears i number # of times in the current row sum = sum + (i * A) # Update A for the next row A = A + B # Return the sum return sum # Driver codeA, B, R = 5, 3, 3print(Sum(A, B, R)) # This code is contributed by Mohit Kumar",
"e": 2892,
"s": 2421,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the required sumstatic int sum(int A, int B, int R){ // To store the sum int sum = 0; // For every row for (int i = 1; i <= R; i++) { // Update the sum as A appears i number // of times in the current row sum = sum + (i * A); // Update A for the next row A = A + B; } // Return the sum return sum;} // Driver codepublic static void Main (){ int A = 5, B = 3, R = 3; Console.Write(sum(A, B, R));}} // This code is contributed by anuj_67..",
"e": 3488,
"s": 2892,
"text": null
},
{
"code": "<script>// JAVA SCRIPT implementation of the approach// Function to return the required sumfunction sum( A, B, R){ // To store the sum let sum = 0; // For every row for (let i = 1; i <= R; i++) { // Update the sum as A appears i number // of times in the current row sum = sum + (i * A); // Update A for the next row A = A + B; } // Return the sum return sum;} // Driver code let A = 5, B = 3, R = 3; document.write(sum(A, B, R)); //contributed by bobby </script>",
"e": 4031,
"s": 3488,
"text": null
},
{
"code": null,
"e": 4034,
"s": 4031,
"text": "54"
},
{
"code": null,
"e": 4105,
"s": 4036,
"text": "Time Complexity: O(R), since there runs a loop for once from 1 to R."
},
{
"code": null,
"e": 4165,
"s": 4105,
"text": "Auxiliary Space: O(1), since no extra space has been taken."
},
{
"code": null,
"e": 4180,
"s": 4165,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 4188,
"s": 4180,
"text": "nidhiva"
},
{
"code": null,
"e": 4193,
"s": 4188,
"text": "vt_m"
},
{
"code": null,
"e": 4204,
"s": 4193,
"text": "aditya7409"
},
{
"code": null,
"e": 4222,
"s": 4204,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 4235,
"s": 4222,
"text": "simmytarika5"
},
{
"code": null,
"e": 4251,
"s": 4235,
"text": "subhammahato348"
},
{
"code": null,
"e": 4264,
"s": 4251,
"text": "Mathematical"
},
{
"code": null,
"e": 4271,
"s": 4264,
"text": "Matrix"
},
{
"code": null,
"e": 4284,
"s": 4271,
"text": "Mathematical"
},
{
"code": null,
"e": 4291,
"s": 4284,
"text": "Matrix"
}
] |
N-th root of a number - GeeksforGeeks
|
13 Jul, 2021
Given two numbers N and A, find N-th root of A. In mathematics, Nth root of a number A is a real number that gives A, when we raise it to integer power N. These roots are used in Number Theory and other advanced branches of mathematics. Refer Wiki page for more information. Examples:
Input : A = 81
N = 4
Output : 3
3^4 = 81
As this problem involves a real valued function A^(1/N) we can solve this using Newtonβs method, which starts with an initial guess and iteratively shift towards the result. We can derive a relation between two consecutive values of iteration using Newtonβs method as follows,
according to newtonβs method
x(K+1) = x(K) β f(x) / fβ(x)
here f(x) = x^(N) β A
so fβ(x) = N*x^(N - 1)
and x(K) denoted the value of x at Kth iteration
putting the values and simplifying we get,
x(K + 1) = (1 / N) * ((N - 1) * x(K) + A / x(K) ^ (N - 1))
Using above relation, we can solve the given problem. In below code we iterate over values of x, until difference between two consecutive values of x become lower than desired accuracy.Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to calculate Nth root of a number#include <bits/stdc++.h>using namespace std; // method returns Nth power of Adouble nthRoot(int A, int N){ // initially guessing a random number between // 0 and 9 double xPre = rand() % 10; // smaller eps, denotes more accuracy double eps = 1e-3; // initializing difference between two // roots by INT_MAX double delX = INT_MAX; // xK denotes current value of x double xK; // loop until we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + (double)A/pow(xPre, N-1)) / (double)N; delX = abs(xK - xPre); xPre = xK; } return xK;} // Driver code to test above methodsint main(){ int N = 4; int A = 81; double nthRootValue = nthRoot(A, N); cout << "Nth root is " << nthRootValue << endl; /* double Acalc = pow(nthRootValue, N); cout << "Error in difference of powers " << abs(A - Acalc) << endl; */ return 0;}
// Java program to calculate Nth root of a numberclass GFG{ // method returns Nth power of A static double nthRoot(int A, int N) { // initially guessing a random number between // 0 and 9 double xPre = Math.random() % 10; // smaller eps, denotes more accuracy double eps = 0.001; // initializing difference between two // roots by INT_MAX double delX = 2147483647; // xK denotes current value of x double xK = 0.0; // loop until we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + (double)A / Math.pow(xPre, N - 1)) / (double)N; delX = Math.abs(xK - xPre); xPre = xK; } return xK; } // Driver code public static void main (String[] args) { int N = 4; int A = 81; double nthRootValue = nthRoot(A, N); System.out.println("Nth root is " + Math.round(nthRootValue*1000.0)/1000.0); /* double Acalc = pow(nthRootValue, N); cout << "Error in difference of powers " << abs(A - Acalc) << endl; */ }} // This code is contributed by Anant Agarwal.
# Python3 program to calculate# Nth root of a numberimport mathimport random # method returns Nth power of Adef nthRoot(A,N): # initially guessing a random number between # 0 and 9 xPre = random.randint(1,101) % 10 # smaller eps, denotes more accuracy eps = 0.001 # initializing difference between two # roots by INT_MAX delX = 2147483647 # xK denotes current value of x xK=0.0 # loop until we reach desired accuracy while (delX > eps): # calculating current value from previous # value by newton's method xK = ((N - 1.0) * xPre + A/pow(xPre, N-1)) /N delX = abs(xK - xPre) xPre = xK; return xK # Driver codeN = 4A = 81nthRootValue = nthRoot(A, N) print("Nth root is ", nthRootValue) ## Acalc = pow(nthRootValue, N);## print("Error in difference of powers ",## abs(A - Acalc)) # This code is contributed# by Anant Agarwal.
// C# program to calculate Nth root of a numberusing System;class GFG{ // method returns Nth power of A static double nthRoot(int A, int N) { Random rand = new Random(); // initially guessing a random number between // 0 and 9 double xPre = rand.Next(10);; // smaller eps, denotes more accuracy double eps = 0.001; // initializing difference between two // roots by INT_MAX double delX = 2147483647; // xK denotes current value of x double xK = 0.0; // loop until we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + (double)A / Math.Pow(xPre, N - 1)) / (double)N; delX = Math.Abs(xK - xPre); xPre = xK; } return xK; } // Driver code static void Main() { int N = 4; int A = 81; double nthRootValue = nthRoot(A, N); Console.WriteLine("Nth root is "+Math.Round(nthRootValue*1000.0)/1000.0); }} // This code is contributed by mits
<?php// PHP program to calculate// Nth root of a number // method returns// Nth power of Afunction nthRoot($A, $N){ // initially guessing a // random number between // 0 and 9 $xPre = rand() % 10; // smaller eps, denotes // more accuracy $eps = 0.001; // initializing difference // between two roots by INT_MAX $delX = PHP_INT_MAX; // xK denotes current // value of x $xK; // loop until we reach // desired accuracy while ($delX > $eps) { // calculating current // value from previous // value by newton's method $xK = ((int)($N - 1.0) * $xPre + $A / (int)pow($xPre, $N - 1)) / $N; $delX = abs($xK - $xPre); $xPre = $xK; } return floor($xK);} // Driver code$N = 4;$A = 81; $nthRootValue = nthRoot($A, $N);echo "Nth root is " , $nthRootValue ,"\n"; // This code is contributed by akt_mit?>
<script> // Javascript program for the above approach // method returns Nth power of A function nthRoot(A, N) { // initially guessing a random number between // 0 and 9 let xPre = Math.random() % 10; // smaller eps, denotes more accuracy let eps = 0.001; // initializing difference between two // roots by INT_MAX let delX = 2147483647; // xK denotes current value of x let xK = 0.0; // loop until we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + A / Math.pow(xPre, N - 1)) / N; delX = Math.abs(xK - xPre); xPre = xK; } return xK; } // Driver Code let N = 4; let A = 81; let nthRootValue = nthRoot(A, N); document.write("Nth root is "+Math.round(nthRootValue*1000.0)/1000.0); </script>
Output:
Nth root is 3
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
Mithun Kumar
souravghosh0416
simranarora5sos
ruhelaa48
Accenture
Directi
Mathematical
Directi
Accenture
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Sieve of Eratosthenes
Program for Decimal to Binary Conversion
Program for factorial of a number
Operators in C / C++
The Knight's tour problem | Backtracking-1
|
[
{
"code": null,
"e": 24904,
"s": 24876,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 25191,
"s": 24904,
"text": "Given two numbers N and A, find N-th root of A. In mathematics, Nth root of a number A is a real number that gives A, when we raise it to integer power N. These roots are used in Number Theory and other advanced branches of mathematics. Refer Wiki page for more information. Examples: "
},
{
"code": null,
"e": 25241,
"s": 25191,
"text": "Input : A = 81\n N = 4\nOutput : 3 \n3^4 = 81"
},
{
"code": null,
"e": 25522,
"s": 25243,
"text": "As this problem involves a real valued function A^(1/N) we can solve this using Newtonβs method, which starts with an initial guess and iteratively shift towards the result. We can derive a relation between two consecutive values of iteration using Newtonβs method as follows, "
},
{
"code": null,
"e": 25795,
"s": 25522,
"text": "according to newtonβs method\nx(K+1) = x(K) β f(x) / fβ(x) \nhere f(x) = x^(N) β A\nso fβ(x) = N*x^(N - 1)\nand x(K) denoted the value of x at Kth iteration\nputting the values and simplifying we get,\nx(K + 1) = (1 / N) * ((N - 1) * x(K) + A / x(K) ^ (N - 1))"
},
{
"code": null,
"e": 26029,
"s": 25795,
"text": "Using above relation, we can solve the given problem. In below code we iterate over values of x, until difference between two consecutive values of x become lower than desired accuracy.Below is the implementation of above approach: "
},
{
"code": null,
"e": 26033,
"s": 26029,
"text": "C++"
},
{
"code": null,
"e": 26038,
"s": 26033,
"text": "Java"
},
{
"code": null,
"e": 26046,
"s": 26038,
"text": "Python3"
},
{
"code": null,
"e": 26049,
"s": 26046,
"text": "C#"
},
{
"code": null,
"e": 26053,
"s": 26049,
"text": "PHP"
},
{
"code": null,
"e": 26064,
"s": 26053,
"text": "Javascript"
},
{
"code": "// C++ program to calculate Nth root of a number#include <bits/stdc++.h>using namespace std; // method returns Nth power of Adouble nthRoot(int A, int N){ // initially guessing a random number between // 0 and 9 double xPre = rand() % 10; // smaller eps, denotes more accuracy double eps = 1e-3; // initializing difference between two // roots by INT_MAX double delX = INT_MAX; // xK denotes current value of x double xK; // loop until we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + (double)A/pow(xPre, N-1)) / (double)N; delX = abs(xK - xPre); xPre = xK; } return xK;} // Driver code to test above methodsint main(){ int N = 4; int A = 81; double nthRootValue = nthRoot(A, N); cout << \"Nth root is \" << nthRootValue << endl; /* double Acalc = pow(nthRootValue, N); cout << \"Error in difference of powers \" << abs(A - Acalc) << endl; */ return 0;}",
"e": 27164,
"s": 26064,
"text": null
},
{
"code": "// Java program to calculate Nth root of a numberclass GFG{ // method returns Nth power of A static double nthRoot(int A, int N) { // initially guessing a random number between // 0 and 9 double xPre = Math.random() % 10; // smaller eps, denotes more accuracy double eps = 0.001; // initializing difference between two // roots by INT_MAX double delX = 2147483647; // xK denotes current value of x double xK = 0.0; // loop until we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + (double)A / Math.pow(xPre, N - 1)) / (double)N; delX = Math.abs(xK - xPre); xPre = xK; } return xK; } // Driver code public static void main (String[] args) { int N = 4; int A = 81; double nthRootValue = nthRoot(A, N); System.out.println(\"Nth root is \" + Math.round(nthRootValue*1000.0)/1000.0); /* double Acalc = pow(nthRootValue, N); cout << \"Error in difference of powers \" << abs(A - Acalc) << endl; */ }} // This code is contributed by Anant Agarwal.",
"e": 28527,
"s": 27164,
"text": null
},
{
"code": "# Python3 program to calculate# Nth root of a numberimport mathimport random # method returns Nth power of Adef nthRoot(A,N): # initially guessing a random number between # 0 and 9 xPre = random.randint(1,101) % 10 # smaller eps, denotes more accuracy eps = 0.001 # initializing difference between two # roots by INT_MAX delX = 2147483647 # xK denotes current value of x xK=0.0 # loop until we reach desired accuracy while (delX > eps): # calculating current value from previous # value by newton's method xK = ((N - 1.0) * xPre + A/pow(xPre, N-1)) /N delX = abs(xK - xPre) xPre = xK; return xK # Driver codeN = 4A = 81nthRootValue = nthRoot(A, N) print(\"Nth root is \", nthRootValue) ## Acalc = pow(nthRootValue, N);## print(\"Error in difference of powers \",## abs(A - Acalc)) # This code is contributed# by Anant Agarwal.",
"e": 29471,
"s": 28527,
"text": null
},
{
"code": "// C# program to calculate Nth root of a numberusing System;class GFG{ // method returns Nth power of A static double nthRoot(int A, int N) { Random rand = new Random(); // initially guessing a random number between // 0 and 9 double xPre = rand.Next(10);; // smaller eps, denotes more accuracy double eps = 0.001; // initializing difference between two // roots by INT_MAX double delX = 2147483647; // xK denotes current value of x double xK = 0.0; // loop until we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + (double)A / Math.Pow(xPre, N - 1)) / (double)N; delX = Math.Abs(xK - xPre); xPre = xK; } return xK; } // Driver code static void Main() { int N = 4; int A = 81; double nthRootValue = nthRoot(A, N); Console.WriteLine(\"Nth root is \"+Math.Round(nthRootValue*1000.0)/1000.0); }} // This code is contributed by mits",
"e": 30659,
"s": 29471,
"text": null
},
{
"code": "<?php// PHP program to calculate// Nth root of a number // method returns// Nth power of Afunction nthRoot($A, $N){ // initially guessing a // random number between // 0 and 9 $xPre = rand() % 10; // smaller eps, denotes // more accuracy $eps = 0.001; // initializing difference // between two roots by INT_MAX $delX = PHP_INT_MAX; // xK denotes current // value of x $xK; // loop until we reach // desired accuracy while ($delX > $eps) { // calculating current // value from previous // value by newton's method $xK = ((int)($N - 1.0) * $xPre + $A / (int)pow($xPre, $N - 1)) / $N; $delX = abs($xK - $xPre); $xPre = $xK; } return floor($xK);} // Driver code$N = 4;$A = 81; $nthRootValue = nthRoot($A, $N);echo \"Nth root is \" , $nthRootValue ,\"\\n\"; // This code is contributed by akt_mit?>",
"e": 31626,
"s": 30659,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // method returns Nth power of A function nthRoot(A, N) { // initially guessing a random number between // 0 and 9 let xPre = Math.random() % 10; // smaller eps, denotes more accuracy let eps = 0.001; // initializing difference between two // roots by INT_MAX let delX = 2147483647; // xK denotes current value of x let xK = 0.0; // loop until we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + A / Math.pow(xPre, N - 1)) / N; delX = Math.abs(xK - xPre); xPre = xK; } return xK; } // Driver Code let N = 4; let A = 81; let nthRootValue = nthRoot(A, N); document.write(\"Nth root is \"+Math.round(nthRootValue*1000.0)/1000.0); </script>",
"e": 32694,
"s": 31626,
"text": null
},
{
"code": null,
"e": 32703,
"s": 32694,
"text": "Output: "
},
{
"code": null,
"e": 32717,
"s": 32703,
"text": "Nth root is 3"
},
{
"code": null,
"e": 33141,
"s": 32717,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 33147,
"s": 33141,
"text": "jit_t"
},
{
"code": null,
"e": 33160,
"s": 33147,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 33176,
"s": 33160,
"text": "souravghosh0416"
},
{
"code": null,
"e": 33192,
"s": 33176,
"text": "simranarora5sos"
},
{
"code": null,
"e": 33202,
"s": 33192,
"text": "ruhelaa48"
},
{
"code": null,
"e": 33212,
"s": 33202,
"text": "Accenture"
},
{
"code": null,
"e": 33220,
"s": 33212,
"text": "Directi"
},
{
"code": null,
"e": 33233,
"s": 33220,
"text": "Mathematical"
},
{
"code": null,
"e": 33241,
"s": 33233,
"text": "Directi"
},
{
"code": null,
"e": 33251,
"s": 33241,
"text": "Accenture"
},
{
"code": null,
"e": 33264,
"s": 33251,
"text": "Mathematical"
},
{
"code": null,
"e": 33362,
"s": 33264,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33386,
"s": 33362,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33428,
"s": 33386,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 33471,
"s": 33428,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33485,
"s": 33471,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33534,
"s": 33485,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33556,
"s": 33534,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 33597,
"s": 33556,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 33631,
"s": 33597,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 33652,
"s": 33631,
"text": "Operators in C / C++"
}
] |
Why should we use <noscript> element in JavaScript?
|
To find whether the browser supports JavaScript or not, use the <noscript> tag. The HTML <noscript> tag is used to handle the browsers, which do recognize <script> tag but do not support scripting. This tag is used to display an alternate text message.
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML noscript Tag</title>
</head>
<body>
<script>
<!--
document.write("Hello JavaScript!")
-->
</script>
<noscript>
Your browser does not support JavaScript!
</noscript>
</body>
</html>
|
[
{
"code": null,
"e": 1315,
"s": 1062,
"text": "To find whether the browser supports JavaScript or not, use the <noscript> tag. The HTML <noscript> tag is used to handle the browsers, which do recognize <script> tag but do not support scripting. This tag is used to display an alternate text message."
},
{
"code": null,
"e": 1325,
"s": 1315,
"text": "Live Demo"
},
{
"code": null,
"e": 1636,
"s": 1325,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML noscript Tag</title>\n </head>\n\n <body>\n <script>\n <!--\n document.write(\"Hello JavaScript!\")\n -->\n </script>\n \n <noscript>\n Your browser does not support JavaScript!\n </noscript>\n </body>\n</html>"
}
] |
BootStrap | Text Utilities (Alignment, Wrapping, Weight etc.) - GeeksforGeeks
|
15 Jan, 2019
Bootstrap is one of the most popular, open-source front-end frame work which helps us in developing responsive, mobile-first websites and web applications. As a part of its offering, bootstrap provides us a collection of classes, called the Text Utilities classes, which controls various text properties, such as, text alignment, text wrapping, text overflow, text transformation, font weight, italics, monospace, resetting color of text, removing text decorations.
Bootstrap breakpoints:
sm: Viewport greater than 576px.
md: Viewport greater than 768px.
lg: Viewport greater than 992px.
xl: Viewport greater than 1200px.
Let us now see the various classes:
Text Alignment:
text-justify: As the name suggest this class is used to set the text alignment to justified state.Example:<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-justify</h3> <!-- text-justify class --> <p class="text-justify"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-justify</h3> <!-- text-justify class --> <p class="text-justify"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
text-center: It sets the text alignment to center for all screen sizes.Example:<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-center</h3> <!-- text-center class --> <p class="text-center"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
Example:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-center</h3> <!-- text-center class --> <p class="text-center"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
text-left: It sets the text alignment to left for all screen sizes.Example:<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-left</h3> <!-- text-left class --> <p class="text-left"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
Example:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-left</h3> <!-- text-left class --> <p class="text-left"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
text-right: It sets the text alignment to right for all screen sizes.Example:<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-right</h3> <!-- text-left right --> <p class="text-right"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
Example:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-right</h3> <!-- text-left right --> <p class="text-right"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
text-(viewport)-(align): Bootstrap offers us a series of classes which can change the text alignment based on the viewport size.text-sm-left: It sets the text alignment to left on viewport of size greater than 576px(sm).text-md-left: It sets the text alignment to left on viewport of size greater than 768px(md).text-lg-left: It sets the text alignment to left on viewport of size greater than 992px(lg).text-xl-left: It sets the text alignment to left on viewport of size greater than 1200px(xl).text-sm-center: It sets the text alignment to center on viewport of size greater than 576px(sm).text-md-center: It sets the text alignment to center on viewport of size greater than 768px(md).text-lg-center: It sets the text alignment to center on viewport of size greater than 992px(lg).text-xl-center: It sets the text alignment to center on viewport of size greater than 1200px(xl).text-sm-right: It sets the text alignment to right on viewport of size greater than 576px(sm).text-md-right: It sets the text alignment to right on viewport of size greater than 768px(md).text-lg-right: It sets the text alignment to right on viewport of size greater than 992px(lg).text-xl-right: It sets the text alignment to right on viewport of size greater than 1200px(xl).Example: text-sm-right<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-sm-right</h3> <!-- text-sm-right --> <p class="text-sm-right"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:Note: You can combine text-(align) and text-(viewport)-(align) and also two different text-(viewport)-(align), to obtain different alignments according on different viewports. Like, you can use text-center and text-md-right, to get right text alignment when viewport on size is greater 768px(md), in smaller viewports the text will be center aligned.
text-sm-left: It sets the text alignment to left on viewport of size greater than 576px(sm).
text-md-left: It sets the text alignment to left on viewport of size greater than 768px(md).
text-lg-left: It sets the text alignment to left on viewport of size greater than 992px(lg).
text-xl-left: It sets the text alignment to left on viewport of size greater than 1200px(xl).
text-sm-center: It sets the text alignment to center on viewport of size greater than 576px(sm).
text-md-center: It sets the text alignment to center on viewport of size greater than 768px(md).
text-lg-center: It sets the text alignment to center on viewport of size greater than 992px(lg).
text-xl-center: It sets the text alignment to center on viewport of size greater than 1200px(xl).
text-sm-right: It sets the text alignment to right on viewport of size greater than 576px(sm).
text-md-right: It sets the text alignment to right on viewport of size greater than 768px(md).
text-lg-right: It sets the text alignment to right on viewport of size greater than 992px(lg).
text-xl-right: It sets the text alignment to right on viewport of size greater than 1200px(xl).
Example: text-sm-right
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-sm-right</h3> <!-- text-sm-right --> <p class="text-sm-right"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
Note: You can combine text-(align) and text-(viewport)-(align) and also two different text-(viewport)-(align), to obtain different alignments according on different viewports. Like, you can use text-center and text-md-right, to get right text alignment when viewport on size is greater 768px(md), in smaller viewports the text will be center aligned.
Text Wrapping
text-wrap: It sets text wrapping on the applied element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-wrap</h3> <!-- text-wrap --> <p class="text-wrap" style="width: 30rem;"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-wrap</h3> <!-- text-wrap --> <p class="text-wrap" style="width: 30rem;"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
text-nowrap: It removes text wrapping on the applied element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-nowrap</h3> <!-- text-nowrap --> <p class="text-nowrap" style="width: 30rem;"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-nowrap</h3> <!-- text-nowrap --> <p class="text-nowrap" style="width: 30rem;"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
text-truncate: It sets truncation on the applied element with ellipses.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-truncate</h3> <!-- text-truncate --> <p class="text-truncate" style="width: 30rem;"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-truncate</h3> <!-- text-truncate --> <p class="text-truncate" style="width: 30rem;"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
Font Weight and Italics
font-weight-bold: It is used to set font text to bold face.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-bold</h3> <!-- font-weight-bold --> <p class="font-weight-bold"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-bold</h3> <!-- font-weight-bold --> <p class="font-weight-bold"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
font-weight-bolder: It is used to set font weight bolder than its parent element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-bolder</h3> <!-- font-weight-bolder --> <p class="font-weight-bolder"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-bolder</h3> <!-- font-weight-bolder --> <p class="font-weight-bolder"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
font-weight-normal: It is used to set normal font weight.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-normal</h3> <!-- font-weight-normal --> <p class="font-weight-normal"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-normal</h3> <!-- font-weight-normal --> <p class="font-weight-normal"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
font-weight-light: It is used to set light font weight to the text.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-light</h3> <!-- font-weight-light --> <p class="font-weight-light"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-light</h3> <!-- font-weight-light --> <p class="font-weight-light"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
font-weight-lighter: It is used to set font weight lighter than its parent element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-lighter</h3> <!-- font-weight-lighter --> <p class="font-weight-lighter"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-weight-lighter</h3> <!-- font-weight-lighter --> <p class="font-weight-lighter"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
font-italics: It is used to set the style of the font to italics.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-italic</h3> <!-- font-italic --> <p class="font-italic"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>font-italic</h3> <!-- font-italic --> <p class="font-italic"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
Monospace:
text-monospace: It is used to change the text font to monospace.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-monospace</h3> <!-- text-monospace --> <p class="text-monospace"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-monospace</h3> <!-- text-monospace --> <p class="text-monospace"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
Reset Color:
text-reset: It is used to remove the font color from the text to font color inherited from its parent element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; color: blue; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-reset</h3> <!-- text-reset --> <p class="text-reset"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; color: blue; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-reset</h3> <!-- text-reset --> <p class="text-reset"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
Remove Text Decorations:
text-decoration-none: It is used to remove all the text decoration from the text.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; text-decoration: line-through; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-decoration-none</h3> <!-- text-decoration-none --> <p class="text-decoration-none"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>Output:
<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; text-decoration: line-through; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class="container"> <h1 class="text-center">GeeksForGeeks</h1> <h3>text-decoration-none</h3> <!-- text-decoration-none --> <p class="text-decoration-none"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body></html>
Output:
Picked
Technical Scripter 2018
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 24500,
"s": 24472,
"text": "\n15 Jan, 2019"
},
{
"code": null,
"e": 24966,
"s": 24500,
"text": "Bootstrap is one of the most popular, open-source front-end frame work which helps us in developing responsive, mobile-first websites and web applications. As a part of its offering, bootstrap provides us a collection of classes, called the Text Utilities classes, which controls various text properties, such as, text alignment, text wrapping, text overflow, text transformation, font weight, italics, monospace, resetting color of text, removing text decorations."
},
{
"code": null,
"e": 24989,
"s": 24966,
"text": "Bootstrap breakpoints:"
},
{
"code": null,
"e": 25022,
"s": 24989,
"text": "sm: Viewport greater than 576px."
},
{
"code": null,
"e": 25055,
"s": 25022,
"text": "md: Viewport greater than 768px."
},
{
"code": null,
"e": 25088,
"s": 25055,
"text": "lg: Viewport greater than 992px."
},
{
"code": null,
"e": 25122,
"s": 25088,
"text": "xl: Viewport greater than 1200px."
},
{
"code": null,
"e": 25158,
"s": 25122,
"text": "Let us now see the various classes:"
},
{
"code": null,
"e": 25174,
"s": 25158,
"text": "Text Alignment:"
},
{
"code": null,
"e": 27077,
"s": 25174,
"text": "text-justify: As the name suggest this class is used to set the text alignment to justified state.Example:<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-justify</h3> <!-- text-justify class --> <p class=\"text-justify\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-justify</h3> <!-- text-justify class --> <p class=\"text-justify\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 28867,
"s": 27077,
"text": null
},
{
"code": null,
"e": 28875,
"s": 28867,
"text": "Output:"
},
{
"code": null,
"e": 30732,
"s": 28875,
"text": "text-center: It sets the text alignment to center for all screen sizes.Example:<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-center</h3> <!-- text-center class --> <p class=\"text-center\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": null,
"e": 30741,
"s": 30732,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-center</h3> <!-- text-center class --> <p class=\"text-center\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 32512,
"s": 30741,
"text": null
},
{
"code": null,
"e": 32520,
"s": 32512,
"text": "Output:"
},
{
"code": null,
"e": 34367,
"s": 32520,
"text": "text-left: It sets the text alignment to left for all screen sizes.Example:<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-left</h3> <!-- text-left class --> <p class=\"text-left\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": null,
"e": 34376,
"s": 34367,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-left</h3> <!-- text-left class --> <p class=\"text-left\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 36141,
"s": 34376,
"text": null
},
{
"code": null,
"e": 36149,
"s": 36141,
"text": "Output:"
},
{
"code": null,
"e": 38000,
"s": 36149,
"text": "text-right: It sets the text alignment to right for all screen sizes.Example:<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-right</h3> <!-- text-left right --> <p class=\"text-right\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": null,
"e": 38009,
"s": 38000,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-right</h3> <!-- text-left right --> <p class=\"text-right\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 39776,
"s": 38009,
"text": null
},
{
"code": null,
"e": 39784,
"s": 39776,
"text": "Output:"
},
{
"code": null,
"e": 43193,
"s": 39784,
"text": "text-(viewport)-(align): Bootstrap offers us a series of classes which can change the text alignment based on the viewport size.text-sm-left: It sets the text alignment to left on viewport of size greater than 576px(sm).text-md-left: It sets the text alignment to left on viewport of size greater than 768px(md).text-lg-left: It sets the text alignment to left on viewport of size greater than 992px(lg).text-xl-left: It sets the text alignment to left on viewport of size greater than 1200px(xl).text-sm-center: It sets the text alignment to center on viewport of size greater than 576px(sm).text-md-center: It sets the text alignment to center on viewport of size greater than 768px(md).text-lg-center: It sets the text alignment to center on viewport of size greater than 992px(lg).text-xl-center: It sets the text alignment to center on viewport of size greater than 1200px(xl).text-sm-right: It sets the text alignment to right on viewport of size greater than 576px(sm).text-md-right: It sets the text alignment to right on viewport of size greater than 768px(md).text-lg-right: It sets the text alignment to right on viewport of size greater than 992px(lg).text-xl-right: It sets the text alignment to right on viewport of size greater than 1200px(xl).Example: text-sm-right<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-sm-right</h3> <!-- text-sm-right --> <p class=\"text-sm-right\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:Note: You can combine text-(align) and text-(viewport)-(align) and also two different text-(viewport)-(align), to obtain different alignments according on different viewports. Like, you can use text-center and text-md-right, to get right text alignment when viewport on size is greater 768px(md), in smaller viewports the text will be center aligned."
},
{
"code": null,
"e": 43286,
"s": 43193,
"text": "text-sm-left: It sets the text alignment to left on viewport of size greater than 576px(sm)."
},
{
"code": null,
"e": 43379,
"s": 43286,
"text": "text-md-left: It sets the text alignment to left on viewport of size greater than 768px(md)."
},
{
"code": null,
"e": 43472,
"s": 43379,
"text": "text-lg-left: It sets the text alignment to left on viewport of size greater than 992px(lg)."
},
{
"code": null,
"e": 43566,
"s": 43472,
"text": "text-xl-left: It sets the text alignment to left on viewport of size greater than 1200px(xl)."
},
{
"code": null,
"e": 43663,
"s": 43566,
"text": "text-sm-center: It sets the text alignment to center on viewport of size greater than 576px(sm)."
},
{
"code": null,
"e": 43760,
"s": 43663,
"text": "text-md-center: It sets the text alignment to center on viewport of size greater than 768px(md)."
},
{
"code": null,
"e": 43857,
"s": 43760,
"text": "text-lg-center: It sets the text alignment to center on viewport of size greater than 992px(lg)."
},
{
"code": null,
"e": 43955,
"s": 43857,
"text": "text-xl-center: It sets the text alignment to center on viewport of size greater than 1200px(xl)."
},
{
"code": null,
"e": 44050,
"s": 43955,
"text": "text-sm-right: It sets the text alignment to right on viewport of size greater than 576px(sm)."
},
{
"code": null,
"e": 44145,
"s": 44050,
"text": "text-md-right: It sets the text alignment to right on viewport of size greater than 768px(md)."
},
{
"code": null,
"e": 44240,
"s": 44145,
"text": "text-lg-right: It sets the text alignment to right on viewport of size greater than 992px(lg)."
},
{
"code": null,
"e": 44336,
"s": 44240,
"text": "text-xl-right: It sets the text alignment to right on viewport of size greater than 1200px(xl)."
},
{
"code": null,
"e": 44359,
"s": 44336,
"text": "Example: text-sm-right"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-sm-right</h3> <!-- text-sm-right --> <p class=\"text-sm-right\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 46130,
"s": 44359,
"text": null
},
{
"code": null,
"e": 46138,
"s": 46130,
"text": "Output:"
},
{
"code": null,
"e": 46489,
"s": 46138,
"text": "Note: You can combine text-(align) and text-(viewport)-(align) and also two different text-(viewport)-(align), to obtain different alignments according on different viewports. Like, you can use text-center and text-md-right, to get right text alignment when viewport on size is greater 768px(md), in smaller viewports the text will be center aligned."
},
{
"code": null,
"e": 46503,
"s": 46489,
"text": "Text Wrapping"
},
{
"code": null,
"e": 48347,
"s": 46503,
"text": "text-wrap: It sets text wrapping on the applied element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-wrap</h3> <!-- text-wrap --> <p class=\"text-wrap\" style=\"width: 30rem;\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-wrap</h3> <!-- text-wrap --> <p class=\"text-wrap\" style=\"width: 30rem;\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 50128,
"s": 48347,
"text": null
},
{
"code": null,
"e": 50136,
"s": 50128,
"text": "Output:"
},
{
"code": null,
"e": 51991,
"s": 50136,
"text": "text-nowrap: It removes text wrapping on the applied element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-nowrap</h3> <!-- text-nowrap --> <p class=\"text-nowrap\" style=\"width: 30rem;\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-nowrap</h3> <!-- text-nowrap --> <p class=\"text-nowrap\" style=\"width: 30rem;\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 53778,
"s": 51991,
"text": null
},
{
"code": null,
"e": 53786,
"s": 53778,
"text": "Output:"
},
{
"code": null,
"e": 55657,
"s": 53786,
"text": "text-truncate: It sets truncation on the applied element with ellipses.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-truncate</h3> <!-- text-truncate --> <p class=\"text-truncate\" style=\"width: 30rem;\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-truncate</h3> <!-- text-truncate --> <p class=\"text-truncate\" style=\"width: 30rem;\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 57450,
"s": 55657,
"text": null
},
{
"code": null,
"e": 57458,
"s": 57450,
"text": "Output:"
},
{
"code": null,
"e": 57482,
"s": 57458,
"text": "Font Weight and Italics"
},
{
"code": null,
"e": 59328,
"s": 57482,
"text": "font-weight-bold: It is used to set font text to bold face.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-bold</h3> <!-- font-weight-bold --> <p class=\"font-weight-bold\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-bold</h3> <!-- font-weight-bold --> <p class=\"font-weight-bold\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 61108,
"s": 59328,
"text": null
},
{
"code": null,
"e": 61116,
"s": 61108,
"text": "Output:"
},
{
"code": null,
"e": 62990,
"s": 61116,
"text": "font-weight-bolder: It is used to set font weight bolder than its parent element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-bolder</h3> <!-- font-weight-bolder --> <p class=\"font-weight-bolder\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-bolder</h3> <!-- font-weight-bolder --> <p class=\"font-weight-bolder\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 64776,
"s": 62990,
"text": null
},
{
"code": null,
"e": 64784,
"s": 64776,
"text": "Output:"
},
{
"code": null,
"e": 66634,
"s": 64784,
"text": "font-weight-normal: It is used to set normal font weight.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-normal</h3> <!-- font-weight-normal --> <p class=\"font-weight-normal\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-normal</h3> <!-- font-weight-normal --> <p class=\"font-weight-normal\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 68420,
"s": 66634,
"text": null
},
{
"code": null,
"e": 68428,
"s": 68420,
"text": "Output:"
},
{
"code": null,
"e": 70285,
"s": 68428,
"text": "font-weight-light: It is used to set light font weight to the text.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-light</h3> <!-- font-weight-light --> <p class=\"font-weight-light\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-light</h3> <!-- font-weight-light --> <p class=\"font-weight-light\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 72068,
"s": 70285,
"text": null
},
{
"code": null,
"e": 72076,
"s": 72068,
"text": "Output:"
},
{
"code": null,
"e": 73955,
"s": 72076,
"text": "font-weight-lighter: It is used to set font weight lighter than its parent element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-lighter</h3> <!-- font-weight-lighter --> <p class=\"font-weight-lighter\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-weight-lighter</h3> <!-- font-weight-lighter --> <p class=\"font-weight-lighter\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 75744,
"s": 73955,
"text": null
},
{
"code": null,
"e": 75752,
"s": 75744,
"text": "Output:"
},
{
"code": null,
"e": 77589,
"s": 75752,
"text": "font-italics: It is used to set the style of the font to italics.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-italic</h3> <!-- font-italic --> <p class=\"font-italic\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>font-italic</h3> <!-- font-italic --> <p class=\"font-italic\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 79354,
"s": 77589,
"text": null
},
{
"code": null,
"e": 79362,
"s": 79354,
"text": "Output:"
},
{
"code": null,
"e": 79373,
"s": 79362,
"text": "Monospace:"
},
{
"code": null,
"e": 81220,
"s": 79373,
"text": "text-monospace: It is used to change the text font to monospace.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-monospace</h3> <!-- text-monospace --> <p class=\"text-monospace\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-monospace</h3> <!-- text-monospace --> <p class=\"text-monospace\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 82996,
"s": 81220,
"text": null
},
{
"code": null,
"e": 83004,
"s": 82996,
"text": "Output:"
},
{
"code": null,
"e": 83017,
"s": 83004,
"text": "Reset Color:"
},
{
"code": null,
"e": 84916,
"s": 83017,
"text": "text-reset: It is used to remove the font color from the text to font color inherited from its parent element.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; color: blue; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-reset</h3> <!-- text-reset --> <p class=\"text-reset\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; color: blue; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-reset</h3> <!-- text-reset --> <p class=\"text-reset\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 86698,
"s": 84916,
"text": null
},
{
"code": null,
"e": 86706,
"s": 86698,
"text": "Output:"
},
{
"code": null,
"e": 86731,
"s": 86706,
"text": "Remove Text Decorations:"
},
{
"code": null,
"e": 88647,
"s": 86731,
"text": "text-decoration-none: It is used to remove all the text decoration from the text.<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; text-decoration: line-through; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-decoration-none</h3> <!-- text-decoration-none --> <p class=\"text-decoration-none\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Custom CSS --> <style> p{ border: 1px dashed black; text-decoration: line-through; } h1.text-center{ color: green; } </style> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap Text Utilities</title> </head> <body> <!-- Bootstrap class for making the enire div responsive --> <div class=\"container\"> <h1 class=\"text-center\">GeeksForGeeks</h1> <h3>text-decoration-none</h3> <!-- text-decoration-none --> <p class=\"text-decoration-none\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> <!-- Link JavaScript --> <!-- jQuery, Popper.js, Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 90475,
"s": 88647,
"text": null
},
{
"code": null,
"e": 90483,
"s": 90475,
"text": "Output:"
},
{
"code": null,
"e": 90490,
"s": 90483,
"text": "Picked"
},
{
"code": null,
"e": 90514,
"s": 90490,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 90533,
"s": 90514,
"text": "Technical Scripter"
},
{
"code": null,
"e": 90550,
"s": 90533,
"text": "Web Technologies"
},
{
"code": null,
"e": 90648,
"s": 90550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 90690,
"s": 90648,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 90752,
"s": 90690,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 90795,
"s": 90752,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 90828,
"s": 90795,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 90873,
"s": 90828,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 90923,
"s": 90873,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 90984,
"s": 90923,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 91053,
"s": 90984,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 91111,
"s": 91053,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
How to check Aadhaar number is valid or not using Regular Expression - GeeksforGeeks
|
31 Mar, 2022
Given string str, the task is to check whether the given string is a valid Aadhaar number or not by using Regular Expression. The valid Aadhaar number must satisfy the following conditions:
It should have 12 digits.It should not start with 0 and 1.It should not contain any alphabet and special characters.It should have white space after every 4 digits.
It should have 12 digits.
It should not start with 0 and 1.
It should not contain any alphabet and special characters.
It should have white space after every 4 digits.
Examples:
Input: str = β3675 9834 6012β Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid Aadhaar number.Input: str = β3675 9834 6012 8β Output: false Explanation: The given string contains 13 digits. Therefore, it is not a valid Aadhaar number.
Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer:
Get the String.
Create a regular expression to check valid Aadhaar number as mentioned below:
regex = β^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]{4}$β;
Where: ^ represents the starting of the string.[2-9]{1} represents the first digit should be any from 2-9.[0-9]{3} represents the next 3 digits after the first digit should be any digit from 0-9.\\s represents white space.[0-9]{4} represents the next 4 digits should be any from 0-9.\\s represents white space.[0-9]{4} represents the next 4 digits should be any from 0-9.$ represents the ending of the string.
^ represents the starting of the string.
[2-9]{1} represents the first digit should be any from 2-9.
[0-9]{3} represents the next 3 digits after the first digit should be any digit from 0-9.
\\s represents white space.
[0-9]{4} represents the next 4 digits should be any from 0-9.
\\s represents white space.
[0-9]{4} represents the next 4 digits should be any from 0-9.
$ represents the ending of the string.
Match the given string with the regular expression. In Java, this can be done by using Pattern.matcher().
Return true if the string matches with the given regular expression, else return false.
Below is the implementation of the above approach:
C++
Java
Python3
// C++ program to validate the// Aadhaar number using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the Aadhaar number.bool isValidAadhaarNumber(string str){ // Regex to check valid Aadhaar number. const regex pattern("^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]{4}$"); // If the Aadhaar number // is empty return false if (str.empty()) { return false; } // Return true if the Aadhaar number // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "3675 9834 6015"; cout << isValidAadhaarNumber(str1) << endl; // Test Case 2: string str2 = "4675 9834 6012 8"; cout << isValidAadhaarNumber(str2) << endl; // Test Case 3: string str3 = "0175 9834 6012"; cout << isValidAadhaarNumber(str3) << endl; // Test Case 4: string str4 = "3675 98AF 60#2"; cout << isValidAadhaarNumber(str4) << endl; // Test Case 5: string str5 = "417598346012"; cout << isValidAadhaarNumber(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra
// Java program to check valid// Aadhaar number using regex. import java.util.regex.*;class GFG { // Function to validate Aadhaar number. public static boolean isValidAadhaarNumber(String str) { // Regex to check valid Aadhaar number. String regex = "^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]{4}$"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() method // to find matching between given string // and regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = "3675 9834 6015"; System.out.println(isValidAadhaarNumber(str1)); // Test Case 2: String str2 = "4675 9834 6012 8"; System.out.println(isValidAadhaarNumber(str2)); // Test Case 3: String str3 = "0175 9834 6012"; System.out.println(isValidAadhaarNumber(str3)); // Test Case 4: String str4 = "3675 98AF 60#2"; System.out.println(isValidAadhaarNumber(str4)); // Test Case 5: String str5 = "417598346012"; System.out.println(isValidAadhaarNumber(str5)); }}
# Python3 program to validate# Aadhaar number using regex.import re # Function to validate Aadhaar# number.def isValidAadhaarNumber(str): # Regex to check valid # Aadhaar number. regex = ("^[2-9]{1}[0-9]{3}\\" + "s[0-9]{4}\\s[0-9]{4}$") # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = "3675 9834 6015"print(isValidAadhaarNumber(str1)) # Test Case 2:str2 = "4675 9834 6012 8"print(isValidAadhaarNumber(str2)) # Test Case 3:str3 = "0175 9834 6012"print(isValidAadhaarNumber(str3)) # Test Case 4:str4 = "3675 98AF 60#2"print(isValidAadhaarNumber(str4)) # Test Case 5:str5 = "417598346012"print(isValidAadhaarNumber(str5)) # This code is contributed by avanitrachhadiya2155
true
false
false
false
false
avanitrachhadiya2155
yuvraj_chandra
rkbhola5
CPP-regex
java-regular-expression
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Boyer Moore Algorithm for Pattern Searching
Check if an URL is valid or not using Regular Expression
Check if a string contains uppercase, lowercase, special characters and numeric values
How to check if string contains only digits in Java
Search a Word in a 2D Grid of characters
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 24970,
"s": 24942,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 25161,
"s": 24970,
"text": "Given string str, the task is to check whether the given string is a valid Aadhaar number or not by using Regular Expression. The valid Aadhaar number must satisfy the following conditions: "
},
{
"code": null,
"e": 25326,
"s": 25161,
"text": "It should have 12 digits.It should not start with 0 and 1.It should not contain any alphabet and special characters.It should have white space after every 4 digits."
},
{
"code": null,
"e": 25352,
"s": 25326,
"text": "It should have 12 digits."
},
{
"code": null,
"e": 25386,
"s": 25352,
"text": "It should not start with 0 and 1."
},
{
"code": null,
"e": 25445,
"s": 25386,
"text": "It should not contain any alphabet and special characters."
},
{
"code": null,
"e": 25494,
"s": 25445,
"text": "It should have white space after every 4 digits."
},
{
"code": null,
"e": 25505,
"s": 25494,
"text": "Examples: "
},
{
"code": null,
"e": 25806,
"s": 25505,
"text": "Input: str = β3675 9834 6012β Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid Aadhaar number.Input: str = β3675 9834 6012 8β Output: false Explanation: The given string contains 13 digits. Therefore, it is not a valid Aadhaar number. "
},
{
"code": null,
"e": 25937,
"s": 25806,
"text": "Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer: "
},
{
"code": null,
"e": 25953,
"s": 25937,
"text": "Get the String."
},
{
"code": null,
"e": 26031,
"s": 25953,
"text": "Create a regular expression to check valid Aadhaar number as mentioned below:"
},
{
"code": null,
"e": 26083,
"s": 26031,
"text": "regex = β^[2-9]{1}[0-9]{3}\\\\s[0-9]{4}\\\\s[0-9]{4}$β;"
},
{
"code": null,
"e": 26493,
"s": 26083,
"text": "Where: ^ represents the starting of the string.[2-9]{1} represents the first digit should be any from 2-9.[0-9]{3} represents the next 3 digits after the first digit should be any digit from 0-9.\\\\s represents white space.[0-9]{4} represents the next 4 digits should be any from 0-9.\\\\s represents white space.[0-9]{4} represents the next 4 digits should be any from 0-9.$ represents the ending of the string."
},
{
"code": null,
"e": 26534,
"s": 26493,
"text": "^ represents the starting of the string."
},
{
"code": null,
"e": 26594,
"s": 26534,
"text": "[2-9]{1} represents the first digit should be any from 2-9."
},
{
"code": null,
"e": 26684,
"s": 26594,
"text": "[0-9]{3} represents the next 3 digits after the first digit should be any digit from 0-9."
},
{
"code": null,
"e": 26712,
"s": 26684,
"text": "\\\\s represents white space."
},
{
"code": null,
"e": 26774,
"s": 26712,
"text": "[0-9]{4} represents the next 4 digits should be any from 0-9."
},
{
"code": null,
"e": 26802,
"s": 26774,
"text": "\\\\s represents white space."
},
{
"code": null,
"e": 26864,
"s": 26802,
"text": "[0-9]{4} represents the next 4 digits should be any from 0-9."
},
{
"code": null,
"e": 26903,
"s": 26864,
"text": "$ represents the ending of the string."
},
{
"code": null,
"e": 27009,
"s": 26903,
"text": "Match the given string with the regular expression. In Java, this can be done by using Pattern.matcher()."
},
{
"code": null,
"e": 27097,
"s": 27009,
"text": "Return true if the string matches with the given regular expression, else return false."
},
{
"code": null,
"e": 27149,
"s": 27097,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27153,
"s": 27149,
"text": "C++"
},
{
"code": null,
"e": 27158,
"s": 27153,
"text": "Java"
},
{
"code": null,
"e": 27166,
"s": 27158,
"text": "Python3"
},
{
"code": "// C++ program to validate the// Aadhaar number using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the Aadhaar number.bool isValidAadhaarNumber(string str){ // Regex to check valid Aadhaar number. const regex pattern(\"^[2-9]{1}[0-9]{3}\\\\s[0-9]{4}\\\\s[0-9]{4}$\"); // If the Aadhaar number // is empty return false if (str.empty()) { return false; } // Return true if the Aadhaar number // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"3675 9834 6015\"; cout << isValidAadhaarNumber(str1) << endl; // Test Case 2: string str2 = \"4675 9834 6012 8\"; cout << isValidAadhaarNumber(str2) << endl; // Test Case 3: string str3 = \"0175 9834 6012\"; cout << isValidAadhaarNumber(str3) << endl; // Test Case 4: string str4 = \"3675 98AF 60#2\"; cout << isValidAadhaarNumber(str4) << endl; // Test Case 5: string str5 = \"417598346012\"; cout << isValidAadhaarNumber(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra",
"e": 28286,
"s": 27166,
"text": null
},
{
"code": "// Java program to check valid// Aadhaar number using regex. import java.util.regex.*;class GFG { // Function to validate Aadhaar number. public static boolean isValidAadhaarNumber(String str) { // Regex to check valid Aadhaar number. String regex = \"^[2-9]{1}[0-9]{3}\\\\s[0-9]{4}\\\\s[0-9]{4}$\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() method // to find matching between given string // and regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = \"3675 9834 6015\"; System.out.println(isValidAadhaarNumber(str1)); // Test Case 2: String str2 = \"4675 9834 6012 8\"; System.out.println(isValidAadhaarNumber(str2)); // Test Case 3: String str3 = \"0175 9834 6012\"; System.out.println(isValidAadhaarNumber(str3)); // Test Case 4: String str4 = \"3675 98AF 60#2\"; System.out.println(isValidAadhaarNumber(str4)); // Test Case 5: String str5 = \"417598346012\"; System.out.println(isValidAadhaarNumber(str5)); }}",
"e": 29730,
"s": 28286,
"text": null
},
{
"code": "# Python3 program to validate# Aadhaar number using regex.import re # Function to validate Aadhaar# number.def isValidAadhaarNumber(str): # Regex to check valid # Aadhaar number. regex = (\"^[2-9]{1}[0-9]{3}\\\\\" + \"s[0-9]{4}\\\\s[0-9]{4}$\") # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = \"3675 9834 6015\"print(isValidAadhaarNumber(str1)) # Test Case 2:str2 = \"4675 9834 6012 8\"print(isValidAadhaarNumber(str2)) # Test Case 3:str3 = \"0175 9834 6012\"print(isValidAadhaarNumber(str3)) # Test Case 4:str4 = \"3675 98AF 60#2\"print(isValidAadhaarNumber(str4)) # Test Case 5:str5 = \"417598346012\"print(isValidAadhaarNumber(str5)) # This code is contributed by avanitrachhadiya2155",
"e": 30674,
"s": 29730,
"text": null
},
{
"code": null,
"e": 30703,
"s": 30674,
"text": "true\nfalse\nfalse\nfalse\nfalse"
},
{
"code": null,
"e": 30726,
"s": 30705,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 30741,
"s": 30726,
"text": "yuvraj_chandra"
},
{
"code": null,
"e": 30750,
"s": 30741,
"text": "rkbhola5"
},
{
"code": null,
"e": 30760,
"s": 30750,
"text": "CPP-regex"
},
{
"code": null,
"e": 30784,
"s": 30760,
"text": "java-regular-expression"
},
{
"code": null,
"e": 30802,
"s": 30784,
"text": "Pattern Searching"
},
{
"code": null,
"e": 30810,
"s": 30802,
"text": "Strings"
},
{
"code": null,
"e": 30818,
"s": 30810,
"text": "Strings"
},
{
"code": null,
"e": 30836,
"s": 30818,
"text": "Pattern Searching"
},
{
"code": null,
"e": 30934,
"s": 30836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30943,
"s": 30934,
"text": "Comments"
},
{
"code": null,
"e": 30956,
"s": 30943,
"text": "Old Comments"
},
{
"code": null,
"e": 31000,
"s": 30956,
"text": "Boyer Moore Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31057,
"s": 31000,
"text": "Check if an URL is valid or not using Regular Expression"
},
{
"code": null,
"e": 31144,
"s": 31057,
"text": "Check if a string contains uppercase, lowercase, special characters and numeric values"
},
{
"code": null,
"e": 31196,
"s": 31144,
"text": "How to check if string contains only digits in Java"
},
{
"code": null,
"e": 31237,
"s": 31196,
"text": "Search a Word in a 2D Grid of characters"
},
{
"code": null,
"e": 31262,
"s": 31237,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31308,
"s": 31262,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 31323,
"s": 31308,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31357,
"s": 31323,
"text": "Longest Common Subsequence | DP-4"
}
] |
OffsetDateTime of(LocalDateTime) method in Java with Examples - GeeksforGeeks
|
05 Jun, 2020
The of(LocalDateTime dateTime, ZoneOffset offset) method of the OffsetDateTime class in Java is used to create an instance of OffsetDateTime from given instances of date-time and offset. This method creates an OffsetDateTime with the specified local date-time and offset.
Syntax:
public static OffsetDateTime
of(LocalDateTime dateTime,
ZoneOffset offset)
Parameters: This method accepts two parameters:
dateTime β It represents the local date-time.
offset β It represents the zone offset.
Return value: This method returns the OffsetDateTime.
Exception: This method does not throw any exception.
Below programs illustrate the of(LocalDateTime, ZoneOffset) method of OffsetDateTime class in Java:
Program 1:
// Java program to demonstrate// OffsetDateTime of(LocalDateTime,// ZoneOffset) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDateTime object LocalDateTime dateTime = LocalDateTime.parse( "2020-05-28T04:12:50"); // Create OffsetDateTime object OffsetDateTime offsetdatetime = OffsetDateTime.of( dateTime, ZoneOffset.UTC); // Print date-time System.out.println("DATE-TIME: " + offsetdatetime); }}
DATE-TIME: 2020-05-28T04:12:50Z
Program 2:
// Java program to demonstrate// OffsetDateTime of(LocalDateTime,// ZoneOffset) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDateTime object LocalDateTime dateTime = LocalDateTime.of( 2020, 5, 28, 4, 12, 50); // Create OffsetDateTime object OffsetDateTime offsetdatetime = OffsetDateTime.of( dateTime, ZoneOffset.UTC); // Print date-time System.out.println("DATE-TIME: " + offsetdatetime); }}
DATE-TIME: 2020-05-28T04:12:50Z
References:https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html#of(java.time.LocalDateTime, java.time.ZoneOffset)
Java-Functions
Java-OffsetDateTime
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 24220,
"s": 23948,
"text": "The of(LocalDateTime dateTime, ZoneOffset offset) method of the OffsetDateTime class in Java is used to create an instance of OffsetDateTime from given instances of date-time and offset. This method creates an OffsetDateTime with the specified local date-time and offset."
},
{
"code": null,
"e": 24228,
"s": 24220,
"text": "Syntax:"
},
{
"code": null,
"e": 24321,
"s": 24228,
"text": "public static OffsetDateTime\n of(LocalDateTime dateTime,\n ZoneOffset offset)\n"
},
{
"code": null,
"e": 24369,
"s": 24321,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 24415,
"s": 24369,
"text": "dateTime β It represents the local date-time."
},
{
"code": null,
"e": 24455,
"s": 24415,
"text": "offset β It represents the zone offset."
},
{
"code": null,
"e": 24509,
"s": 24455,
"text": "Return value: This method returns the OffsetDateTime."
},
{
"code": null,
"e": 24562,
"s": 24509,
"text": "Exception: This method does not throw any exception."
},
{
"code": null,
"e": 24662,
"s": 24562,
"text": "Below programs illustrate the of(LocalDateTime, ZoneOffset) method of OffsetDateTime class in Java:"
},
{
"code": null,
"e": 24673,
"s": 24662,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// OffsetDateTime of(LocalDateTime,// ZoneOffset) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDateTime object LocalDateTime dateTime = LocalDateTime.parse( \"2020-05-28T04:12:50\"); // Create OffsetDateTime object OffsetDateTime offsetdatetime = OffsetDateTime.of( dateTime, ZoneOffset.UTC); // Print date-time System.out.println(\"DATE-TIME: \" + offsetdatetime); }}",
"e": 25290,
"s": 24673,
"text": null
},
{
"code": null,
"e": 25323,
"s": 25290,
"text": "DATE-TIME: 2020-05-28T04:12:50Z\n"
},
{
"code": null,
"e": 25334,
"s": 25323,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// OffsetDateTime of(LocalDateTime,// ZoneOffset) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDateTime object LocalDateTime dateTime = LocalDateTime.of( 2020, 5, 28, 4, 12, 50); // Create OffsetDateTime object OffsetDateTime offsetdatetime = OffsetDateTime.of( dateTime, ZoneOffset.UTC); // Print date-time System.out.println(\"DATE-TIME: \" + offsetdatetime); }}",
"e": 25949,
"s": 25334,
"text": null
},
{
"code": null,
"e": 25982,
"s": 25949,
"text": "DATE-TIME: 2020-05-28T04:12:50Z\n"
},
{
"code": null,
"e": 26116,
"s": 25982,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html#of(java.time.LocalDateTime, java.time.ZoneOffset)"
},
{
"code": null,
"e": 26131,
"s": 26116,
"text": "Java-Functions"
},
{
"code": null,
"e": 26151,
"s": 26131,
"text": "Java-OffsetDateTime"
},
{
"code": null,
"e": 26156,
"s": 26151,
"text": "Java"
},
{
"code": null,
"e": 26161,
"s": 26156,
"text": "Java"
},
{
"code": null,
"e": 26259,
"s": 26161,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26274,
"s": 26259,
"text": "Stream In Java"
},
{
"code": null,
"e": 26295,
"s": 26274,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26341,
"s": 26295,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26360,
"s": 26341,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26390,
"s": 26360,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26407,
"s": 26390,
"text": "Generics in Java"
},
{
"code": null,
"e": 26450,
"s": 26407,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26471,
"s": 26450,
"text": "Introduction to Java"
},
{
"code": null,
"e": 26500,
"s": 26471,
"text": "HashMap get() Method in Java"
}
] |
C++ continue statement
|
The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests.
The syntax of a continue statement in C++ is β
continue;
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
if( a == 15) {
// skip the iteration.
a = a + 1;
continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
}
while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result β
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2515,
"s": 2318,
"text": "The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between."
},
{
"code": null,
"e": 2702,
"s": 2515,
"text": "For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests."
},
{
"code": null,
"e": 2749,
"s": 2702,
"text": "The syntax of a continue statement in C++ is β"
},
{
"code": null,
"e": 2760,
"s": 2749,
"text": "continue;\n"
},
{
"code": null,
"e": 3102,
"s": 2760,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // Local variable declaration:\n int a = 10;\n\n // do loop execution\n do {\n if( a == 15) {\n // skip the iteration.\n a = a + 1;\n continue;\n }\n cout << \"value of a: \" << a << endl;\n a = a + 1;\n } \n while( a < 20 );\n \n return 0;\n}"
},
{
"code": null,
"e": 3183,
"s": 3102,
"text": "When the above code is compiled and executed, it produces the following result β"
},
{
"code": null,
"e": 3319,
"s": 3183,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n"
},
{
"code": null,
"e": 3356,
"s": 3319,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 3375,
"s": 3356,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3407,
"s": 3375,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 3430,
"s": 3407,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 3466,
"s": 3430,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3483,
"s": 3466,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3518,
"s": 3483,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3535,
"s": 3518,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3570,
"s": 3535,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3587,
"s": 3570,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3622,
"s": 3587,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3639,
"s": 3622,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3646,
"s": 3639,
"text": " Print"
},
{
"code": null,
"e": 3657,
"s": 3646,
"text": " Add Notes"
}
] |
How to Build Your Own Dataset of YouTube Comments | by William Yang | Towards Data Science
|
This is the first of a series of articles that will cover textual data collection, data preprocessing, and sentiment analysis. In this article specifically, I will talk about why I wanted to collect comments from Blackpinkβs latest music video, How You Like That, and then walk you through how you can build your own dataset of YouTube comments from any video you want.
If you would like to cut to the chase and start collecting comments immediately, you can follow the script at my repo:
github.com
Otherwise, letβs get started!
For this project, I was interested in analyzing YouTube comments on Blackpinkβs latest music video, βHow You Like Thatβ, released on June 26th, 2020.
By breaking records such as the most-viewed YouTube clip in 24 hours, most-viewed K-Pop act in 24 hours, and the fastest video to reach 200 million views, Blackpink has more than shown the world that it is a group to reckon with. However, prior to βHow You Like Thatβ, the groupβs last album Kill this Love was released more than a year ago on April 4th, 2019. Between then and June 26th 2020, only one more song, a collaboration with Lady Gaga called βSour Candyβ, was released. Now that Blackpink has graced its fans with more content featuring just themselves, I was interested in how BLINKs (the official fandom name for Blackpink) were responding to it.
What are fans saying about the four members and their agency, YG? What are their sentiments toward Blackpinkβs latest song and the individual members? Do these sentiments differ across languages?
These guiding questions motivated me to apply sentiment analysis on comments from their music video. I chose YouTube as a data source not only because it is a popular social media platform, but because it is also the second largest search engine, with 3 billion searches per month as of 2017. This makes it a valuable resource for entertainment companies to promote their artistsβ new singles and albums. In addition, since each video is accompanied by a comment section, these promotional videos also become a forum for fans to directly engage with artists and other fans.
Beyond those points, I also wanted to challenge myself with building and cleaning a dataset from scratch. I encourage you to do the same for the following reasons:
Exposure to web scraping and using APIs: knowing how to gather data will be incredibly useful for augmenting an existing dataset or creating a new one to address questions and hypotheses you may have about a topic.Greater customization over data: you have greater control over which features youβll include in your custom dataset, and you can change them up to fit your needs as you analyze your data.Practice data cleaning techniques: often times, publicly available datasets have been cleaned and pruned to some extent. Meanwhile, YouTube comments, and social media texts in general, are difficult to work with due to slang words, abbreviations, misspellings, emojis, and irony and sarcasm. Cleaning these types of texts will force you to consider the effectiveness and consequences of each technique.
Exposure to web scraping and using APIs: knowing how to gather data will be incredibly useful for augmenting an existing dataset or creating a new one to address questions and hypotheses you may have about a topic.
Greater customization over data: you have greater control over which features youβll include in your custom dataset, and you can change them up to fit your needs as you analyze your data.
Practice data cleaning techniques: often times, publicly available datasets have been cleaned and pruned to some extent. Meanwhile, YouTube comments, and social media texts in general, are difficult to work with due to slang words, abbreviations, misspellings, emojis, and irony and sarcasm. Cleaning these types of texts will force you to consider the effectiveness and consequences of each technique.
For this project, I chose to familiarize myself with APIs by querying comments through YouTubeβs Data API. The following sections will walk you through how I collected comments of interest. Some understanding of Python is assumed. Iβve also included a short introduction to APIs and JSON. If youβre already familiar with them, you can skip directly to the Data Collection section.
API is short for Application Programming Interface. Its role is to send requests from the user to a service provider, and then return the results generated by the service provider back to the user. Geeksforgeeks uses the example of searching for a hotel room on an online website; the API sends the request of the user to the hotel bookingβs website, and then returns the most relevant data from the website to the intended user. In that sense, APIs, especially those produced by large companies, offer tools for users to obtain data of interest.
According to w3schools, JSON, short for JavaScript Object Notation, is a lightweight format for storing and transporting data. JSON has very similar syntax to dictionaries in Python. JSON is denoted by curly braces, and its data is stored in key:value pairs separated by commas.
This data format is important to know since itβs the most common format for responses from APIs. For example, the response provided by the YouTube Data API is a JSON object.
1. Head over to Google Developerβs Console and create a new project.
2. Once youβve set up a new project, select + ENABLE APIS AND SERVICES
4. Search for YouTube Data API v3 and click on Enable.
5. Then return to Credentials. You can do so by clicking on the hamburger menu, β°
6. Select + CREATE CREDENTIALS, and then API Key.
According to the developer docs, we do not need user authorization to retrieve information about a public YouTube channel, so an API key is all weβll need to collect comments off a video.
7. Finally, install the Google API Client for Python.
pip install --upgrade google-api-python-client
If youβre curious, you can read more about setting up Google APIs with Python here:
developers.google.com
Once we have our credentials set up, we can now start collecting comments! Weβll first build the service for calling the YouTube API:
Now letβs take a look at the resource of interest. In order to obtain all YouTube comments on a specific video, weβll need to send a request for CommentThreads. An example request in Python for a commentThread will look like the following:
# you only need to build the service onceservice = build_service('path/to/apikey.json') response = service.commentThreads().list( part='snippet', maxResults=100, textFormat='plainText', order='time', videoId='ioNng23DkIM').execute()
Of the parameters listed above, there are two parameters that are required, part, and exactly one of allThreadsRelatedToChannelId, channelId, id, and videoId. For the part parameter, we need to pass a comma-separated list consisting of any combination of id, snippet, and replies. The snippet keyword will return basic details about the comment thread and the threadβs top-level comment, while replies contains a list of replies to the top level comment.
The second required parameter is a filter, and we can choose between allThreadsRelatedToChannelId, channelId, id, and videoId. Since I was interested in just the YouTube comments on Blackpinkβs How You Like That, I chose to filter by videoId.
A videoβs ID can be obtained from its YouTube link. They will generally look like this:
https://www.youtube.com/watch?v=ioNng23DkIM
The video ID in this case will be ioNng23DkIM. And in general, the video ID follows β?v=β.
But sometimes a link may look like the following, such as when you obtain a link through the share option on a video:
https://youtu.be/ioNng23DkIM
In that case, the ID will be directly after βyoutu.beβ.
We can handle both cases with the following function (although this is unnecessary if youβll be manually sourcing YouTube video links. If thatβs the case, you can just copy the ID part of the link.)
For this project, I was only interested in top level comments, the number of replies and likes, and whether the commenter also rated (liked) the video, so I passed just the string βsnippetβ to parameter part.
After running the code above, youβll get a JSON response that looks like this:
{ "kind": "youtube#commentThreadListResponse", "etag": etag, "nextPageToken": string, "pageInfo": { "totalResults": integer, "resultsPerPage": integer }, "items": [ commentThread Resource ]}
The items of interest are nextPageToken and items. Letβs talk about items first. The key items contains a list of commentThreads, and each commentThread consists of the following:
{ "kind": "youtube#commentThread", "etag": etag, "id": string, "snippet": { "channelId": string, "videoId": string, "topLevelComment": comments Resource, "canReply": boolean, "totalReplyCount": unsigned integer, "isPublic": boolean }, "replies": { "comments": [ comments Resource ] }}
Since I chose to pass only the string snippet to the part parameter, I will only get the snippet portion of the JSON resource above. The snippet is a dictionary containing keys and corresponding values for channelId, videoId, topLevelComment, canReply, totalReplyCount, and isPublic.
Among these resources, I chose to save the values of topLevelComment and totalReplyCount. However, we still have not accessed the actual text content of the topLevelComment. We can extract the text, the number of likes the top level comment has received, and whether the commenter has also rated the video by indexing into the topLevelComment object. It is a comment resource, which looks like this:
{ "kind": "youtube#comment", "etag": etag, "id": string, "snippet": { "authorDisplayName": string, "authorProfileImageUrl": string, "authorChannelUrl": string, "authorChannelId": { "value": string }, "channelId": string, "videoId": string, "textDisplay": string, "textOriginal": string, "parentId": string, "canRate": boolean, "viewerRating": string, "likeCount": unsigned integer, "moderationStatus": string, "publishedAt": datetime, "updatedAt": datetime }}
We can index into the response as follows:
comment = response['items']['snippet']['topLevelComment']['snippet']['textDisplay']
Putting it all together, we can use the code snippet below to get the data points of interest.
If youβre interested in additional data points, such as the time at which a comment was updated, you can write something like:
published_at = item['snippet']['topLevelComment']['snippet']['updatedAt']
The other value of interest for the commentThreads resource was the nextPageToken. Each time we submit a request, we get maxResults number of comments in the items list. The maximum number of results we can obtain is limited between 1 and 100. Thus, if a video has more than 100 comments, weβll need to make an API call several times. The nextPageToken helps us start directly on the next page of comments instead of starting from the beginning again. We just need to modify our API call a bit:
response = service.commentThreads().list( part='snippet', maxResults=100, textFormat='plainText', order='time', videoId='ioNng23DkIM', pageToken=response['nextPageToken']).execute()
Note that we donβt need a nextPageToken for our very first service call. Instead, we use the nextPageToken obtained from the current JSON response for our next call to the service object.
The function below will help us get comments off a YouTube video:
Feel free to change the function as you see fit! After importing the necessary libraries (#1), I changed the parameters of the function to include an extra variable, csv_filename (#2). Lists to hold features of interest, code to index for those data points, and code to save the data points to lists are outlined in #3, #5, and #6. I then saved the desired features of each item in the JSON response line-by-line to the csv file (#7). After we check every item in the JSON response, we check if thereβs a nextPageToken (#8). If not, weβll return our data points of interest in dictionary form (#9).
There is a lot more we can do to make this program more modular. For example, instead of hard-coding lists for each feature (#2, #5), we can write a function that takes in a list of keywords and returns a dictionary containing the relevant information for each given keyword. We can also write a dictionary that maps long, involved indexing such as the one for published_at to a shorthand. For example:
shorthand = { 'updated_at' : item['snippet']['topLevelComment']['snippet']['updatedAt']}
This will involve some work the first time around to simplify things down the line. Fortunately, these functions (and more) are already available in the wrapper library youtube-data-api.
However, if youβd like to just collect comments out-of-the-box, my repo contains instructions on how to run the provided script get_comments_of_video_id.py.
Note that Google does impose a daily quota on the number of API calls you can make. This quota is set at around 10 thousand units per day, which becomes more or less 250,000 comments I can collect in one day. To address these limitations, I created two API keys to collect more comments.
In this article, we took a look at how to collect YouTube comments from a video of interest using YouTube Data API (v3). In my next article, weβll follow the classical NLP pipeline to preprocess our data for sentiment analysis.
Thank you for following me on this data science journey!
|
[
{
"code": null,
"e": 541,
"s": 171,
"text": "This is the first of a series of articles that will cover textual data collection, data preprocessing, and sentiment analysis. In this article specifically, I will talk about why I wanted to collect comments from Blackpinkβs latest music video, How You Like That, and then walk you through how you can build your own dataset of YouTube comments from any video you want."
},
{
"code": null,
"e": 660,
"s": 541,
"text": "If you would like to cut to the chase and start collecting comments immediately, you can follow the script at my repo:"
},
{
"code": null,
"e": 671,
"s": 660,
"text": "github.com"
},
{
"code": null,
"e": 701,
"s": 671,
"text": "Otherwise, letβs get started!"
},
{
"code": null,
"e": 851,
"s": 701,
"text": "For this project, I was interested in analyzing YouTube comments on Blackpinkβs latest music video, βHow You Like Thatβ, released on June 26th, 2020."
},
{
"code": null,
"e": 1510,
"s": 851,
"text": "By breaking records such as the most-viewed YouTube clip in 24 hours, most-viewed K-Pop act in 24 hours, and the fastest video to reach 200 million views, Blackpink has more than shown the world that it is a group to reckon with. However, prior to βHow You Like Thatβ, the groupβs last album Kill this Love was released more than a year ago on April 4th, 2019. Between then and June 26th 2020, only one more song, a collaboration with Lady Gaga called βSour Candyβ, was released. Now that Blackpink has graced its fans with more content featuring just themselves, I was interested in how BLINKs (the official fandom name for Blackpink) were responding to it."
},
{
"code": null,
"e": 1706,
"s": 1510,
"text": "What are fans saying about the four members and their agency, YG? What are their sentiments toward Blackpinkβs latest song and the individual members? Do these sentiments differ across languages?"
},
{
"code": null,
"e": 2280,
"s": 1706,
"text": "These guiding questions motivated me to apply sentiment analysis on comments from their music video. I chose YouTube as a data source not only because it is a popular social media platform, but because it is also the second largest search engine, with 3 billion searches per month as of 2017. This makes it a valuable resource for entertainment companies to promote their artistsβ new singles and albums. In addition, since each video is accompanied by a comment section, these promotional videos also become a forum for fans to directly engage with artists and other fans."
},
{
"code": null,
"e": 2444,
"s": 2280,
"text": "Beyond those points, I also wanted to challenge myself with building and cleaning a dataset from scratch. I encourage you to do the same for the following reasons:"
},
{
"code": null,
"e": 3248,
"s": 2444,
"text": "Exposure to web scraping and using APIs: knowing how to gather data will be incredibly useful for augmenting an existing dataset or creating a new one to address questions and hypotheses you may have about a topic.Greater customization over data: you have greater control over which features youβll include in your custom dataset, and you can change them up to fit your needs as you analyze your data.Practice data cleaning techniques: often times, publicly available datasets have been cleaned and pruned to some extent. Meanwhile, YouTube comments, and social media texts in general, are difficult to work with due to slang words, abbreviations, misspellings, emojis, and irony and sarcasm. Cleaning these types of texts will force you to consider the effectiveness and consequences of each technique."
},
{
"code": null,
"e": 3463,
"s": 3248,
"text": "Exposure to web scraping and using APIs: knowing how to gather data will be incredibly useful for augmenting an existing dataset or creating a new one to address questions and hypotheses you may have about a topic."
},
{
"code": null,
"e": 3651,
"s": 3463,
"text": "Greater customization over data: you have greater control over which features youβll include in your custom dataset, and you can change them up to fit your needs as you analyze your data."
},
{
"code": null,
"e": 4054,
"s": 3651,
"text": "Practice data cleaning techniques: often times, publicly available datasets have been cleaned and pruned to some extent. Meanwhile, YouTube comments, and social media texts in general, are difficult to work with due to slang words, abbreviations, misspellings, emojis, and irony and sarcasm. Cleaning these types of texts will force you to consider the effectiveness and consequences of each technique."
},
{
"code": null,
"e": 4435,
"s": 4054,
"text": "For this project, I chose to familiarize myself with APIs by querying comments through YouTubeβs Data API. The following sections will walk you through how I collected comments of interest. Some understanding of Python is assumed. Iβve also included a short introduction to APIs and JSON. If youβre already familiar with them, you can skip directly to the Data Collection section."
},
{
"code": null,
"e": 4982,
"s": 4435,
"text": "API is short for Application Programming Interface. Its role is to send requests from the user to a service provider, and then return the results generated by the service provider back to the user. Geeksforgeeks uses the example of searching for a hotel room on an online website; the API sends the request of the user to the hotel bookingβs website, and then returns the most relevant data from the website to the intended user. In that sense, APIs, especially those produced by large companies, offer tools for users to obtain data of interest."
},
{
"code": null,
"e": 5261,
"s": 4982,
"text": "According to w3schools, JSON, short for JavaScript Object Notation, is a lightweight format for storing and transporting data. JSON has very similar syntax to dictionaries in Python. JSON is denoted by curly braces, and its data is stored in key:value pairs separated by commas."
},
{
"code": null,
"e": 5435,
"s": 5261,
"text": "This data format is important to know since itβs the most common format for responses from APIs. For example, the response provided by the YouTube Data API is a JSON object."
},
{
"code": null,
"e": 5504,
"s": 5435,
"text": "1. Head over to Google Developerβs Console and create a new project."
},
{
"code": null,
"e": 5575,
"s": 5504,
"text": "2. Once youβve set up a new project, select + ENABLE APIS AND SERVICES"
},
{
"code": null,
"e": 5630,
"s": 5575,
"text": "4. Search for YouTube Data API v3 and click on Enable."
},
{
"code": null,
"e": 5712,
"s": 5630,
"text": "5. Then return to Credentials. You can do so by clicking on the hamburger menu, β°"
},
{
"code": null,
"e": 5762,
"s": 5712,
"text": "6. Select + CREATE CREDENTIALS, and then API Key."
},
{
"code": null,
"e": 5950,
"s": 5762,
"text": "According to the developer docs, we do not need user authorization to retrieve information about a public YouTube channel, so an API key is all weβll need to collect comments off a video."
},
{
"code": null,
"e": 6004,
"s": 5950,
"text": "7. Finally, install the Google API Client for Python."
},
{
"code": null,
"e": 6051,
"s": 6004,
"text": "pip install --upgrade google-api-python-client"
},
{
"code": null,
"e": 6135,
"s": 6051,
"text": "If youβre curious, you can read more about setting up Google APIs with Python here:"
},
{
"code": null,
"e": 6157,
"s": 6135,
"text": "developers.google.com"
},
{
"code": null,
"e": 6291,
"s": 6157,
"text": "Once we have our credentials set up, we can now start collecting comments! Weβll first build the service for calling the YouTube API:"
},
{
"code": null,
"e": 6531,
"s": 6291,
"text": "Now letβs take a look at the resource of interest. In order to obtain all YouTube comments on a specific video, weβll need to send a request for CommentThreads. An example request in Python for a commentThread will look like the following:"
},
{
"code": null,
"e": 6799,
"s": 6531,
"text": "# you only need to build the service onceservice = build_service('path/to/apikey.json') response = service.commentThreads().list( part='snippet', maxResults=100, textFormat='plainText', order='time', videoId='ioNng23DkIM').execute()"
},
{
"code": null,
"e": 7254,
"s": 6799,
"text": "Of the parameters listed above, there are two parameters that are required, part, and exactly one of allThreadsRelatedToChannelId, channelId, id, and videoId. For the part parameter, we need to pass a comma-separated list consisting of any combination of id, snippet, and replies. The snippet keyword will return basic details about the comment thread and the threadβs top-level comment, while replies contains a list of replies to the top level comment."
},
{
"code": null,
"e": 7497,
"s": 7254,
"text": "The second required parameter is a filter, and we can choose between allThreadsRelatedToChannelId, channelId, id, and videoId. Since I was interested in just the YouTube comments on Blackpinkβs How You Like That, I chose to filter by videoId."
},
{
"code": null,
"e": 7585,
"s": 7497,
"text": "A videoβs ID can be obtained from its YouTube link. They will generally look like this:"
},
{
"code": null,
"e": 7629,
"s": 7585,
"text": "https://www.youtube.com/watch?v=ioNng23DkIM"
},
{
"code": null,
"e": 7720,
"s": 7629,
"text": "The video ID in this case will be ioNng23DkIM. And in general, the video ID follows β?v=β."
},
{
"code": null,
"e": 7838,
"s": 7720,
"text": "But sometimes a link may look like the following, such as when you obtain a link through the share option on a video:"
},
{
"code": null,
"e": 7867,
"s": 7838,
"text": "https://youtu.be/ioNng23DkIM"
},
{
"code": null,
"e": 7923,
"s": 7867,
"text": "In that case, the ID will be directly after βyoutu.beβ."
},
{
"code": null,
"e": 8122,
"s": 7923,
"text": "We can handle both cases with the following function (although this is unnecessary if youβll be manually sourcing YouTube video links. If thatβs the case, you can just copy the ID part of the link.)"
},
{
"code": null,
"e": 8331,
"s": 8122,
"text": "For this project, I was only interested in top level comments, the number of replies and likes, and whether the commenter also rated (liked) the video, so I passed just the string βsnippetβ to parameter part."
},
{
"code": null,
"e": 8410,
"s": 8331,
"text": "After running the code above, youβll get a JSON response that looks like this:"
},
{
"code": null,
"e": 8617,
"s": 8410,
"text": "{ \"kind\": \"youtube#commentThreadListResponse\", \"etag\": etag, \"nextPageToken\": string, \"pageInfo\": { \"totalResults\": integer, \"resultsPerPage\": integer }, \"items\": [ commentThread Resource ]}"
},
{
"code": null,
"e": 8797,
"s": 8617,
"text": "The items of interest are nextPageToken and items. Letβs talk about items first. The key items contains a list of commentThreads, and each commentThread consists of the following:"
},
{
"code": null,
"e": 9118,
"s": 8797,
"text": "{ \"kind\": \"youtube#commentThread\", \"etag\": etag, \"id\": string, \"snippet\": { \"channelId\": string, \"videoId\": string, \"topLevelComment\": comments Resource, \"canReply\": boolean, \"totalReplyCount\": unsigned integer, \"isPublic\": boolean }, \"replies\": { \"comments\": [ comments Resource ] }}"
},
{
"code": null,
"e": 9402,
"s": 9118,
"text": "Since I chose to pass only the string snippet to the part parameter, I will only get the snippet portion of the JSON resource above. The snippet is a dictionary containing keys and corresponding values for channelId, videoId, topLevelComment, canReply, totalReplyCount, and isPublic."
},
{
"code": null,
"e": 9802,
"s": 9402,
"text": "Among these resources, I chose to save the values of topLevelComment and totalReplyCount. However, we still have not accessed the actual text content of the topLevelComment. We can extract the text, the number of likes the top level comment has received, and whether the commenter has also rated the video by indexing into the topLevelComment object. It is a comment resource, which looks like this:"
},
{
"code": null,
"e": 10320,
"s": 9802,
"text": "{ \"kind\": \"youtube#comment\", \"etag\": etag, \"id\": string, \"snippet\": { \"authorDisplayName\": string, \"authorProfileImageUrl\": string, \"authorChannelUrl\": string, \"authorChannelId\": { \"value\": string }, \"channelId\": string, \"videoId\": string, \"textDisplay\": string, \"textOriginal\": string, \"parentId\": string, \"canRate\": boolean, \"viewerRating\": string, \"likeCount\": unsigned integer, \"moderationStatus\": string, \"publishedAt\": datetime, \"updatedAt\": datetime }}"
},
{
"code": null,
"e": 10363,
"s": 10320,
"text": "We can index into the response as follows:"
},
{
"code": null,
"e": 10447,
"s": 10363,
"text": "comment = response['items']['snippet']['topLevelComment']['snippet']['textDisplay']"
},
{
"code": null,
"e": 10542,
"s": 10447,
"text": "Putting it all together, we can use the code snippet below to get the data points of interest."
},
{
"code": null,
"e": 10669,
"s": 10542,
"text": "If youβre interested in additional data points, such as the time at which a comment was updated, you can write something like:"
},
{
"code": null,
"e": 10743,
"s": 10669,
"text": "published_at = item['snippet']['topLevelComment']['snippet']['updatedAt']"
},
{
"code": null,
"e": 11238,
"s": 10743,
"text": "The other value of interest for the commentThreads resource was the nextPageToken. Each time we submit a request, we get maxResults number of comments in the items list. The maximum number of results we can obtain is limited between 1 and 100. Thus, if a video has more than 100 comments, weβll need to make an API call several times. The nextPageToken helps us start directly on the next page of comments instead of starting from the beginning again. We just need to modify our API call a bit:"
},
{
"code": null,
"e": 11438,
"s": 11238,
"text": "response = service.commentThreads().list( part='snippet', maxResults=100, textFormat='plainText', order='time', videoId='ioNng23DkIM', pageToken=response['nextPageToken']).execute()"
},
{
"code": null,
"e": 11626,
"s": 11438,
"text": "Note that we donβt need a nextPageToken for our very first service call. Instead, we use the nextPageToken obtained from the current JSON response for our next call to the service object."
},
{
"code": null,
"e": 11692,
"s": 11626,
"text": "The function below will help us get comments off a YouTube video:"
},
{
"code": null,
"e": 12291,
"s": 11692,
"text": "Feel free to change the function as you see fit! After importing the necessary libraries (#1), I changed the parameters of the function to include an extra variable, csv_filename (#2). Lists to hold features of interest, code to index for those data points, and code to save the data points to lists are outlined in #3, #5, and #6. I then saved the desired features of each item in the JSON response line-by-line to the csv file (#7). After we check every item in the JSON response, we check if thereβs a nextPageToken (#8). If not, weβll return our data points of interest in dictionary form (#9)."
},
{
"code": null,
"e": 12694,
"s": 12291,
"text": "There is a lot more we can do to make this program more modular. For example, instead of hard-coding lists for each feature (#2, #5), we can write a function that takes in a list of keywords and returns a dictionary containing the relevant information for each given keyword. We can also write a dictionary that maps long, involved indexing such as the one for published_at to a shorthand. For example:"
},
{
"code": null,
"e": 12786,
"s": 12694,
"text": "shorthand = { 'updated_at' : item['snippet']['topLevelComment']['snippet']['updatedAt']}"
},
{
"code": null,
"e": 12973,
"s": 12786,
"text": "This will involve some work the first time around to simplify things down the line. Fortunately, these functions (and more) are already available in the wrapper library youtube-data-api."
},
{
"code": null,
"e": 13130,
"s": 12973,
"text": "However, if youβd like to just collect comments out-of-the-box, my repo contains instructions on how to run the provided script get_comments_of_video_id.py."
},
{
"code": null,
"e": 13418,
"s": 13130,
"text": "Note that Google does impose a daily quota on the number of API calls you can make. This quota is set at around 10 thousand units per day, which becomes more or less 250,000 comments I can collect in one day. To address these limitations, I created two API keys to collect more comments."
},
{
"code": null,
"e": 13646,
"s": 13418,
"text": "In this article, we took a look at how to collect YouTube comments from a video of interest using YouTube Data API (v3). In my next article, weβll follow the classical NLP pipeline to preprocess our data for sentiment analysis."
}
] |
Imbalanced Data β Oversampling Using Gaussian Mixture Models | by Bassel Karami | Towards Data Science
|
TL;DR β Drawing samples from Gaussian Mixture Models (GMM), or other generative models, is another creative oversampling technique that can potentially outperform SMOTE variants.
Introduction
Dataset preparation
Intro to GMM
Using GMM as an oversampling technique
Evaluation of performance metrics
Conclustion
In a previous article, I discuss how one can come up with many creative oversampling techniques that can outperform SMOTE variants. We saw how oversampling using βcrossoversβ outperformed SMOTE variants.
In this article, we will show how Gaussian Mixture Models (GMM), or generative model, can be used to oversample minority class instances in an imbalanced dataset.
We first generate an imablanced classification dataset using scikit-learnβs make_classification function with 5000 data points across two classes (binary classification). There is a 95% chance the target is 0 and a 5% chance the target is 1. We prepare a similar dataset to the previous article.
from sklearn.datasets import make_classificationimport seaborn as snsX, y = make_classification( n_samples=5000, n_classes=2, weights=[0.95, 0.05], flip_y=0)sns.countplot(y)plt.show()
By default 20 features are created, below is what a sample entry in our X array looks like.
Finally, we split the data into training and testing datasets.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y)
Gaussian mixture models (GMM) assume that there are a number of normally distributed subpopulations that the data comes from.
Example: Suppose we have data on the height of 10,000 individuals. Below is a sample distribution. It doesnβt look like a bell-shaped normal distribution.
However, it actually comes from 4 different groups of people with different average heights that are normally distributed. One group has an average height of 150 cm, the others have average heights of 160, 170, and 180 cm.
Below is the code used to generate the chart. You can see the 4 different groups out of which we generate 4000, 1000, 1000, and 4000 sample data respectively, totaling 10,000 sample individuals.
samples_150 = ss.norm(150, 10).rvs(4000)samples_160 = ss.norm(160, 10).rvs(1000)samples_170 = ss.norm(170, 10).rvs(1000)samples_180 = ss.norm(180, 10).rvs(4000)samples_total = np.hstack([samples_150, samples_160, samples_170, samples_180])plt.figure(figsize=(10, 5))ax = sns.distplot(samples_total)ax.set_xlabel("Height (in cm)")plt.show()
The height in each group is normally distributed.
plt.figure(figsize=(10, 5))ax = sns.distplot(samples_150)ax.set_xlabel("Height (in cm)")plt.show()
The idea behind GMM is that a dataset may have observations coming from different subpopulations that have their own characteristics. GMM helps in extracting the subpopulations from the data such that each subpopulation forms a cluster that we can use.
If we go back to the classification dataset we generated in the section βDataset Preparationβ, we can try to extract subpopulations/clusters from the data. Letβs extract 5 clusters for example.
gmm = GaussianMixture(5)gmm.fit(X_train)
That was it!
Under the hood, our GMM model has now created 5 different clusters with different normal distributions reflecting the feature values each cluster can take.
Below is an example showing the cluster mean values for each of the 20 features.
pd.DataFrame(gmm.means_.T)
More importantly, the GMM model can help us with 2 functions:
1- It can look at the feature values for a particular sample and assign the sample to a cluster.
gmm.predict(X_test)
2- It can use the fitted normal distributions to generate new samples which we can use for oversampling.
gmm.sample(5)
Finally, in this example, we are clustering our data into 5 different buckets, but our problem is a binary classification problem where our target variable can be either 0 or 1.
One idea is to check for the relationship between every cluster and the target (y) variable.
cluster_mean = pd.DataFrame(data={ "Cluster": gmm.predict(X_train), "Mean Target Variable (y)": y_train}).groupby("Cluster").mean().reset_index(drop=False)plt.figure(figsize=(10, 5))sns.barplot(data=cluster_mean, x="Cluster", y="Mean Target Variable (y)")plt.show()
We can see that Cluster 4 has the highest mean value for the target value at just over 40%.
Remember this is an imbalanced dataset where only 5% of the samples have a target variable (y) value = 1, so 40% is a large number.
The last step would be to generate random samples from the GMM model and only keep the ones which belong to Cluster 4. We can label them with a positive target variable (y=1).
samples, clusters = gmm.sample(100)samples_to_keep = samples[clusters==4]
We can finally add them to our training data!
We can similarly draw sample from the top 2β3 clusters that are most strongly associated with y=1. Or we can draw sample from any cluster where the mean value of y is above a predefined threshold.
When testing the performance of this oversampling technique we will use the below function which summarizes all the steps we discussed.
def oversample_gmm(X, y, rows_1, no_clusters=2, no_sampling_clusters=1, rs=1): # Instantiate GMM model gmm = GaussianMixture( no_clusters, covariance_type='tied', max_iter=10000, random_state=rs ) gmm.fit(X) # Finding cluster with y=1 most likely cluster_mean = pd.DataFrame(data={ "Cluster": gmm.predict(X_train), "Mean Target Variable (y)": y_train }).groupby("Cluster").mean().sort_values( by='Mean Target Variable (y)', ascending=False)top_clusters = cluster_mean.sort_values( by='Mean Target Variable (y)', ascending=False).index[ :no_sampling_clusters] # Number of rows we will generate before # filtering by required cluster. # Multiply by 5 to ensure we have sufficient samples rows_initial = rows_1 * no_clusters * 5 # Generate samples samples, clusters = gmm.sample(rows_initial)# Keep samples coming from clusters where y=1 is likely top_clusters_filter = [np.any([ cluster == x for x in top_clusters] ) for cluster in clusters] samples_to_keep = samples[top_clusters_filter] # Keep only required number of additional samples rows_required = rows_1 - np.sum(y) np.random.shuffle(samples_to_keep) samples_to_keep = samples_to_keep[:rows_required] # Add samples to training dataset X_gmm = np.vstack([X, samples_to_keep]) y_gmm = np.hstack([y, np.ones(samples_to_keep.shape[0])]) return X_gmm, y_gmm
Similar to our previous article, we iterate through 30 random states and compare the performance of a random forest classifier on the original dataset as well as the oversampling methods, ensuring we have 2000 training samples with a positive target value (target = 1):
Random oversampling
SMOTE β 1 neighbor
SMOTE β 3 neighbors
SMOTE β 5 neighbors
SMOTE β 10 neighbors
GMM β 2
GMM β 3
GMM β 5
GMM β 10
GMM β 15
We also look into 7 classification metrics:
ROC AUC β area under the ROC curve
PR AUC β area under the precision-recall curve
Balanced accuracy β this is also equivalent to macro-averaged recall across both labels
Max F1 β Maximum F1 score for different probability cutoffs (i.e. if we predict 1 when predicted probability > 0.2 or 0.3 etc. instead of the default 0.5)
Recall
Precision
F1 score
Below are the results...
There are mixed results of course.
GMM with 10 clusters is the best option when looking at the metrics that are arguably most relevant for imbalanced datasets: Precision-Recall curve, F1 score, and Max F1 (an alternative to F1 where we consider all probability thresholds).
Weβve demonstrated how another creative, yet simple, oversampling technique for imbalanced datasets can outperform default techniques such as SMOTE and random oversampling on several metrics.
The same GMM-based approach can also be used for generating synthetic data samples to regularize your predition model. This is particularly helpful in use cases where a lot of model/data drift is expected and cross-validation results are misleading.
That is a topic to discuss in a subsequent post...
|
[
{
"code": null,
"e": 350,
"s": 171,
"text": "TL;DR β Drawing samples from Gaussian Mixture Models (GMM), or other generative models, is another creative oversampling technique that can potentially outperform SMOTE variants."
},
{
"code": null,
"e": 363,
"s": 350,
"text": "Introduction"
},
{
"code": null,
"e": 383,
"s": 363,
"text": "Dataset preparation"
},
{
"code": null,
"e": 396,
"s": 383,
"text": "Intro to GMM"
},
{
"code": null,
"e": 435,
"s": 396,
"text": "Using GMM as an oversampling technique"
},
{
"code": null,
"e": 469,
"s": 435,
"text": "Evaluation of performance metrics"
},
{
"code": null,
"e": 481,
"s": 469,
"text": "Conclustion"
},
{
"code": null,
"e": 685,
"s": 481,
"text": "In a previous article, I discuss how one can come up with many creative oversampling techniques that can outperform SMOTE variants. We saw how oversampling using βcrossoversβ outperformed SMOTE variants."
},
{
"code": null,
"e": 848,
"s": 685,
"text": "In this article, we will show how Gaussian Mixture Models (GMM), or generative model, can be used to oversample minority class instances in an imbalanced dataset."
},
{
"code": null,
"e": 1144,
"s": 848,
"text": "We first generate an imablanced classification dataset using scikit-learnβs make_classification function with 5000 data points across two classes (binary classification). There is a 95% chance the target is 0 and a 5% chance the target is 1. We prepare a similar dataset to the previous article."
},
{
"code": null,
"e": 1335,
"s": 1144,
"text": "from sklearn.datasets import make_classificationimport seaborn as snsX, y = make_classification( n_samples=5000, n_classes=2, weights=[0.95, 0.05], flip_y=0)sns.countplot(y)plt.show()"
},
{
"code": null,
"e": 1427,
"s": 1335,
"text": "By default 20 features are created, below is what a sample entry in our X array looks like."
},
{
"code": null,
"e": 1490,
"s": 1427,
"text": "Finally, we split the data into training and testing datasets."
},
{
"code": null,
"e": 1600,
"s": 1490,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y)"
},
{
"code": null,
"e": 1726,
"s": 1600,
"text": "Gaussian mixture models (GMM) assume that there are a number of normally distributed subpopulations that the data comes from."
},
{
"code": null,
"e": 1881,
"s": 1726,
"text": "Example: Suppose we have data on the height of 10,000 individuals. Below is a sample distribution. It doesnβt look like a bell-shaped normal distribution."
},
{
"code": null,
"e": 2104,
"s": 1881,
"text": "However, it actually comes from 4 different groups of people with different average heights that are normally distributed. One group has an average height of 150 cm, the others have average heights of 160, 170, and 180 cm."
},
{
"code": null,
"e": 2299,
"s": 2104,
"text": "Below is the code used to generate the chart. You can see the 4 different groups out of which we generate 4000, 1000, 1000, and 4000 sample data respectively, totaling 10,000 sample individuals."
},
{
"code": null,
"e": 2664,
"s": 2299,
"text": "samples_150 = ss.norm(150, 10).rvs(4000)samples_160 = ss.norm(160, 10).rvs(1000)samples_170 = ss.norm(170, 10).rvs(1000)samples_180 = ss.norm(180, 10).rvs(4000)samples_total = np.hstack([samples_150, samples_160, samples_170, samples_180])plt.figure(figsize=(10, 5))ax = sns.distplot(samples_total)ax.set_xlabel(\"Height (in cm)\")plt.show()"
},
{
"code": null,
"e": 2714,
"s": 2664,
"text": "The height in each group is normally distributed."
},
{
"code": null,
"e": 2813,
"s": 2714,
"text": "plt.figure(figsize=(10, 5))ax = sns.distplot(samples_150)ax.set_xlabel(\"Height (in cm)\")plt.show()"
},
{
"code": null,
"e": 3066,
"s": 2813,
"text": "The idea behind GMM is that a dataset may have observations coming from different subpopulations that have their own characteristics. GMM helps in extracting the subpopulations from the data such that each subpopulation forms a cluster that we can use."
},
{
"code": null,
"e": 3260,
"s": 3066,
"text": "If we go back to the classification dataset we generated in the section βDataset Preparationβ, we can try to extract subpopulations/clusters from the data. Letβs extract 5 clusters for example."
},
{
"code": null,
"e": 3301,
"s": 3260,
"text": "gmm = GaussianMixture(5)gmm.fit(X_train)"
},
{
"code": null,
"e": 3314,
"s": 3301,
"text": "That was it!"
},
{
"code": null,
"e": 3470,
"s": 3314,
"text": "Under the hood, our GMM model has now created 5 different clusters with different normal distributions reflecting the feature values each cluster can take."
},
{
"code": null,
"e": 3551,
"s": 3470,
"text": "Below is an example showing the cluster mean values for each of the 20 features."
},
{
"code": null,
"e": 3578,
"s": 3551,
"text": "pd.DataFrame(gmm.means_.T)"
},
{
"code": null,
"e": 3640,
"s": 3578,
"text": "More importantly, the GMM model can help us with 2 functions:"
},
{
"code": null,
"e": 3737,
"s": 3640,
"text": "1- It can look at the feature values for a particular sample and assign the sample to a cluster."
},
{
"code": null,
"e": 3757,
"s": 3737,
"text": "gmm.predict(X_test)"
},
{
"code": null,
"e": 3862,
"s": 3757,
"text": "2- It can use the fitted normal distributions to generate new samples which we can use for oversampling."
},
{
"code": null,
"e": 3876,
"s": 3862,
"text": "gmm.sample(5)"
},
{
"code": null,
"e": 4054,
"s": 3876,
"text": "Finally, in this example, we are clustering our data into 5 different buckets, but our problem is a binary classification problem where our target variable can be either 0 or 1."
},
{
"code": null,
"e": 4147,
"s": 4054,
"text": "One idea is to check for the relationship between every cluster and the target (y) variable."
},
{
"code": null,
"e": 4425,
"s": 4147,
"text": "cluster_mean = pd.DataFrame(data={ \"Cluster\": gmm.predict(X_train), \"Mean Target Variable (y)\": y_train}).groupby(\"Cluster\").mean().reset_index(drop=False)plt.figure(figsize=(10, 5))sns.barplot(data=cluster_mean, x=\"Cluster\", y=\"Mean Target Variable (y)\")plt.show()"
},
{
"code": null,
"e": 4517,
"s": 4425,
"text": "We can see that Cluster 4 has the highest mean value for the target value at just over 40%."
},
{
"code": null,
"e": 4649,
"s": 4517,
"text": "Remember this is an imbalanced dataset where only 5% of the samples have a target variable (y) value = 1, so 40% is a large number."
},
{
"code": null,
"e": 4825,
"s": 4649,
"text": "The last step would be to generate random samples from the GMM model and only keep the ones which belong to Cluster 4. We can label them with a positive target variable (y=1)."
},
{
"code": null,
"e": 4899,
"s": 4825,
"text": "samples, clusters = gmm.sample(100)samples_to_keep = samples[clusters==4]"
},
{
"code": null,
"e": 4945,
"s": 4899,
"text": "We can finally add them to our training data!"
},
{
"code": null,
"e": 5142,
"s": 4945,
"text": "We can similarly draw sample from the top 2β3 clusters that are most strongly associated with y=1. Or we can draw sample from any cluster where the mean value of y is above a predefined threshold."
},
{
"code": null,
"e": 5278,
"s": 5142,
"text": "When testing the performance of this oversampling technique we will use the below function which summarizes all the steps we discussed."
},
{
"code": null,
"e": 6782,
"s": 5278,
"text": "def oversample_gmm(X, y, rows_1, no_clusters=2, no_sampling_clusters=1, rs=1): # Instantiate GMM model gmm = GaussianMixture( no_clusters, covariance_type='tied', max_iter=10000, random_state=rs ) gmm.fit(X) # Finding cluster with y=1 most likely cluster_mean = pd.DataFrame(data={ \"Cluster\": gmm.predict(X_train), \"Mean Target Variable (y)\": y_train }).groupby(\"Cluster\").mean().sort_values( by='Mean Target Variable (y)', ascending=False)top_clusters = cluster_mean.sort_values( by='Mean Target Variable (y)', ascending=False).index[ :no_sampling_clusters] # Number of rows we will generate before # filtering by required cluster. # Multiply by 5 to ensure we have sufficient samples rows_initial = rows_1 * no_clusters * 5 # Generate samples samples, clusters = gmm.sample(rows_initial)# Keep samples coming from clusters where y=1 is likely top_clusters_filter = [np.any([ cluster == x for x in top_clusters] ) for cluster in clusters] samples_to_keep = samples[top_clusters_filter] # Keep only required number of additional samples rows_required = rows_1 - np.sum(y) np.random.shuffle(samples_to_keep) samples_to_keep = samples_to_keep[:rows_required] # Add samples to training dataset X_gmm = np.vstack([X, samples_to_keep]) y_gmm = np.hstack([y, np.ones(samples_to_keep.shape[0])]) return X_gmm, y_gmm"
},
{
"code": null,
"e": 7052,
"s": 6782,
"text": "Similar to our previous article, we iterate through 30 random states and compare the performance of a random forest classifier on the original dataset as well as the oversampling methods, ensuring we have 2000 training samples with a positive target value (target = 1):"
},
{
"code": null,
"e": 7072,
"s": 7052,
"text": "Random oversampling"
},
{
"code": null,
"e": 7091,
"s": 7072,
"text": "SMOTE β 1 neighbor"
},
{
"code": null,
"e": 7111,
"s": 7091,
"text": "SMOTE β 3 neighbors"
},
{
"code": null,
"e": 7131,
"s": 7111,
"text": "SMOTE β 5 neighbors"
},
{
"code": null,
"e": 7152,
"s": 7131,
"text": "SMOTE β 10 neighbors"
},
{
"code": null,
"e": 7160,
"s": 7152,
"text": "GMM β 2"
},
{
"code": null,
"e": 7168,
"s": 7160,
"text": "GMM β 3"
},
{
"code": null,
"e": 7176,
"s": 7168,
"text": "GMM β 5"
},
{
"code": null,
"e": 7185,
"s": 7176,
"text": "GMM β 10"
},
{
"code": null,
"e": 7194,
"s": 7185,
"text": "GMM β 15"
},
{
"code": null,
"e": 7238,
"s": 7194,
"text": "We also look into 7 classification metrics:"
},
{
"code": null,
"e": 7273,
"s": 7238,
"text": "ROC AUC β area under the ROC curve"
},
{
"code": null,
"e": 7320,
"s": 7273,
"text": "PR AUC β area under the precision-recall curve"
},
{
"code": null,
"e": 7408,
"s": 7320,
"text": "Balanced accuracy β this is also equivalent to macro-averaged recall across both labels"
},
{
"code": null,
"e": 7563,
"s": 7408,
"text": "Max F1 β Maximum F1 score for different probability cutoffs (i.e. if we predict 1 when predicted probability > 0.2 or 0.3 etc. instead of the default 0.5)"
},
{
"code": null,
"e": 7570,
"s": 7563,
"text": "Recall"
},
{
"code": null,
"e": 7580,
"s": 7570,
"text": "Precision"
},
{
"code": null,
"e": 7589,
"s": 7580,
"text": "F1 score"
},
{
"code": null,
"e": 7614,
"s": 7589,
"text": "Below are the results..."
},
{
"code": null,
"e": 7649,
"s": 7614,
"text": "There are mixed results of course."
},
{
"code": null,
"e": 7888,
"s": 7649,
"text": "GMM with 10 clusters is the best option when looking at the metrics that are arguably most relevant for imbalanced datasets: Precision-Recall curve, F1 score, and Max F1 (an alternative to F1 where we consider all probability thresholds)."
},
{
"code": null,
"e": 8080,
"s": 7888,
"text": "Weβve demonstrated how another creative, yet simple, oversampling technique for imbalanced datasets can outperform default techniques such as SMOTE and random oversampling on several metrics."
},
{
"code": null,
"e": 8330,
"s": 8080,
"text": "The same GMM-based approach can also be used for generating synthetic data samples to regularize your predition model. This is particularly helpful in use cases where a lot of model/data drift is expected and cross-validation results are misleading."
}
] |
Virtual Background in webcam with Body Segmentation technique | by Benson Ruan | Towards Data Science
|
Have you ever had a moment when browsing those pretty travel selfies on social media, you talk to yourself: βI wish I could be thereβ? Guess what, we are going to make it come true today. With the latest technology of Person Segmentation, we can separate the body section with the background on a pixel level.
Very similar to the video conference software Zoomβs change background feature, which can hide the messy room behind you, and transport you to a deserted island or peaceful beach.
In this article, I will show you how to build a Selfie Anywhere app, which can put you inside those beautiful travel scenes by changing the background of a selfie in real-time. You donβt need Photoshop, and you donβt need a green screen neither. Letβs have some fun and count down β 3, 2, 1... Say cheeseβ !
Try it yourself, the demo is in the link below :
bensonruan.com
Did you take some selfies above and show that to your friends? I hope you like it, this app utilized an advanced technique called Body Segmentation, which can identify human being in an image or video stream, and segment the foreground body from the background.
Early this year, Google releases BodyPix, an open-source machine learning model which allows for person and body-part segmentation in the browser with TensorFlow.js. I was amazed by this technology, and come up with the idea of building the above Selfie Anywhere application. Follow me below for the journey of how I implemented it.
First of all, simply include the script Tensorflow.js and its body-pix model in the <head> section of the html file.
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.2"></script><script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix@2.0"></script>
Or you can install it via npm for use in a TypeScript / ES6 project
npm install @tensorflow-models/body-pix
To stream your webcam into the browser, I utilize the JavaScript library navigator.mediaDevices.getUserMedia. To find out more details about that, please refer to my previous article :
medium.com
In order to process segmentation, we first need to load the pre-trained BodyPix model, by calling the API of bodyPix.load(modelConfig). BodyPix comes with a few different versions of the model, with different performance characteristics trading off model size and prediction time with accuracy.
By default, BodyPix loads a MobileNetV1 architecture with a 0.75 multiplier. This is recommended for computers with mid-range/lower-end GPUs. A model with a 0.50 multiplier is recommended for mobile. The ResNet architecture is recommended for computers with even more powerful GPUs.
bodyPix.load({ architecture: 'MobileNetV1', outputStride: 16, multiplier: 0.75, quantBytes: 2})
Next, we start to feed the webcam stream through the body-pix model to perform person segmentation, by calling the API of net.estimatePersonSegmentation(video, outputStride, segmentationThreshold). It segments an image into pixels that are and arenβt part of a person. It returns a binary array with 1 for the pixels that are part of the person, and 0 otherwise. The array size corresponds to the number of pixels in the image.
net.segmentPerson(webcamElement, { flipHorizontal: true, internalResolution: 'medium', segmentationThreshold: 0.5 }) .then(personSegmentation => { if(personSegmentation!=null){ drawBody(personSegmentation); }});cameraFrame = requestAnimFrame(detectBody);
flipHorizontal defaults to false. If the segmentation & pose should be flipped/mirrored horizontally. This should be set to true for videos where the video is by default flipped horizontally (i.e. a webcam), and you want the segmentation & pose to be returned in the proper orientation.
segmentationThreshold is used to determining the minimum value a pixelβs score must have to be considered part of a person. In essence, a higher value will create a tighter crop around a person but may result in some pixels being that are part of a person being excluded from the returned segmentation mask.
It returns a Promise that resolves with a SemanticPersonSegmentation object. Multiple people in the image get merged into a single binary mask. In addition to width, height, and data fields, it returns a field allPoses which contains poses for all people. The data array for all people containing 307200 values, one for each pixel of the 640x480 image.
{ width: 640, height: 480, data: Uint8Array(307200) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, ...], allPoses: [{"score": 0.4, "keypoints": [...]}, ...]}
In the above function, we get the binary array to indicate pixels belong to body or not, now we can use it to remove the background, and only draw the body on a canvas. In an ImageData object, each pixel holds the values of red, green, blue, and alpha (transparency), the trick to remove the background is by setting the pixelβs transparency value to 0.
const canvasPerson = document.getElementById("canvasPerson");let contextPerson = canvasPerson.getContext('2d'); function drawBody(personSegmentation){ contextPerson.drawImage(camera, 0, 0, camera.width, camera.height); var imageData = contextPerson.getImageData(0,0, camera.width, camera.height); var pixel = imageData.data; for (var p = 0; p<pixel.length; p+=4) { if (personSegmentation.data[p/4] == 0) { pixel[p+3] = 0; } } contextPerson.imageSmoothingEnabled = true; contextPerson.putImageData(imageData,0,0);}
Once we had the canvas that only contains the body with a transparent background, then we just need to overlay it on top of a background image of the breathtaking nature scene.
<video id="webcam" autoplay playsinline width="640" height="480"></video><div id="selfie-container"> <div id="background-container"></div> <canvas id="canvasPerson" width="640" height="480"></canvas></div>
Applying css style below
#background-container { height: 100vh; width: 100vw; background-image: url(../images/greatwall.jpg); background-position: center center; background-repeat: no-repeat; background-size: cover; background-color: transparent;} #canvasPerson{ background-color: transparent; position: absolute; width: 100vw; height: auto; z-index: 9999; margin: auto; top: 0; bottom: 0; left: 0; right: 0; margin-left: auto; margin-right: auto; -moz-transform: scale(-1, 1); -webkit-transform: scale(-1, 1); -o-transform: scale(-1, 1); transform: scale(-1, 1); filter: FlipH;}
For taking the picture, I am using a 3rd party JavaScript library html2canvas.js. It allows you to take βscreenshotsβ of web pages or parts of it, directly on the users browser.
$("#take-photo").click(function () { beforeTakePhoto(); var captureElement= document.getElementById('selfie-container'); var appendElement= document.getElementById('webcam-container'); html2canvas(captureElement).then(function(canvas) { canvas.id='captureCanvas'; appendElement.appendChild(canvas); document.querySelector('#download-photo').href = canvas.toDataURL('image/png'); afterTakePhoto(); });});
Thatβs pretty much for the code! Other than that is just making the demo look nice. Choose one of those spectacular scenes, set your favorite pose and smile!
You can download the complete code of the above demo in the link below:
github.com
Advancements in instance segmentation technologies are now showing promise for many fields ranging from self-driving vehicles to medical diagnosis. With deep learning neural network, the models are now becoming more and more accurate. I hope this article is just the beginning of your journey to learn more about image segmentation and computer vision.
Thank you for reading. If you like this article, please share on Facebook or Twitter. Let me know in the comment if you have any questions. Follow me on GitHub and Linkedin.
|
[
{
"code": null,
"e": 482,
"s": 172,
"text": "Have you ever had a moment when browsing those pretty travel selfies on social media, you talk to yourself: βI wish I could be thereβ? Guess what, we are going to make it come true today. With the latest technology of Person Segmentation, we can separate the body section with the background on a pixel level."
},
{
"code": null,
"e": 662,
"s": 482,
"text": "Very similar to the video conference software Zoomβs change background feature, which can hide the messy room behind you, and transport you to a deserted island or peaceful beach."
},
{
"code": null,
"e": 970,
"s": 662,
"text": "In this article, I will show you how to build a Selfie Anywhere app, which can put you inside those beautiful travel scenes by changing the background of a selfie in real-time. You donβt need Photoshop, and you donβt need a green screen neither. Letβs have some fun and count down β 3, 2, 1... Say cheeseβ !"
},
{
"code": null,
"e": 1019,
"s": 970,
"text": "Try it yourself, the demo is in the link below :"
},
{
"code": null,
"e": 1034,
"s": 1019,
"text": "bensonruan.com"
},
{
"code": null,
"e": 1296,
"s": 1034,
"text": "Did you take some selfies above and show that to your friends? I hope you like it, this app utilized an advanced technique called Body Segmentation, which can identify human being in an image or video stream, and segment the foreground body from the background."
},
{
"code": null,
"e": 1629,
"s": 1296,
"text": "Early this year, Google releases BodyPix, an open-source machine learning model which allows for person and body-part segmentation in the browser with TensorFlow.js. I was amazed by this technology, and come up with the idea of building the above Selfie Anywhere application. Follow me below for the journey of how I implemented it."
},
{
"code": null,
"e": 1746,
"s": 1629,
"text": "First of all, simply include the script Tensorflow.js and its body-pix model in the <head> section of the html file."
},
{
"code": null,
"e": 1904,
"s": 1746,
"text": "<script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.2\"></script><script src=\"https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix@2.0\"></script>"
},
{
"code": null,
"e": 1972,
"s": 1904,
"text": "Or you can install it via npm for use in a TypeScript / ES6 project"
},
{
"code": null,
"e": 2012,
"s": 1972,
"text": "npm install @tensorflow-models/body-pix"
},
{
"code": null,
"e": 2197,
"s": 2012,
"text": "To stream your webcam into the browser, I utilize the JavaScript library navigator.mediaDevices.getUserMedia. To find out more details about that, please refer to my previous article :"
},
{
"code": null,
"e": 2208,
"s": 2197,
"text": "medium.com"
},
{
"code": null,
"e": 2503,
"s": 2208,
"text": "In order to process segmentation, we first need to load the pre-trained BodyPix model, by calling the API of bodyPix.load(modelConfig). BodyPix comes with a few different versions of the model, with different performance characteristics trading off model size and prediction time with accuracy."
},
{
"code": null,
"e": 2786,
"s": 2503,
"text": "By default, BodyPix loads a MobileNetV1 architecture with a 0.75 multiplier. This is recommended for computers with mid-range/lower-end GPUs. A model with a 0.50 multiplier is recommended for mobile. The ResNet architecture is recommended for computers with even more powerful GPUs."
},
{
"code": null,
"e": 2894,
"s": 2786,
"text": "bodyPix.load({ architecture: 'MobileNetV1', outputStride: 16, multiplier: 0.75, quantBytes: 2})"
},
{
"code": null,
"e": 3322,
"s": 2894,
"text": "Next, we start to feed the webcam stream through the body-pix model to perform person segmentation, by calling the API of net.estimatePersonSegmentation(video, outputStride, segmentationThreshold). It segments an image into pixels that are and arenβt part of a person. It returns a binary array with 1 for the pixels that are part of the person, and 0 otherwise. The array size corresponds to the number of pixels in the image."
},
{
"code": null,
"e": 3602,
"s": 3322,
"text": "net.segmentPerson(webcamElement, { flipHorizontal: true, internalResolution: 'medium', segmentationThreshold: 0.5 }) .then(personSegmentation => { if(personSegmentation!=null){ drawBody(personSegmentation); }});cameraFrame = requestAnimFrame(detectBody);"
},
{
"code": null,
"e": 3889,
"s": 3602,
"text": "flipHorizontal defaults to false. If the segmentation & pose should be flipped/mirrored horizontally. This should be set to true for videos where the video is by default flipped horizontally (i.e. a webcam), and you want the segmentation & pose to be returned in the proper orientation."
},
{
"code": null,
"e": 4197,
"s": 3889,
"text": "segmentationThreshold is used to determining the minimum value a pixelβs score must have to be considered part of a person. In essence, a higher value will create a tighter crop around a person but may result in some pixels being that are part of a person being excluded from the returned segmentation mask."
},
{
"code": null,
"e": 4550,
"s": 4197,
"text": "It returns a Promise that resolves with a SemanticPersonSegmentation object. Multiple people in the image get merged into a single binary mask. In addition to width, height, and data fields, it returns a field allPoses which contains poses for all people. The data array for all people containing 307200 values, one for each pixel of the 640x480 image."
},
{
"code": null,
"e": 4717,
"s": 4550,
"text": "{ width: 640, height: 480, data: Uint8Array(307200) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, ...], allPoses: [{\"score\": 0.4, \"keypoints\": [...]}, ...]}"
},
{
"code": null,
"e": 5071,
"s": 4717,
"text": "In the above function, we get the binary array to indicate pixels belong to body or not, now we can use it to remove the background, and only draw the body on a canvas. In an ImageData object, each pixel holds the values of red, green, blue, and alpha (transparency), the trick to remove the background is by setting the pixelβs transparency value to 0."
},
{
"code": null,
"e": 5628,
"s": 5071,
"text": "const canvasPerson = document.getElementById(\"canvasPerson\");let contextPerson = canvasPerson.getContext('2d'); function drawBody(personSegmentation){ contextPerson.drawImage(camera, 0, 0, camera.width, camera.height); var imageData = contextPerson.getImageData(0,0, camera.width, camera.height); var pixel = imageData.data; for (var p = 0; p<pixel.length; p+=4) { if (personSegmentation.data[p/4] == 0) { pixel[p+3] = 0; } } contextPerson.imageSmoothingEnabled = true; contextPerson.putImageData(imageData,0,0);}"
},
{
"code": null,
"e": 5805,
"s": 5628,
"text": "Once we had the canvas that only contains the body with a transparent background, then we just need to overlay it on top of a background image of the breathtaking nature scene."
},
{
"code": null,
"e": 6017,
"s": 5805,
"text": "<video id=\"webcam\" autoplay playsinline width=\"640\" height=\"480\"></video><div id=\"selfie-container\"> <div id=\"background-container\"></div> <canvas id=\"canvasPerson\" width=\"640\" height=\"480\"></canvas></div>"
},
{
"code": null,
"e": 6042,
"s": 6017,
"text": "Applying css style below"
},
{
"code": null,
"e": 6618,
"s": 6042,
"text": "#background-container { height: 100vh; width: 100vw; background-image: url(../images/greatwall.jpg); background-position: center center; background-repeat: no-repeat; background-size: cover; background-color: transparent;} #canvasPerson{ background-color: transparent; position: absolute; width: 100vw; height: auto; z-index: 9999; margin: auto; top: 0; bottom: 0; left: 0; right: 0; margin-left: auto; margin-right: auto; -moz-transform: scale(-1, 1); -webkit-transform: scale(-1, 1); -o-transform: scale(-1, 1); transform: scale(-1, 1); filter: FlipH;}"
},
{
"code": null,
"e": 6796,
"s": 6618,
"text": "For taking the picture, I am using a 3rd party JavaScript library html2canvas.js. It allows you to take βscreenshotsβ of web pages or parts of it, directly on the users browser."
},
{
"code": null,
"e": 7243,
"s": 6796,
"text": "$(\"#take-photo\").click(function () { beforeTakePhoto(); var captureElement= document.getElementById('selfie-container'); var appendElement= document.getElementById('webcam-container'); html2canvas(captureElement).then(function(canvas) { canvas.id='captureCanvas'; appendElement.appendChild(canvas); document.querySelector('#download-photo').href = canvas.toDataURL('image/png'); afterTakePhoto(); });});"
},
{
"code": null,
"e": 7401,
"s": 7243,
"text": "Thatβs pretty much for the code! Other than that is just making the demo look nice. Choose one of those spectacular scenes, set your favorite pose and smile!"
},
{
"code": null,
"e": 7473,
"s": 7401,
"text": "You can download the complete code of the above demo in the link below:"
},
{
"code": null,
"e": 7484,
"s": 7473,
"text": "github.com"
},
{
"code": null,
"e": 7837,
"s": 7484,
"text": "Advancements in instance segmentation technologies are now showing promise for many fields ranging from self-driving vehicles to medical diagnosis. With deep learning neural network, the models are now becoming more and more accurate. I hope this article is just the beginning of your journey to learn more about image segmentation and computer vision."
}
] |
Image Processing with Python β Working with Entropy | by Tonichi Edeza | Towards Data Science
|
Apart from segregating objects based on their colors, another way to segregate objects is via their textures. To do this we can make use of the entropy function in Skimage. In this article we shall learn how to use the function to effectively extract objects of interest in our image.
Letβs begin!
As always, start by importing the required Python libraries.
import matplotlib.pyplot as pltimport numpy as npfrom skimage.io import imread, imshowfrom skimage import datafrom skimage.util import img_as_ubytefrom skimage.filters.rank import entropyfrom skimage.morphology import diskfrom skimage.color import rgb2hsv, rgb2gray, rgb2yuv
Now let us import the image we will be working with.
shawls = imread('shawls.PNG')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(shawls);
The above image has shawls of varying prints and textures. Let us try to see if we can segregate them based on these features. As a start let us first convert our image to grayscale.
shawl_gray = rgb2gray(imread('shawls.PNG'))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(shawl_gray);
Excellent, from this point we can now apply the entropy function of Skimage.
entropy_image = entropy(shawl_gray, disk(5))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(entropy_image, cmap = 'magma');
In a nutshell, the entropy function gives a value that represents level of complexity in a certain section of an image. The resulting values are of course subject to the initial structuring element we chose. As an example let us experiment by changing the initial radius of the disk.
def disk_iterations(image): image_gray = rgb2gray(image) f_size = 20 radi = list(range(1,10)) fig, ax = plt.subplots(3,3,figsize=(15,15)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'Radius at {radi[n]}', fontsize = f_size) ax.imshow(entropy(shawl_gray, disk(radi[n])), cmap = 'magma'); ax.set_axis_off() fig.tight_layout()
We can see that the image becomes increasingly blurry if we increase the disk radius. As the goal of this exercise is to segment the image based on texture, we do not need a size that may include portions of a differently textured image. Let us choose a radius of 6 as it seems to be a good balance between the sharpness of 1 and the dullness of 9.
Our next task is to then turn this into a mask. To do this let us use image binarization. The below code will iterate over several thresholds.
def threshold_checker(image): thresholds = np.arange(0.1,1.1,0.1) image_gray = rgb2gray(image) entropy_image = entropy(image_gray, disk(6)) scaled_entropy = entropy_image / entropy_image.max() fig, ax = plt.subplots(2, 5, figsize=(17, 10)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'Threshold : {round(thresholds[n],2)}', fontsize = 16) threshold = scaled_entropy > thresholds[n] ax.imshow(threshold, cmap = 'gist_stern_r') ; ax.axis('off') fig.tight_layout()
We can see that increasing the threshold for binarization decreases how much of the image is shown. Intuitively this makes sense as once the threshold is equal to 1, there is no part of the image that can match that level of entropy.
For visualization purposes let us set the threshold equal to 0.8 and see what happens when we use it as a mask for our image.
scaled_entropy = shawl_gray / shawl_gray.max()entropy_image = entropy(scaled_entropy, disk(6))scaled_entropy = entropy_image / entropy_image.max()mask = scaled_entropy > 0.8plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(shawl_gray * mask, cmap = 'gray');
As expected, see that only objects that breach a level of entropy were able to be rendered. If we flip the mathematical operator we can see the opposite effect.
Notice how only low entropy objects have been rendered. To aid in visualization let us convert both these masks to their original colored image and compare them side by side.
def entropy_mask_viz(image): image_gray = rgb2gray(image) entropy_image = entropy(image_gray, disk(6)) scaled_entropy = entropy_image / entropy_image.max() f_size = 24 fig, ax = plt.subplots(1, 2, figsize=(17, 10)) ax[0].set_title('Greater Than Threshold', fontsize = f_size) threshold = scaled_entropy > 0.8 image_a = np.dstack([image[:,:,0]*threshold, image[:,:,1]*threshold, image[:,:,2]*threshold]) ax[0].imshow(image_a) ax[0].axis('off') ax[1].set_title('Less Than Threshold', fontsize = f_size) threshold = scaled_entropy < 0.8 image_b = np.dstack([image[:,:,0]*threshold, image[:,:,1]*threshold, image[:,:,2]*threshold]) ax[1].imshow(image_b) ax[1].axis('off') fig.tight_layout() return [image_a, image_b]entropic_images = entropy_mask_viz(shawls)
We can see that we were able to successfully split the figures by the level of complexity of the objects. The objects on the left image exhibit far more intricate design patterns (as well as being made of fabrics with more complex textures). The objects on the right image are far more plain and contain only one color.
An interesting note is how we were able to separate the text from the sheet of paper it was written on.
This is useful to keep in mind. Human texts tend to be written on plain backgrounds to facilitate reading. Knowing this means that it is possible to extract all text features from an image, but this is a task we shall reserve for another time.
In Conclusion
Entropy masking is a useful technique that can help data scientists segment portions of an image by complexity. The applications range from texture analysis, image filtering, and even text extraction (a feature that can lend itself well to Natural Language Processing). I hope that after reading this article you have a better appreciation and understanding of how to use this tool.
|
[
{
"code": null,
"e": 457,
"s": 172,
"text": "Apart from segregating objects based on their colors, another way to segregate objects is via their textures. To do this we can make use of the entropy function in Skimage. In this article we shall learn how to use the function to effectively extract objects of interest in our image."
},
{
"code": null,
"e": 470,
"s": 457,
"text": "Letβs begin!"
},
{
"code": null,
"e": 531,
"s": 470,
"text": "As always, start by importing the required Python libraries."
},
{
"code": null,
"e": 806,
"s": 531,
"text": "import matplotlib.pyplot as pltimport numpy as npfrom skimage.io import imread, imshowfrom skimage import datafrom skimage.util import img_as_ubytefrom skimage.filters.rank import entropyfrom skimage.morphology import diskfrom skimage.color import rgb2hsv, rgb2gray, rgb2yuv"
},
{
"code": null,
"e": 859,
"s": 806,
"text": "Now let us import the image we will be working with."
},
{
"code": null,
"e": 948,
"s": 859,
"text": "shawls = imread('shawls.PNG')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(shawls);"
},
{
"code": null,
"e": 1131,
"s": 948,
"text": "The above image has shawls of varying prints and textures. Let us try to see if we can segregate them based on these features. As a start let us first convert our image to grayscale."
},
{
"code": null,
"e": 1238,
"s": 1131,
"text": "shawl_gray = rgb2gray(imread('shawls.PNG'))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(shawl_gray);"
},
{
"code": null,
"e": 1315,
"s": 1238,
"text": "Excellent, from this point we can now apply the entropy function of Skimage."
},
{
"code": null,
"e": 1442,
"s": 1315,
"text": "entropy_image = entropy(shawl_gray, disk(5))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(entropy_image, cmap = 'magma');"
},
{
"code": null,
"e": 1726,
"s": 1442,
"text": "In a nutshell, the entropy function gives a value that represents level of complexity in a certain section of an image. The resulting values are of course subject to the initial structuring element we chose. As an example let us experiment by changing the initial radius of the disk."
},
{
"code": null,
"e": 2115,
"s": 1726,
"text": "def disk_iterations(image): image_gray = rgb2gray(image) f_size = 20 radi = list(range(1,10)) fig, ax = plt.subplots(3,3,figsize=(15,15)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'Radius at {radi[n]}', fontsize = f_size) ax.imshow(entropy(shawl_gray, disk(radi[n])), cmap = 'magma'); ax.set_axis_off() fig.tight_layout()"
},
{
"code": null,
"e": 2464,
"s": 2115,
"text": "We can see that the image becomes increasingly blurry if we increase the disk radius. As the goal of this exercise is to segment the image based on texture, we do not need a size that may include portions of a differently textured image. Let us choose a radius of 6 as it seems to be a good balance between the sharpness of 1 and the dullness of 9."
},
{
"code": null,
"e": 2607,
"s": 2464,
"text": "Our next task is to then turn this into a mask. To do this let us use image binarization. The below code will iterate over several thresholds."
},
{
"code": null,
"e": 3151,
"s": 2607,
"text": "def threshold_checker(image): thresholds = np.arange(0.1,1.1,0.1) image_gray = rgb2gray(image) entropy_image = entropy(image_gray, disk(6)) scaled_entropy = entropy_image / entropy_image.max() fig, ax = plt.subplots(2, 5, figsize=(17, 10)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'Threshold : {round(thresholds[n],2)}', fontsize = 16) threshold = scaled_entropy > thresholds[n] ax.imshow(threshold, cmap = 'gist_stern_r') ; ax.axis('off') fig.tight_layout()"
},
{
"code": null,
"e": 3385,
"s": 3151,
"text": "We can see that increasing the threshold for binarization decreases how much of the image is shown. Intuitively this makes sense as once the threshold is equal to 1, there is no part of the image that can match that level of entropy."
},
{
"code": null,
"e": 3511,
"s": 3385,
"text": "For visualization purposes let us set the threshold equal to 0.8 and see what happens when we use it as a mask for our image."
},
{
"code": null,
"e": 3770,
"s": 3511,
"text": "scaled_entropy = shawl_gray / shawl_gray.max()entropy_image = entropy(scaled_entropy, disk(6))scaled_entropy = entropy_image / entropy_image.max()mask = scaled_entropy > 0.8plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(shawl_gray * mask, cmap = 'gray');"
},
{
"code": null,
"e": 3931,
"s": 3770,
"text": "As expected, see that only objects that breach a level of entropy were able to be rendered. If we flip the mathematical operator we can see the opposite effect."
},
{
"code": null,
"e": 4106,
"s": 3931,
"text": "Notice how only low entropy objects have been rendered. To aid in visualization let us convert both these masks to their original colored image and compare them side by side."
},
{
"code": null,
"e": 5070,
"s": 4106,
"text": "def entropy_mask_viz(image): image_gray = rgb2gray(image) entropy_image = entropy(image_gray, disk(6)) scaled_entropy = entropy_image / entropy_image.max() f_size = 24 fig, ax = plt.subplots(1, 2, figsize=(17, 10)) ax[0].set_title('Greater Than Threshold', fontsize = f_size) threshold = scaled_entropy > 0.8 image_a = np.dstack([image[:,:,0]*threshold, image[:,:,1]*threshold, image[:,:,2]*threshold]) ax[0].imshow(image_a) ax[0].axis('off') ax[1].set_title('Less Than Threshold', fontsize = f_size) threshold = scaled_entropy < 0.8 image_b = np.dstack([image[:,:,0]*threshold, image[:,:,1]*threshold, image[:,:,2]*threshold]) ax[1].imshow(image_b) ax[1].axis('off') fig.tight_layout() return [image_a, image_b]entropic_images = entropy_mask_viz(shawls)"
},
{
"code": null,
"e": 5390,
"s": 5070,
"text": "We can see that we were able to successfully split the figures by the level of complexity of the objects. The objects on the left image exhibit far more intricate design patterns (as well as being made of fabrics with more complex textures). The objects on the right image are far more plain and contain only one color."
},
{
"code": null,
"e": 5494,
"s": 5390,
"text": "An interesting note is how we were able to separate the text from the sheet of paper it was written on."
},
{
"code": null,
"e": 5738,
"s": 5494,
"text": "This is useful to keep in mind. Human texts tend to be written on plain backgrounds to facilitate reading. Knowing this means that it is possible to extract all text features from an image, but this is a task we shall reserve for another time."
},
{
"code": null,
"e": 5752,
"s": 5738,
"text": "In Conclusion"
}
] |
JavaScript DOM HTML
|
The HTML DOM allows JavaScript to change the content of HTML elements.
The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
This example changes the content of a <p> element:
Example explained:
The HTML document above contains a <p> element with id="p1"
We use the HTML DOM to get the element with id="p1"
A JavaScript changes the content (innerHTML) of that element to "New
text!"
This example changes the content of an <h1> element:
Example explained:
The HTML document above contains an <h1> element with id="id01"
We use the HTML DOM to get the element with id="id01"
A JavaScript changes the content (innerHTML) of that element to "New
Heading"
To change the value of an HTML attribute, use this syntax:
This example changes the value of the src attribute of an <img> element:
Example explained:
The HTML document above contains an <img> element with id="myImage"
We use the HTML DOM to get the element with id="myImage"
A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"
JavaScript can create dynamic HTML content:
Date : Mon Apr 25 2022 02:15:55 GMT-0700 (Pacific Daylight Time)
In JavaScript, document.write() can be used to write directly to the HTML
output stream:
Never use document.write() after the document is loaded. It will
overwrite the document.
Use HTML DOM to change the value of the image's src attribute.
<img id="image" src="smiley.gif">
<script>
document.getElementById("image") = "pic_mountain.jpg";
</script>
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 71,
"s": 0,
"text": "The HTML DOM allows JavaScript to change the content of HTML elements."
},
{
"code": null,
"e": 164,
"s": 71,
"text": "The easiest way to modify the content of an HTML element is by using the innerHTML property."
},
{
"code": null,
"e": 223,
"s": 164,
"text": "To change the content of an HTML element, use this syntax:"
},
{
"code": null,
"e": 274,
"s": 223,
"text": "This example changes the content of a <p> element:"
},
{
"code": null,
"e": 293,
"s": 274,
"text": "Example explained:"
},
{
"code": null,
"e": 353,
"s": 293,
"text": "The HTML document above contains a <p> element with id=\"p1\""
},
{
"code": null,
"e": 405,
"s": 353,
"text": "We use the HTML DOM to get the element with id=\"p1\""
},
{
"code": null,
"e": 484,
"s": 405,
"text": "A JavaScript changes the content (innerHTML) of that element to \"New \n text!\""
},
{
"code": null,
"e": 537,
"s": 484,
"text": "This example changes the content of an <h1> element:"
},
{
"code": null,
"e": 556,
"s": 537,
"text": "Example explained:"
},
{
"code": null,
"e": 620,
"s": 556,
"text": "The HTML document above contains an <h1> element with id=\"id01\""
},
{
"code": null,
"e": 674,
"s": 620,
"text": "We use the HTML DOM to get the element with id=\"id01\""
},
{
"code": null,
"e": 755,
"s": 674,
"text": "A JavaScript changes the content (innerHTML) of that element to \"New \n Heading\""
},
{
"code": null,
"e": 815,
"s": 755,
"text": "To change the value of an HTML attribute, use this syntax: "
},
{
"code": null,
"e": 888,
"s": 815,
"text": "This example changes the value of the src attribute of an <img> element:"
},
{
"code": null,
"e": 907,
"s": 888,
"text": "Example explained:"
},
{
"code": null,
"e": 975,
"s": 907,
"text": "The HTML document above contains an <img> element with id=\"myImage\""
},
{
"code": null,
"e": 1032,
"s": 975,
"text": "We use the HTML DOM to get the element with id=\"myImage\""
},
{
"code": null,
"e": 1124,
"s": 1032,
"text": "A JavaScript changes the src attribute of that element from \"smiley.gif\" to \"landscape.jpg\""
},
{
"code": null,
"e": 1168,
"s": 1124,
"text": "JavaScript can create dynamic HTML content:"
},
{
"code": null,
"e": 1233,
"s": 1168,
"text": "Date : Mon Apr 25 2022 02:15:55 GMT-0700 (Pacific Daylight Time)"
},
{
"code": null,
"e": 1323,
"s": 1233,
"text": "In JavaScript, document.write() can be used to write directly to the HTML \noutput stream:"
},
{
"code": null,
"e": 1413,
"s": 1323,
"text": "Never use document.write() after the document is loaded. It will \noverwrite the document."
},
{
"code": null,
"e": 1476,
"s": 1413,
"text": "Use HTML DOM to change the value of the image's src attribute."
},
{
"code": null,
"e": 1586,
"s": 1476,
"text": "<img id=\"image\" src=\"smiley.gif\">\n\n<script>\ndocument.getElementById(\"image\") = \"pic_mountain.jpg\";\n</script>\n"
},
{
"code": null,
"e": 1605,
"s": 1586,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1638,
"s": 1605,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1680,
"s": 1638,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1787,
"s": 1680,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1806,
"s": 1787,
"text": "help@w3schools.com"
}
] |
Matplotlib.axes.Axes.tick_params() in Python
|
21 Apr, 2020
Matplotlib is a library in Python and it is numerical β mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.tick_params() function in axes module of matplotlib library is used to control behavior of major tick locators.
Syntax: Axes.tick_params(self, axis=βbothβ, **kwargs)
Parameters: This method accepts the following parameters.
axis : This parameter is the used to which axis to apply the parameters to.
Return value: This method does not returns any value.
Below examples illustrate the matplotlib.axes.Axes.tick_params() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np values = np.array([ 0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018, 0.143, 0.056, 0.125, 0.096, 0.094, 0.051, 0.043, 0.021, 0.138, 0.075, 0.109, 0.195, 0.050, 0.074, 0.079, 0.155, 0.020, 0.010, 0.061, 0.008]) values[[3, 14]] += .8 fig, (ax, ax2) = plt.subplots(2, 1, sharex = True) ax.plot(values, "o-", color ="green")ax2.plot(values, "o-", color ="green") ax.set_ylim(.78, 1.) ax2.set_ylim(0, .22) ax.spines['bottom'].set_visible(False)ax2.spines['top'].set_visible(False)ax.xaxis.tick_top()ax.tick_params(labeltop = False)ax2.xaxis.tick_bottom() d = .005kwargs = dict(transform = ax.transAxes, color ='k', clip_on = False) ax.plot((-d, +d), (-d, +d), **kwargs) ax.plot((1 - d, 1 + d), (-d, +d), **kwargs) kwargs.update(transform = ax2.transAxes) ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs)ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) fig.suptitle('matplotlib.axes.Axes.tick_params()\function Example\n\n', fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) fig, host = plt.subplots()fig.subplots_adjust(right = 0.75) par1 = host.twinx()par2 = host.twinx() # Offset the right spine of par2.# The ticks and label have already been# placed on the right by twinx above.par2.spines["right"].set_position(("axes", 1.2)) # Having been created by twinx, par2 # has its frame off, so the line of its# detached spine is invisible. First,# activate the frame but make the patch# and spines invisible.make_patch_spines_invisible(par2) # Second, show the right spine.par2.spines["right"].set_visible(True) p1, = host.plot([0, 1, 2], [0, 1, 2], "b-", label ="Y-label 1") p2, = par1.plot([0, 1, 2], [0, 30, 20], "r-", label ="Y-label 2") p3, = par2.plot([0, 1, 2], [500, 300, 150], "g-", label ="Y-label 3") host.set_xlim(0.25, 1.75)host.set_ylim(0.25, 1.75)par1.set_ylim(0, 40)par2.set_ylim(10, 500) host.set_xlabel("X-label")host.set_ylabel("Y-label 1")par1.set_ylabel("Y-label 2")par2.set_ylabel("Y-label 3") host.yaxis.label.set_color(p1.get_color())par1.yaxis.label.set_color(p2.get_color())par2.yaxis.label.set_color(p3.get_color()) tkw = dict(size = 4, width = 1.5)host.tick_params(axis ='y', colors = p1.get_color(), **tkw) par1.tick_params(axis ='y', colors = p2.get_color(), **tkw) par2.tick_params(axis ='y', colors = p3.get_color(), **tkw) host.tick_params(axis ='x', **tkw) lines = [p1, p2, p3] host.legend(lines, [l.get_label() for l in lines]) fig.suptitle('matplotlib.axes.Axes.tick_params()\function Example\n\n', fontweight ="bold") plt.show()
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical β mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 449,
"s": 328,
"text": "The Axes.tick_params() function in axes module of matplotlib library is used to control behavior of major tick locators."
},
{
"code": null,
"e": 503,
"s": 449,
"text": "Syntax: Axes.tick_params(self, axis=βbothβ, **kwargs)"
},
{
"code": null,
"e": 561,
"s": 503,
"text": "Parameters: This method accepts the following parameters."
},
{
"code": null,
"e": 637,
"s": 561,
"text": "axis : This parameter is the used to which axis to apply the parameters to."
},
{
"code": null,
"e": 691,
"s": 637,
"text": "Return value: This method does not returns any value."
},
{
"code": null,
"e": 785,
"s": 691,
"text": "Below examples illustrate the matplotlib.axes.Axes.tick_params() function in matplotlib.axes:"
},
{
"code": null,
"e": 796,
"s": 785,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np values = np.array([ 0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018, 0.143, 0.056, 0.125, 0.096, 0.094, 0.051, 0.043, 0.021, 0.138, 0.075, 0.109, 0.195, 0.050, 0.074, 0.079, 0.155, 0.020, 0.010, 0.061, 0.008]) values[[3, 14]] += .8 fig, (ax, ax2) = plt.subplots(2, 1, sharex = True) ax.plot(values, \"o-\", color =\"green\")ax2.plot(values, \"o-\", color =\"green\") ax.set_ylim(.78, 1.) ax2.set_ylim(0, .22) ax.spines['bottom'].set_visible(False)ax2.spines['top'].set_visible(False)ax.xaxis.tick_top()ax.tick_params(labeltop = False)ax2.xaxis.tick_bottom() d = .005kwargs = dict(transform = ax.transAxes, color ='k', clip_on = False) ax.plot((-d, +d), (-d, +d), **kwargs) ax.plot((1 - d, 1 + d), (-d, +d), **kwargs) kwargs.update(transform = ax2.transAxes) ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs)ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) fig.suptitle('matplotlib.axes.Axes.tick_params()\\function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 1905,
"s": 796,
"text": null
},
{
"code": null,
"e": 1913,
"s": 1905,
"text": "Output:"
},
{
"code": null,
"e": 1924,
"s": 1913,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) fig, host = plt.subplots()fig.subplots_adjust(right = 0.75) par1 = host.twinx()par2 = host.twinx() # Offset the right spine of par2.# The ticks and label have already been# placed on the right by twinx above.par2.spines[\"right\"].set_position((\"axes\", 1.2)) # Having been created by twinx, par2 # has its frame off, so the line of its# detached spine is invisible. First,# activate the frame but make the patch# and spines invisible.make_patch_spines_invisible(par2) # Second, show the right spine.par2.spines[\"right\"].set_visible(True) p1, = host.plot([0, 1, 2], [0, 1, 2], \"b-\", label =\"Y-label 1\") p2, = par1.plot([0, 1, 2], [0, 30, 20], \"r-\", label =\"Y-label 2\") p3, = par2.plot([0, 1, 2], [500, 300, 150], \"g-\", label =\"Y-label 3\") host.set_xlim(0.25, 1.75)host.set_ylim(0.25, 1.75)par1.set_ylim(0, 40)par2.set_ylim(10, 500) host.set_xlabel(\"X-label\")host.set_ylabel(\"Y-label 1\")par1.set_ylabel(\"Y-label 2\")par2.set_ylabel(\"Y-label 3\") host.yaxis.label.set_color(p1.get_color())par1.yaxis.label.set_color(p2.get_color())par2.yaxis.label.set_color(p3.get_color()) tkw = dict(size = 4, width = 1.5)host.tick_params(axis ='y', colors = p1.get_color(), **tkw) par1.tick_params(axis ='y', colors = p2.get_color(), **tkw) par2.tick_params(axis ='y', colors = p3.get_color(), **tkw) host.tick_params(axis ='x', **tkw) lines = [p1, p2, p3] host.legend(lines, [l.get_label() for l in lines]) fig.suptitle('matplotlib.axes.Axes.tick_params()\\function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 3845,
"s": 1924,
"text": null
},
{
"code": null,
"e": 3853,
"s": 3845,
"text": "Output:"
},
{
"code": null,
"e": 3875,
"s": 3853,
"text": "Matplotlib axes-class"
},
{
"code": null,
"e": 3893,
"s": 3875,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3900,
"s": 3893,
"text": "Python"
},
{
"code": null,
"e": 3998,
"s": 3900,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4016,
"s": 3998,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4058,
"s": 4016,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4080,
"s": 4058,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4106,
"s": 4080,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4138,
"s": 4106,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4167,
"s": 4138,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4197,
"s": 4167,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4224,
"s": 4197,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4260,
"s": 4224,
"text": "Convert integer to string in Python"
}
] |
Comments in Julia
|
11 Feb, 2022
Comments are the statements in a code that are ignored by the compiler at the time of execution. These statements are written to beautify the code, providing an explanation for the steps that are used in the code. During coding, proper use of comments makes maintenance easier and finding bugs easily. In Julia, comments are used in a similar manner as in Python. Comments can be of two types, based on their usage. These are:
Single Lined comments
Multi lined comments
Comments are generally used for the following purposes:
Code Readability
Explanation of the code or Metadata of the project
Prevent execution of code
To include resources
Single line comments in Julia start with the hashtag symbol(#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Juliaβs single lined comments are useful for supplying short explanations for function declarations, variables, and expressions. See the following code snippet demonstrating single line comment: Example:
Python
# This is a comment # Print "GeeksforGeeks !" to console print("GeeksforGeeks")
Output:
In the above code, the compiler ignores the statement written after #, because it considers the line as a comment and skips its execution.
Julia multi-line comment is a piece of text enclosed in a delimiter (#=) on start of the comment and (=#) on the end of the comment. A multiline comment is useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment:
Python
#= This would be a multiline comment in Julia that spans several lines and describes geeksforgeeks. A Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes and more.=# print("GeeksForGeeks")
Output:
In the above code snippet, the statements that are enclosed within #= and =# are considered as comments and are ignored by the compiler at the time of Code execution.
rkbhola5
Julia-Basics
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 459,
"s": 28,
"text": "Comments are the statements in a code that are ignored by the compiler at the time of execution. These statements are written to beautify the code, providing an explanation for the steps that are used in the code. During coding, proper use of comments makes maintenance easier and finding bugs easily. In Julia, comments are used in a similar manner as in Python. Comments can be of two types, based on their usage. These are: "
},
{
"code": null,
"e": 481,
"s": 459,
"text": "Single Lined comments"
},
{
"code": null,
"e": 502,
"s": 481,
"text": "Multi lined comments"
},
{
"code": null,
"e": 560,
"s": 502,
"text": "Comments are generally used for the following purposes: "
},
{
"code": null,
"e": 577,
"s": 560,
"text": "Code Readability"
},
{
"code": null,
"e": 628,
"s": 577,
"text": "Explanation of the code or Metadata of the project"
},
{
"code": null,
"e": 654,
"s": 628,
"text": "Prevent execution of code"
},
{
"code": null,
"e": 675,
"s": 654,
"text": "To include resources"
},
{
"code": null,
"e": 1076,
"s": 677,
"text": "Single line comments in Julia start with the hashtag symbol(#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Juliaβs single lined comments are useful for supplying short explanations for function declarations, variables, and expressions. See the following code snippet demonstrating single line comment: Example: "
},
{
"code": null,
"e": 1083,
"s": 1076,
"text": "Python"
},
{
"code": "# This is a comment # Print \"GeeksforGeeks !\" to console print(\"GeeksforGeeks\") ",
"e": 1164,
"s": 1083,
"text": null
},
{
"code": null,
"e": 1174,
"s": 1164,
"text": "Output: "
},
{
"code": null,
"e": 1315,
"s": 1174,
"text": "In the above code, the compiler ignores the statement written after #, because it considers the line as a comment and skips its execution. "
},
{
"code": null,
"e": 1720,
"s": 1315,
"text": "Julia multi-line comment is a piece of text enclosed in a delimiter (#=) on start of the comment and (=#) on the end of the comment. A multiline comment is useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment: "
},
{
"code": null,
"e": 1727,
"s": 1720,
"text": "Python"
},
{
"code": "#= This would be a multiline comment in Julia that spans several lines and describes geeksforgeeks. A Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes and more.=# print(\"GeeksForGeeks\")",
"e": 2012,
"s": 1727,
"text": null
},
{
"code": null,
"e": 2022,
"s": 2012,
"text": "Output: "
},
{
"code": null,
"e": 2190,
"s": 2022,
"text": "In the above code snippet, the statements that are enclosed within #= and =# are considered as comments and are ignored by the compiler at the time of Code execution. "
},
{
"code": null,
"e": 2199,
"s": 2190,
"text": "rkbhola5"
},
{
"code": null,
"e": 2212,
"s": 2199,
"text": "Julia-Basics"
},
{
"code": null,
"e": 2218,
"s": 2212,
"text": "Julia"
}
] |
How to Set Tick Labels Font Size in Matplotlib?
|
26 Nov, 2020
Prerequisite: Matplotlib
In this article, we will learn how to change (increase/decrease) the font size of tick label of a plot in matplotlib. For this understanding of following concepts is mandatory:
Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
Tick Label : Ticks are the markers denoting data points on axes. Matplotlibβs default tick locators and formatters are designed to be generally sufficient in many common situations. Position and labels of ticks are often explicitly mentioned to suit specific requirements.
Font Size : The font size or text size is how large the characters displayed on a screen or printed on a page are.
Approach: To change the font size of tick labels, one should follow some basic steps that are given below:
Import Libraries.Create or import data.Plot a graph on data using matplotlib.Change the font size of tick labels. (this can be done by different methods)
Import Libraries.
Create or import data.
Plot a graph on data using matplotlib.
Change the font size of tick labels. (this can be done by different methods)
To change the font size of tick labels, any of three different methods in contrast with the above mentioned steps can be employed. These three methods are:
fontsize in plt.xticks/plt.yticks()
fontsize in ax.set_yticklabels/ax.set_xticklabels()
labelsize in ax.tick_params()
Lets discuss implementation of these methods one by one with the help of examples:
Example 1: (Using plt.xticks/plt.yticks)
Python3
# importing librariesimport matplotlib.pyplot as plt # creating datax = list(range(1, 11, 1))y = [s*s for s in x] # ploting dataplt.plot(x, y) # changing the fontsize of yticksplt.yticks(fontsize=20) # showing the plotplt.show()
Output :
Example 2: (Using ax.set_yticklabels/ax.set_xticklabels)
Python3
# importing librariesimport matplotlib.pyplot as pltimport numpy as np # create datax = list(range(1, 11, 1))y = np.log(x) # make objects of subplotsfig, ax = plt.subplots() # plot the dataax.plot(x, y) # change the fontsizeax.set_xticklabels(x, fontsize=20) # show the plotplt.show()
Output :
Example 3: (Using ax.tick_params)
Python3
# importing librariesimport matplotlib.pyplot as pltimport numpy as np # create datax = list(range(1, 11, 1))y = np.sin(x) # make objects of subplotsfig, ax = plt.subplots(1, 1) # plot the dataax.plot(x, y) # change the fontsizeax.tick_params(axis='x', labelsize=20) # show the plotplt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Taking input in Python
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 53,
"s": 28,
"text": "Prerequisite: Matplotlib"
},
{
"code": null,
"e": 230,
"s": 53,
"text": "In this article, we will learn how to change (increase/decrease) the font size of tick label of a plot in matplotlib. For this understanding of following concepts is mandatory:"
},
{
"code": null,
"e": 506,
"s": 230,
"text": "Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002."
},
{
"code": null,
"e": 779,
"s": 506,
"text": "Tick Label : Ticks are the markers denoting data points on axes. Matplotlibβs default tick locators and formatters are designed to be generally sufficient in many common situations. Position and labels of ticks are often explicitly mentioned to suit specific requirements."
},
{
"code": null,
"e": 894,
"s": 779,
"text": "Font Size : The font size or text size is how large the characters displayed on a screen or printed on a page are."
},
{
"code": null,
"e": 1001,
"s": 894,
"text": "Approach: To change the font size of tick labels, one should follow some basic steps that are given below:"
},
{
"code": null,
"e": 1155,
"s": 1001,
"text": "Import Libraries.Create or import data.Plot a graph on data using matplotlib.Change the font size of tick labels. (this can be done by different methods)"
},
{
"code": null,
"e": 1173,
"s": 1155,
"text": "Import Libraries."
},
{
"code": null,
"e": 1196,
"s": 1173,
"text": "Create or import data."
},
{
"code": null,
"e": 1235,
"s": 1196,
"text": "Plot a graph on data using matplotlib."
},
{
"code": null,
"e": 1312,
"s": 1235,
"text": "Change the font size of tick labels. (this can be done by different methods)"
},
{
"code": null,
"e": 1468,
"s": 1312,
"text": "To change the font size of tick labels, any of three different methods in contrast with the above mentioned steps can be employed. These three methods are:"
},
{
"code": null,
"e": 1505,
"s": 1468,
"text": "fontsize in plt.xticks/plt.yticks()"
},
{
"code": null,
"e": 1558,
"s": 1505,
"text": "fontsize in ax.set_yticklabels/ax.set_xticklabels()"
},
{
"code": null,
"e": 1589,
"s": 1558,
"text": "labelsize in ax.tick_params()"
},
{
"code": null,
"e": 1672,
"s": 1589,
"text": "Lets discuss implementation of these methods one by one with the help of examples:"
},
{
"code": null,
"e": 1713,
"s": 1672,
"text": "Example 1: (Using plt.xticks/plt.yticks)"
},
{
"code": null,
"e": 1721,
"s": 1713,
"text": "Python3"
},
{
"code": "# importing librariesimport matplotlib.pyplot as plt # creating datax = list(range(1, 11, 1))y = [s*s for s in x] # ploting dataplt.plot(x, y) # changing the fontsize of yticksplt.yticks(fontsize=20) # showing the plotplt.show()",
"e": 1954,
"s": 1721,
"text": null
},
{
"code": null,
"e": 1963,
"s": 1954,
"text": "Output :"
},
{
"code": null,
"e": 2020,
"s": 1963,
"text": "Example 2: (Using ax.set_yticklabels/ax.set_xticklabels)"
},
{
"code": null,
"e": 2028,
"s": 2020,
"text": "Python3"
},
{
"code": "# importing librariesimport matplotlib.pyplot as pltimport numpy as np # create datax = list(range(1, 11, 1))y = np.log(x) # make objects of subplotsfig, ax = plt.subplots() # plot the dataax.plot(x, y) # change the fontsizeax.set_xticklabels(x, fontsize=20) # show the plotplt.show()",
"e": 2318,
"s": 2028,
"text": null
},
{
"code": null,
"e": 2327,
"s": 2318,
"text": "Output :"
},
{
"code": null,
"e": 2361,
"s": 2327,
"text": "Example 3: (Using ax.tick_params)"
},
{
"code": null,
"e": 2369,
"s": 2361,
"text": "Python3"
},
{
"code": "# importing librariesimport matplotlib.pyplot as pltimport numpy as np # create datax = list(range(1, 11, 1))y = np.sin(x) # make objects of subplotsfig, ax = plt.subplots(1, 1) # plot the dataax.plot(x, y) # change the fontsizeax.tick_params(axis='x', labelsize=20) # show the plotplt.show()",
"e": 2667,
"s": 2369,
"text": null
},
{
"code": null,
"e": 2675,
"s": 2667,
"text": "Output:"
},
{
"code": null,
"e": 2693,
"s": 2675,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2700,
"s": 2693,
"text": "Python"
},
{
"code": null,
"e": 2798,
"s": 2700,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2826,
"s": 2798,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2848,
"s": 2826,
"text": "Python map() function"
},
{
"code": null,
"e": 2898,
"s": 2848,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2916,
"s": 2898,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2960,
"s": 2916,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2983,
"s": 2960,
"text": "Taking input in Python"
},
{
"code": null,
"e": 3025,
"s": 2983,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3047,
"s": 3025,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3082,
"s": 3047,
"text": "Read a file line by line in Python"
}
] |
bool() in Python
|
15 Sep, 2021
Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.
Syntax: bool([x])
The bool() method in general takes only one parameter(here x), on which the standard truth testing procedure can be applied. If no parameter is passed, then by default it returns False. So, passing a parameter is optional.
It can return one of the two values.
It returns True if the parameter or value passed is True.
It returns False if the parameter or value passed is False.
Here are a few cases, in which Pythonβs bool() method returns false. Except these all other values return True.
If a False value is passed.
If None is passed.
If an empty sequence is passed, such as (), [], β, etc
If Zero is passed in any numeric type, such as 0, 0.0 etc
If an empty mapping is passed, such as {}.
If Objects of Classes having __bool__() or __len()__ method, returning 0 or False
Example 1:
Python3
# Python program to illustrate# built-in method bool() # Returns False as x is Falsex = Falseprint(bool(x)) # Returns True as x is Truex = Trueprint(bool(x)) # Returns False as x is not equal to yx = 5y = 10print(bool(x == y)) # Returns False as x is Nonex = Noneprint(bool(x)) # Returns False as x is an empty sequencex = ()print(bool(x)) # Returns False as x is an empty mappingx = {}print(bool(x)) # Returns False as x is 0x = 0.0print(bool(x)) # Returns True as x is a non empty stringx = 'GeeksforGeeks'print(bool(x))
Output:
False
True
False
False
False
False
False
True
Example 2:
Here is a program to find out even and odd by the use of bool() method. You may use other inputs and check out the results.
Python3
# Python code to check whether a number# is even or odd using bool() def check(num): return(bool(num % 2 == 0)) # Driver Codenum = 8if(check(num)): print("Even")else: print("Odd")
Output:
Even
Here we take input in boolean( True/ False) in boolean type with bool() function and check whether it is returned true or false.
Python3
user_input = bool(input("Are you hungry? True or false: "))if user_input == "True": print(" You need to eat some foods ")else: print("Let's go for walk")
Output:
Are you hungry? True or false: False
Let's go for walk
amitofficial
kumar_satyam
sagartomar9927
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
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
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 197,
"s": 52,
"text": "Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure. "
},
{
"code": null,
"e": 215,
"s": 197,
"text": "Syntax: bool([x])"
},
{
"code": null,
"e": 439,
"s": 215,
"text": "The bool() method in general takes only one parameter(here x), on which the standard truth testing procedure can be applied. If no parameter is passed, then by default it returns False. So, passing a parameter is optional. "
},
{
"code": null,
"e": 477,
"s": 439,
"text": "It can return one of the two values. "
},
{
"code": null,
"e": 535,
"s": 477,
"text": "It returns True if the parameter or value passed is True."
},
{
"code": null,
"e": 595,
"s": 535,
"text": "It returns False if the parameter or value passed is False."
},
{
"code": null,
"e": 709,
"s": 595,
"text": " Here are a few cases, in which Pythonβs bool() method returns false. Except these all other values return True. "
},
{
"code": null,
"e": 737,
"s": 709,
"text": "If a False value is passed."
},
{
"code": null,
"e": 756,
"s": 737,
"text": "If None is passed."
},
{
"code": null,
"e": 811,
"s": 756,
"text": "If an empty sequence is passed, such as (), [], β, etc"
},
{
"code": null,
"e": 869,
"s": 811,
"text": "If Zero is passed in any numeric type, such as 0, 0.0 etc"
},
{
"code": null,
"e": 912,
"s": 869,
"text": "If an empty mapping is passed, such as {}."
},
{
"code": null,
"e": 994,
"s": 912,
"text": "If Objects of Classes having __bool__() or __len()__ method, returning 0 or False"
},
{
"code": null,
"e": 1005,
"s": 994,
"text": "Example 1:"
},
{
"code": null,
"e": 1013,
"s": 1005,
"text": "Python3"
},
{
"code": "# Python program to illustrate# built-in method bool() # Returns False as x is Falsex = Falseprint(bool(x)) # Returns True as x is Truex = Trueprint(bool(x)) # Returns False as x is not equal to yx = 5y = 10print(bool(x == y)) # Returns False as x is Nonex = Noneprint(bool(x)) # Returns False as x is an empty sequencex = ()print(bool(x)) # Returns False as x is an empty mappingx = {}print(bool(x)) # Returns False as x is 0x = 0.0print(bool(x)) # Returns True as x is a non empty stringx = 'GeeksforGeeks'print(bool(x))",
"e": 1536,
"s": 1013,
"text": null
},
{
"code": null,
"e": 1545,
"s": 1536,
"text": "Output: "
},
{
"code": null,
"e": 1591,
"s": 1545,
"text": "False\nTrue\nFalse\nFalse\nFalse\nFalse\nFalse\nTrue"
},
{
"code": null,
"e": 1602,
"s": 1591,
"text": "Example 2:"
},
{
"code": null,
"e": 1727,
"s": 1602,
"text": "Here is a program to find out even and odd by the use of bool() method. You may use other inputs and check out the results. "
},
{
"code": null,
"e": 1735,
"s": 1727,
"text": "Python3"
},
{
"code": "# Python code to check whether a number# is even or odd using bool() def check(num): return(bool(num % 2 == 0)) # Driver Codenum = 8if(check(num)): print(\"Even\")else: print(\"Odd\")",
"e": 1924,
"s": 1735,
"text": null
},
{
"code": null,
"e": 1933,
"s": 1924,
"text": "Output: "
},
{
"code": null,
"e": 1938,
"s": 1933,
"text": "Even"
},
{
"code": null,
"e": 2067,
"s": 1938,
"text": "Here we take input in boolean( True/ False) in boolean type with bool() function and check whether it is returned true or false."
},
{
"code": null,
"e": 2075,
"s": 2067,
"text": "Python3"
},
{
"code": "user_input = bool(input(\"Are you hungry? True or false: \"))if user_input == \"True\": print(\" You need to eat some foods \")else: print(\"Let's go for walk\")",
"e": 2235,
"s": 2075,
"text": null
},
{
"code": null,
"e": 2243,
"s": 2235,
"text": "Output:"
},
{
"code": null,
"e": 2298,
"s": 2243,
"text": "Are you hungry? True or false: False\nLet's go for walk"
},
{
"code": null,
"e": 2311,
"s": 2298,
"text": "amitofficial"
},
{
"code": null,
"e": 2324,
"s": 2311,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2339,
"s": 2324,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2365,
"s": 2339,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2372,
"s": 2365,
"text": "Python"
},
{
"code": null,
"e": 2470,
"s": 2372,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2488,
"s": 2470,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2530,
"s": 2488,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2565,
"s": 2530,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2591,
"s": 2565,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2623,
"s": 2591,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2652,
"s": 2623,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2679,
"s": 2652,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2700,
"s": 2679,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2723,
"s": 2700,
"text": "Introduction To PYTHON"
}
] |
Largest and Smallest N-digit Hexadecimal Numbers
|
20 Jan, 2022
Given an integer N, the task is to find the smallest and largest N-digit numbers Hexa-Decimal Number System.
Examples:
Input: N = 4 Output: Largest: FFFF Smallest: 1000
Input: N = 2 Output: Largest: FF Smallest: 10
Approach: The following steps can be followed to complete the required answer:
Largest Number: To get the largest number, every digit of the number must be maximum. The maximum digit in the Hexa-Decimal number system is βFβ. Therefore:
1 Digit Largest Number: 'F'
2 Digit Largest Number: 'FF'
3 Digit Largest Number: 'FFF'
.
.
.
N Digit Largest Number: 'FFF....(N) times'
Smallest Number: The smallest number in hexadecimal numbers is β0β. The idea is that the first digit needs to be as minimal as possible other than 0 which is β1β and the remaining digits need to be 0. Therefore:
1 Digit Smallest Number: '1'
2 Digit Smallest Number: '10'
3 Digit Smallest Number: '100'
.
.
.
N Digit Smallest Number: '100....(N - 1) times'
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the largest// and smallest N-digit numbers// in Hexa-Decimal Number System #include <bits/stdc++.h>using namespace std; // Function to return the largest// N-digit number in Hexa-Decimal// Number Systemstring findLargest(int N){ // Append 'F' N times string largest = string(N, 'F'); return largest;} // Function to return the smallest// N-digit number in Hexa-Decimal// Number Systemstring findSmallest(int N){ // Append '0' (N - 1) times to 1 string smallest = "1" + string((N - 1), '0'); return smallest;} // Function to print the largest and smallest// N-digit Hexa-Decimal numbervoid print(int largest){ cout << "Largest: " << findLargest(largest) << endl; cout << "Smallest: " << findSmallest(largest) << endl;} // Driver codeint main(){ int N = 4; print(N); return 0;}
// Java program to find the largest// and smallest N-digit numbers// in Hexa-Decimal Number Systemclass GFG { // Function to return the largest // N-digit number in Hexa-Decimal // Number System static String findLargest(int N) { String largest = ""; // Append 'F' N times for (int i = 0; i < N ; i++) largest += 'F'; return largest; } // Function to return the smallest // N-digit number in Hexa-Decimal // Number System static String findSmallest(int N) { String smallest = "1" ; // Append '0' (N - 1) times to 1 for(int i = 0; i < N - 1; i++) smallest += '0'; return smallest; } // Function to print the largest and smallest // N-digit Hexa-Decimal number static void print(int largest) { System.out.println("Largest: " + findLargest(largest)) ; System.out.println("Smallest: " + findSmallest(largest)) ; } // Driver code public static void main (String[] args) { int N = 4; print(N); }} // This code is contributed by AnkitRai01
# Python3 program to find the largest# and smallest N-digit numbers# in Hexa-Decimal Number System # Function to return the largest# N-digit number in Hexa-Decimal# Number Systemdef findLargest(N) : # Append 'F' N times largest = 'F'*N return largest; # Function to return the smallest# N-digit number in Hexa-Decimal# Number Systemdef findSmallest(N) : # Append '0' (N - 1) times to 1 smallest = '1' + '0'*(N - 1) return smallest; # Function to print the largest and smallest# N-digit Hexa-Decimal numberdef printAns(largest) : print("Largest: " , findLargest(largest)); print("Smallest: " , findSmallest(largest)); # Driver codeif __name__ == "__main__" : N = 4; printAns(N); # This code is contributed by AnkitRai01
// C# program to find the largest// and smallest N-digit numbers// in Hexa-Decimal Number Systemusing System; class GFG { // Function to return the largest // N-digit number in Hexa-Decimal // Number System static string findLargest(int N) { string largest = ""; // Append 'F' N times for (int i = 0; i < N ; i++) largest += 'F'; return largest; } // Function to return the smallest // N-digit number in Hexa-Decimal // Number System static string findSmallest(int N) { string smallest = "1" ; // Append '0' (N - 1) times to 1 for(int i = 0; i < N - 1; i++) smallest += '0'; return smallest; } // Function to print the largest and smallest // N-digit Hexa-Decimal number static void print(int largest) { Console.WriteLine("Largest: " + findLargest(largest)) ; Console.WriteLine("Smallest: " + findSmallest(largest)) ; } // Driver code public static void Main(string[] args) { int N = 4; print(N); }} // This code is contributed by AnkitRai01
<script>// Javascipt implementation of the// above approach // Function to return the largest// N-digit number in Hexa-Decimal// Number Systemfunction findLargest(N){ // Append 'F' N times "a".repeat(10) var largest = "F".repeat(N); return largest;} // Function to return the smallest// N-digit number in Hexa-Decimal// Number Systemfunction findSmallest(N){ // Append '0' (N - 1) times to 1 var smallest = "1" + "0".repeat(N-1); return smallest;} // Function to print the largest and smallest// N-digit Hexa-Decimal numberfunction print(largest){ document.write("Largest: " + findLargest(largest) + "<br>"); document.write("Smallest: " + findSmallest(largest) + "<br>");} // Driver codevar N = 4;print(N); // This code is contributed by Shivanisingh</script>
Largest: FFFF
Smallest: 1000
Time Complexity: O(N) where N is the length of the string.
Auxiliary Space: O(1)
ankthon
shivanisinghss2110
subhammahato348
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "Given an integer N, the task is to find the smallest and largest N-digit numbers Hexa-Decimal Number System."
},
{
"code": null,
"e": 148,
"s": 137,
"text": "Examples: "
},
{
"code": null,
"e": 198,
"s": 148,
"text": "Input: N = 4 Output: Largest: FFFF Smallest: 1000"
},
{
"code": null,
"e": 245,
"s": 198,
"text": "Input: N = 2 Output: Largest: FF Smallest: 10 "
},
{
"code": null,
"e": 325,
"s": 245,
"text": "Approach: The following steps can be followed to complete the required answer: "
},
{
"code": null,
"e": 482,
"s": 325,
"text": "Largest Number: To get the largest number, every digit of the number must be maximum. The maximum digit in the Hexa-Decimal number system is βFβ. Therefore:"
},
{
"code": null,
"e": 666,
"s": 482,
"text": "1 Digit Largest Number: 'F'\n2 Digit Largest Number: 'FF'\n3 Digit Largest Number: 'FFF'\n .\n .\n .\nN Digit Largest Number: 'FFF....(N) times'"
},
{
"code": null,
"e": 878,
"s": 666,
"text": "Smallest Number: The smallest number in hexadecimal numbers is β0β. The idea is that the first digit needs to be as minimal as possible other than 0 which is β1β and the remaining digits need to be 0. Therefore:"
},
{
"code": null,
"e": 1070,
"s": 878,
"text": "1 Digit Smallest Number: '1'\n2 Digit Smallest Number: '10'\n3 Digit Smallest Number: '100'\n .\n .\n .\nN Digit Smallest Number: '100....(N - 1) times'"
},
{
"code": null,
"e": 1122,
"s": 1070,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1126,
"s": 1122,
"text": "C++"
},
{
"code": null,
"e": 1131,
"s": 1126,
"text": "Java"
},
{
"code": null,
"e": 1139,
"s": 1131,
"text": "Python3"
},
{
"code": null,
"e": 1142,
"s": 1139,
"text": "C#"
},
{
"code": null,
"e": 1153,
"s": 1142,
"text": "Javascript"
},
{
"code": "// C++ program to find the largest// and smallest N-digit numbers// in Hexa-Decimal Number System #include <bits/stdc++.h>using namespace std; // Function to return the largest// N-digit number in Hexa-Decimal// Number Systemstring findLargest(int N){ // Append 'F' N times string largest = string(N, 'F'); return largest;} // Function to return the smallest// N-digit number in Hexa-Decimal// Number Systemstring findSmallest(int N){ // Append '0' (N - 1) times to 1 string smallest = \"1\" + string((N - 1), '0'); return smallest;} // Function to print the largest and smallest// N-digit Hexa-Decimal numbervoid print(int largest){ cout << \"Largest: \" << findLargest(largest) << endl; cout << \"Smallest: \" << findSmallest(largest) << endl;} // Driver codeint main(){ int N = 4; print(N); return 0;}",
"e": 1989,
"s": 1153,
"text": null
},
{
"code": "// Java program to find the largest// and smallest N-digit numbers// in Hexa-Decimal Number Systemclass GFG { // Function to return the largest // N-digit number in Hexa-Decimal // Number System static String findLargest(int N) { String largest = \"\"; // Append 'F' N times for (int i = 0; i < N ; i++) largest += 'F'; return largest; } // Function to return the smallest // N-digit number in Hexa-Decimal // Number System static String findSmallest(int N) { String smallest = \"1\" ; // Append '0' (N - 1) times to 1 for(int i = 0; i < N - 1; i++) smallest += '0'; return smallest; } // Function to print the largest and smallest // N-digit Hexa-Decimal number static void print(int largest) { System.out.println(\"Largest: \" + findLargest(largest)) ; System.out.println(\"Smallest: \" + findSmallest(largest)) ; } // Driver code public static void main (String[] args) { int N = 4; print(N); }} // This code is contributed by AnkitRai01",
"e": 3149,
"s": 1989,
"text": null
},
{
"code": "# Python3 program to find the largest# and smallest N-digit numbers# in Hexa-Decimal Number System # Function to return the largest# N-digit number in Hexa-Decimal# Number Systemdef findLargest(N) : # Append 'F' N times largest = 'F'*N return largest; # Function to return the smallest# N-digit number in Hexa-Decimal# Number Systemdef findSmallest(N) : # Append '0' (N - 1) times to 1 smallest = '1' + '0'*(N - 1) return smallest; # Function to print the largest and smallest# N-digit Hexa-Decimal numberdef printAns(largest) : print(\"Largest: \" , findLargest(largest)); print(\"Smallest: \" , findSmallest(largest)); # Driver codeif __name__ == \"__main__\" : N = 4; printAns(N); # This code is contributed by AnkitRai01",
"e": 3904,
"s": 3149,
"text": null
},
{
"code": "// C# program to find the largest// and smallest N-digit numbers// in Hexa-Decimal Number Systemusing System; class GFG { // Function to return the largest // N-digit number in Hexa-Decimal // Number System static string findLargest(int N) { string largest = \"\"; // Append 'F' N times for (int i = 0; i < N ; i++) largest += 'F'; return largest; } // Function to return the smallest // N-digit number in Hexa-Decimal // Number System static string findSmallest(int N) { string smallest = \"1\" ; // Append '0' (N - 1) times to 1 for(int i = 0; i < N - 1; i++) smallest += '0'; return smallest; } // Function to print the largest and smallest // N-digit Hexa-Decimal number static void print(int largest) { Console.WriteLine(\"Largest: \" + findLargest(largest)) ; Console.WriteLine(\"Smallest: \" + findSmallest(largest)) ; } // Driver code public static void Main(string[] args) { int N = 4; print(N); }} // This code is contributed by AnkitRai01",
"e": 5119,
"s": 3904,
"text": null
},
{
"code": "<script>// Javascipt implementation of the// above approach // Function to return the largest// N-digit number in Hexa-Decimal// Number Systemfunction findLargest(N){ // Append 'F' N times \"a\".repeat(10) var largest = \"F\".repeat(N); return largest;} // Function to return the smallest// N-digit number in Hexa-Decimal// Number Systemfunction findSmallest(N){ // Append '0' (N - 1) times to 1 var smallest = \"1\" + \"0\".repeat(N-1); return smallest;} // Function to print the largest and smallest// N-digit Hexa-Decimal numberfunction print(largest){ document.write(\"Largest: \" + findLargest(largest) + \"<br>\"); document.write(\"Smallest: \" + findSmallest(largest) + \"<br>\");} // Driver codevar N = 4;print(N); // This code is contributed by Shivanisingh</script>",
"e": 5913,
"s": 5119,
"text": null
},
{
"code": null,
"e": 5942,
"s": 5913,
"text": "Largest: FFFF\nSmallest: 1000"
},
{
"code": null,
"e": 6003,
"s": 5944,
"text": "Time Complexity: O(N) where N is the length of the string."
},
{
"code": null,
"e": 6026,
"s": 6003,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 6034,
"s": 6026,
"text": "ankthon"
},
{
"code": null,
"e": 6053,
"s": 6034,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 6069,
"s": 6053,
"text": "subhammahato348"
},
{
"code": null,
"e": 6082,
"s": 6069,
"text": "Mathematical"
},
{
"code": null,
"e": 6101,
"s": 6082,
"text": "School Programming"
},
{
"code": null,
"e": 6114,
"s": 6101,
"text": "Mathematical"
}
] |
Multi-dimensional lists in Python
|
Lists are a very widely use data structure in python. They contain a list of elements separated by comma. But sometimes lists can also contain lists within them. These are called nested lists or multidimensional lists. In this article we will see how to create and access elements in a multidimensional list.
In the below program we create a multidimensional list of 4 columns and 3 rows using nested for loops.
Live Demo
multlist = [[0 for columns in range(4)] for rows in range(3)]
print(multlist)
Running the above code gives us the following result β
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
We can add elements to the list created above using methods that are available to the lists. We will use the methods append and extend to achieve this. Both methods are shown in the program below.
Live Demo
multlist = [["Mon","Tue","Wed"], [2, 4, 9,], [1,1.5, 2]]
multlist.append(["Phy","Chem","Math"])
print(multlist)
multlist[0].extend(["Thu","Fri"])
print(multlist)
Running the above code gives us the following result β
[['Mon', 'Tue', 'Wed'], [2, 4, 9], [1, 1.5, 2], ['Phy', 'Chem', 'Math']]
[['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], [2, 4, 9], [1, 1.5, 2], ['Phy', 'Chem', 'Math']]
We can access the elements in multidimensional list using for loops as shown in the below program. We design nested for loops to first access the rows and then access the columns.
multlist = [[1,5,9], [2, 4, 9,], [1,1, 2]]
for i in range(len(multlist)) :
for j in range(len(multlist[i])) :
print(multlist[i][j], end=" ")
print()
Running the above code gives us the following result β
1 5 9
2 4 9
1 1 2
|
[
{
"code": null,
"e": 1496,
"s": 1187,
"text": "Lists are a very widely use data structure in python. They contain a list of elements separated by comma. But sometimes lists can also contain lists within them. These are called nested lists or multidimensional lists. In this article we will see how to create and access elements in a multidimensional list."
},
{
"code": null,
"e": 1599,
"s": 1496,
"text": "In the below program we create a multidimensional list of 4 columns and 3 rows using nested for loops."
},
{
"code": null,
"e": 1610,
"s": 1599,
"text": " Live Demo"
},
{
"code": null,
"e": 1688,
"s": 1610,
"text": "multlist = [[0 for columns in range(4)] for rows in range(3)]\nprint(multlist)"
},
{
"code": null,
"e": 1743,
"s": 1688,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 1786,
"s": 1743,
"text": "[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]"
},
{
"code": null,
"e": 1983,
"s": 1786,
"text": "We can add elements to the list created above using methods that are available to the lists. We will use the methods append and extend to achieve this. Both methods are shown in the program below."
},
{
"code": null,
"e": 1994,
"s": 1983,
"text": " Live Demo"
},
{
"code": null,
"e": 2157,
"s": 1994,
"text": "multlist = [[\"Mon\",\"Tue\",\"Wed\"], [2, 4, 9,], [1,1.5, 2]]\nmultlist.append([\"Phy\",\"Chem\",\"Math\"])\nprint(multlist)\n\nmultlist[0].extend([\"Thu\",\"Fri\"])\nprint(multlist)"
},
{
"code": null,
"e": 2212,
"s": 2157,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 2372,
"s": 2212,
"text": "[['Mon', 'Tue', 'Wed'], [2, 4, 9], [1, 1.5, 2], ['Phy', 'Chem', 'Math']]\n[['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], [2, 4, 9], [1, 1.5, 2], ['Phy', 'Chem', 'Math']]"
},
{
"code": null,
"e": 2552,
"s": 2372,
"text": "We can access the elements in multidimensional list using for loops as shown in the below program. We design nested for loops to first access the rows and then access the columns."
},
{
"code": null,
"e": 2713,
"s": 2552,
"text": "multlist = [[1,5,9], [2, 4, 9,], [1,1, 2]]\nfor i in range(len(multlist)) :\n for j in range(len(multlist[i])) :\n print(multlist[i][j], end=\" \")\n print()"
},
{
"code": null,
"e": 2768,
"s": 2713,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 2786,
"s": 2768,
"text": "1 5 9\n2 4 9\n1 1 2"
}
] |
CSS3 Media query for all devices
|
03 Nov, 2021
The media query in CSS is used to create a responsive web design to make a user-friendly website. It means that the view of web pages differs from system to system based on screen or media types. Media is allowing us to reshape and design the user view page of the website for specific devices like Tablets, Desktops, Mobile phones, etc.
Media queries can be used to check many things like the following
Width and height of the viewport
Width and height of the device
Orientation
Resolution
A media query consist of a media type that can contain one or more expression which can be either true or false. The result of the query is true if the specified media matches the type of device where the document is displayed on. If the media query is true then the style is applied. In simple words, it uses the @media rule to add the block of CSS properties, based on certain conditions.
Syntax:
@media not | only mediatype and (expression)
{
// Code content
}
We can add the breakpoint to see the screen-width along with the width and height of the viewport for the different devices. A breakpoint is a point or key that determines when to change the layout by reshaping & adding the new rules inside the media queries. There are some common breakpoints, not a standard resolution, that can be used for the different widths & heights of devices:
For Mobile devices: 320px-480px
For Tablets or iPad: 480px - 768px
For Laptop or small-size screen: 768px -1024px
For Desktop or large-size screen: 1024px -1200px
For Extra-large size device: 1200px and more
These breakpoints can help to build responsive designs(ie., Mobile-first design) by specifying the different sets of values for width & height. We can also use the media queries for changing the layout of a webpage that will be depending on the orientation of the browser.
Example: This example illustrates the use of the CSS Media query to build the mobile-first design by specifying the different device-width.
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>GeeksforGeeks CSS Media Query</title> <meta name="description" content="CSS Media Query for all devices like mobile, tablet, desktop etc."> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="gfg-style.css"></head> <body> <div class="gfg-div">GeeksforGeeks</div></body> </html>
CSS Code: The following CSS code specifies the media queries with different styling properties based on certain conditions that will be displayed according to the device size.
CSS
* { margin: 0; padding: 0;} /* Default Design */.gfg-div { /* To make all elements center */ display: flex; justify-content: center; align-items: center; /* Default Styling */ margin: 20px auto; padding: 30px; font-size: 30px; width: 300px; height: 300px; background-color: darkseagreen; color: black;} /* For Desktop View */@media screen and (min-width: 1024px) { .gfg-div { background-color: #63c971; color: #fff; }} /* For Tablet View */@media screen and (min-device-width: 768px)and (max-device-width: 1024px) { .gfg-div { width: 400px; height: 400px; background-color: orange; color: black; }} /* For Mobile Portrait View */@media screen and (max-device-width: 480px)and (orientation: portrait) { .gfg-div { width: 200px; height: 200px; background-color: red; color: #fff; }} /* For Mobile Landscape View */@media screen and (max-device-width: 640px)and (orientation: landscape) { .gfg-div { width: 400px; height: 200px; background-color: cyan; color: black; }} /* For Mobile Phones Portrait or Landscape View */@media screen and (max-device-width: 640px) { .gfg-div { width: 400px; height: 200px; background-color: chartreuse; color: black; }} /* For iPhone 4 Portrait or Landscape View */@media screen and (min-device-width: 320px)and (-webkit-min-device-pixel-ratio: 2) { .gfg-div { width: 400px; height: 400px; background-color: brown; color: black; }} /* For iPhone 5 Portrait or Landscape View */@media (device-height: 568px) and (device-width: 320px)and (-webkit-min-device-pixel-ratio: 2) { .gfg-div { width: 400px; height: 400px; background-color: cornflowerblue; color: black; }} /* For iPhone 6 and 6 plus Portrait or Landscape View */@media (min-device-height: 667px) and (min-device-width: 375px)and (-webkit-min-device-pixel-ratio: 3) { .gfg-div { width: 400px; height: 400px; background-color: darkgoldenrod; color: black; }}
Output:
Supported Browsers:
Google Chrome
Firefox
Microsoft Edge
Internet Explorer
Opera
Safari
surindertarika1234
bhaskargeeksforgeeks
CSS-Advanced
CSS-Properties
CSS-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 392,
"s": 54,
"text": "The media query in CSS is used to create a responsive web design to make a user-friendly website. It means that the view of web pages differs from system to system based on screen or media types. Media is allowing us to reshape and design the user view page of the website for specific devices like Tablets, Desktops, Mobile phones, etc."
},
{
"code": null,
"e": 458,
"s": 392,
"text": "Media queries can be used to check many things like the following"
},
{
"code": null,
"e": 491,
"s": 458,
"text": "Width and height of the viewport"
},
{
"code": null,
"e": 522,
"s": 491,
"text": "Width and height of the device"
},
{
"code": null,
"e": 534,
"s": 522,
"text": "Orientation"
},
{
"code": null,
"e": 545,
"s": 534,
"text": "Resolution"
},
{
"code": null,
"e": 936,
"s": 545,
"text": "A media query consist of a media type that can contain one or more expression which can be either true or false. The result of the query is true if the specified media matches the type of device where the document is displayed on. If the media query is true then the style is applied. In simple words, it uses the @media rule to add the block of CSS properties, based on certain conditions."
},
{
"code": null,
"e": 944,
"s": 936,
"text": "Syntax:"
},
{
"code": null,
"e": 1013,
"s": 944,
"text": "@media not | only mediatype and (expression)\n{\n // Code content\n}"
},
{
"code": null,
"e": 1399,
"s": 1013,
"text": "We can add the breakpoint to see the screen-width along with the width and height of the viewport for the different devices. A breakpoint is a point or key that determines when to change the layout by reshaping & adding the new rules inside the media queries. There are some common breakpoints, not a standard resolution, that can be used for the different widths & heights of devices:"
},
{
"code": null,
"e": 1431,
"s": 1399,
"text": "For Mobile devices: 320px-480px"
},
{
"code": null,
"e": 1466,
"s": 1431,
"text": "For Tablets or iPad: 480px - 768px"
},
{
"code": null,
"e": 1513,
"s": 1466,
"text": "For Laptop or small-size screen: 768px -1024px"
},
{
"code": null,
"e": 1562,
"s": 1513,
"text": "For Desktop or large-size screen: 1024px -1200px"
},
{
"code": null,
"e": 1607,
"s": 1562,
"text": "For Extra-large size device: 1200px and more"
},
{
"code": null,
"e": 1880,
"s": 1607,
"text": "These breakpoints can help to build responsive designs(ie., Mobile-first design) by specifying the different sets of values for width & height. We can also use the media queries for changing the layout of a webpage that will be depending on the orientation of the browser."
},
{
"code": null,
"e": 2020,
"s": 1880,
"text": "Example: This example illustrates the use of the CSS Media query to build the mobile-first design by specifying the different device-width."
},
{
"code": null,
"e": 2025,
"s": 2020,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <title>GeeksforGeeks CSS Media Query</title> <meta name=\"description\" content=\"CSS Media Query for all devices like mobile, tablet, desktop etc.\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"gfg-style.css\"></head> <body> <div class=\"gfg-div\">GeeksforGeeks</div></body> </html>",
"e": 2548,
"s": 2025,
"text": null
},
{
"code": null,
"e": 2724,
"s": 2548,
"text": "CSS Code: The following CSS code specifies the media queries with different styling properties based on certain conditions that will be displayed according to the device size."
},
{
"code": null,
"e": 2728,
"s": 2724,
"text": "CSS"
},
{
"code": "* { margin: 0; padding: 0;} /* Default Design */.gfg-div { /* To make all elements center */ display: flex; justify-content: center; align-items: center; /* Default Styling */ margin: 20px auto; padding: 30px; font-size: 30px; width: 300px; height: 300px; background-color: darkseagreen; color: black;} /* For Desktop View */@media screen and (min-width: 1024px) { .gfg-div { background-color: #63c971; color: #fff; }} /* For Tablet View */@media screen and (min-device-width: 768px)and (max-device-width: 1024px) { .gfg-div { width: 400px; height: 400px; background-color: orange; color: black; }} /* For Mobile Portrait View */@media screen and (max-device-width: 480px)and (orientation: portrait) { .gfg-div { width: 200px; height: 200px; background-color: red; color: #fff; }} /* For Mobile Landscape View */@media screen and (max-device-width: 640px)and (orientation: landscape) { .gfg-div { width: 400px; height: 200px; background-color: cyan; color: black; }} /* For Mobile Phones Portrait or Landscape View */@media screen and (max-device-width: 640px) { .gfg-div { width: 400px; height: 200px; background-color: chartreuse; color: black; }} /* For iPhone 4 Portrait or Landscape View */@media screen and (min-device-width: 320px)and (-webkit-min-device-pixel-ratio: 2) { .gfg-div { width: 400px; height: 400px; background-color: brown; color: black; }} /* For iPhone 5 Portrait or Landscape View */@media (device-height: 568px) and (device-width: 320px)and (-webkit-min-device-pixel-ratio: 2) { .gfg-div { width: 400px; height: 400px; background-color: cornflowerblue; color: black; }} /* For iPhone 6 and 6 plus Portrait or Landscape View */@media (min-device-height: 667px) and (min-device-width: 375px)and (-webkit-min-device-pixel-ratio: 3) { .gfg-div { width: 400px; height: 400px; background-color: darkgoldenrod; color: black; }}",
"e": 4696,
"s": 2728,
"text": null
},
{
"code": null,
"e": 4704,
"s": 4696,
"text": "Output:"
},
{
"code": null,
"e": 4724,
"s": 4704,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 4738,
"s": 4724,
"text": "Google Chrome"
},
{
"code": null,
"e": 4746,
"s": 4738,
"text": "Firefox"
},
{
"code": null,
"e": 4761,
"s": 4746,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 4779,
"s": 4761,
"text": "Internet Explorer"
},
{
"code": null,
"e": 4785,
"s": 4779,
"text": "Opera"
},
{
"code": null,
"e": 4792,
"s": 4785,
"text": "Safari"
},
{
"code": null,
"e": 4811,
"s": 4792,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4832,
"s": 4811,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 4845,
"s": 4832,
"text": "CSS-Advanced"
},
{
"code": null,
"e": 4860,
"s": 4845,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4874,
"s": 4860,
"text": "CSS-Questions"
},
{
"code": null,
"e": 4878,
"s": 4874,
"text": "CSS"
},
{
"code": null,
"e": 4883,
"s": 4878,
"text": "HTML"
},
{
"code": null,
"e": 4900,
"s": 4883,
"text": "Web Technologies"
},
{
"code": null,
"e": 4905,
"s": 4900,
"text": "HTML"
}
] |
How to minify HTML code of PHP page ?
|
03 Jun, 2020
HTML output minification is important to improve website performance by reducing the page load times and reduce the overall page size. Minifying HTML output also reduces the data usage of the user requesting the site.Minification can be done by removing unnecessary details and eliminating excessive whitespaces, newlines, comments, etc. However, minification reduces the readability of the code. Minification can reduce file size upto 70%. PHP is used to transfer files from development to production environment. HTML files can be minified both manually and automatically. Minification can be undone using several tools that add whitespaces in the code. However, any comments removed during minification cannot be restored.
Example: This is the HTML file without minifying the the code.
<html> <head> <!-- This is the content that shows in the browser tab --> <title>Title Page</title> </head> <body> <!-- This is a comment. --> <h1>Hello world!</h1></body> </html>
HTML file after minification
<html><head><title>Title Page</title></head><body><h1>Hello world!</h1></body></html>
Approach 1: Using GZip Compression in Apache:
Steps to enable Gzip Compression in Apache
Open the Apache configuration filevim /etc/httpd/conf/httpd.conf Check the following line in the configuration file.LoadModule deflate_module modules/mod_deflate.soAdd the following lines at the end of configuration file.AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
Restart the Apache Serversudo service httpd restart
Open the Apache configuration filevim /etc/httpd/conf/httpd.conf
vim /etc/httpd/conf/httpd.conf
Check the following line in the configuration file.LoadModule deflate_module modules/mod_deflate.so
LoadModule deflate_module modules/mod_deflate.so
Add the following lines at the end of configuration file.AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
Restart the Apache Serversudo service httpd restart
sudo service httpd restart
Approach 2: HTML code can be minified with ob_start() function with a callback.
<?phpob_start("minifier");function minifier($code) { $search = array( // Remove whitespaces after tags '/\>[^\S ]+/s', // Remove whitespaces before tags '/[^\S ]+\</s', // Remove multiple whitespace sequences '/(\s)+/s', // Removes comments '/<!--(.|\s)*?-->/' ); $replace = array('>', '<', '\\1'); $code = preg_replace($search, $replace, $code); return $code;}?><!DOCTYPE html><html> <head> <!-- title of page --> <title>Demo for minifier</title> </head> <body> <!-- body of page --> <h1>Hello World</h1> </body> </html> <?phpob_end_flush();?>
Output:
<!DOCTYPE html><html><head><title>Demo for minifier</title></head><body><h1>Hello World</h1></body></html>
Approach 3: Using HTMLMinifier plugin: HTML Minifier is a server-side source code minifier designed to optimise HTML, CSS and JavaScript output sent out to the client by removing unnecessary whitespaces, comments and newlines. HTMLMinifier offers a variety of optimisation options in the plugin that can be selected as per the user requirement.
Steps to use HTMLMinifier:
Download the HTMLMinifier file from https://www.terresquall.com/download/HTMLMinifier.phpInclude the following code into the php file<?php // Import the HTMLMinifierrequire_once 'myfolder/HTMLMinifier.php'; // HTML source to be minified$htmlpage = file_get_contents('./mypage.html'); // Minified version of the pageecho HTMLMinifier::process($htmlpage); ?> Run the php file
Download the HTMLMinifier file from https://www.terresquall.com/download/HTMLMinifier.php
Include the following code into the php file<?php // Import the HTMLMinifierrequire_once 'myfolder/HTMLMinifier.php'; // HTML source to be minified$htmlpage = file_get_contents('./mypage.html'); // Minified version of the pageecho HTMLMinifier::process($htmlpage); ?>
<?php // Import the HTMLMinifierrequire_once 'myfolder/HTMLMinifier.php'; // HTML source to be minified$htmlpage = file_get_contents('./mypage.html'); // Minified version of the pageecho HTMLMinifier::process($htmlpage); ?>
Run the php file
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between HTTP GET and POST Methods
PHP Cookies
Download file from URL using PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to get the file size using PHP ?
String comparison using == vs strcmp() in PHP
How to calculate the difference between two dates in PHP ?
How to create comma separated list from an array in PHP ?
Multidimensional arrays in PHP
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 754,
"s": 28,
"text": "HTML output minification is important to improve website performance by reducing the page load times and reduce the overall page size. Minifying HTML output also reduces the data usage of the user requesting the site.Minification can be done by removing unnecessary details and eliminating excessive whitespaces, newlines, comments, etc. However, minification reduces the readability of the code. Minification can reduce file size upto 70%. PHP is used to transfer files from development to production environment. HTML files can be minified both manually and automatically. Minification can be undone using several tools that add whitespaces in the code. However, any comments removed during minification cannot be restored."
},
{
"code": null,
"e": 817,
"s": 754,
"text": "Example: This is the HTML file without minifying the the code."
},
{
"code": "<html> <head> <!-- This is the content that shows in the browser tab --> <title>Title Page</title> </head> <body> <!-- This is a comment. --> <h1>Hello world!</h1></body> </html>",
"e": 1012,
"s": 817,
"text": null
},
{
"code": null,
"e": 1041,
"s": 1012,
"text": "HTML file after minification"
},
{
"code": null,
"e": 1127,
"s": 1041,
"text": "<html><head><title>Title Page</title></head><body><h1>Hello world!</h1></body></html>"
},
{
"code": null,
"e": 1173,
"s": 1127,
"text": "Approach 1: Using GZip Compression in Apache:"
},
{
"code": null,
"e": 1216,
"s": 1173,
"text": "Steps to enable Gzip Compression in Apache"
},
{
"code": null,
"e": 1904,
"s": 1216,
"text": "Open the Apache configuration filevim /etc/httpd/conf/httpd.conf Check the following line in the configuration file.LoadModule deflate_module modules/mod_deflate.soAdd the following lines at the end of configuration file.AddOutputFilterByType DEFLATE text/plain\nAddOutputFilterByType DEFLATE text/html\nAddOutputFilterByType DEFLATE text/xml\nAddOutputFilterByType DEFLATE text/css\nAddOutputFilterByType DEFLATE application/xml\nAddOutputFilterByType DEFLATE application/xhtml+xml\nAddOutputFilterByType DEFLATE application/rss+xml\nAddOutputFilterByType DEFLATE application/javascript\nAddOutputFilterByType DEFLATE application/x-javascript\nRestart the Apache Serversudo service httpd restart"
},
{
"code": null,
"e": 1970,
"s": 1904,
"text": "Open the Apache configuration filevim /etc/httpd/conf/httpd.conf "
},
{
"code": null,
"e": 2002,
"s": 1970,
"text": "vim /etc/httpd/conf/httpd.conf "
},
{
"code": null,
"e": 2102,
"s": 2002,
"text": "Check the following line in the configuration file.LoadModule deflate_module modules/mod_deflate.so"
},
{
"code": null,
"e": 2151,
"s": 2102,
"text": "LoadModule deflate_module modules/mod_deflate.so"
},
{
"code": null,
"e": 2624,
"s": 2151,
"text": "Add the following lines at the end of configuration file.AddOutputFilterByType DEFLATE text/plain\nAddOutputFilterByType DEFLATE text/html\nAddOutputFilterByType DEFLATE text/xml\nAddOutputFilterByType DEFLATE text/css\nAddOutputFilterByType DEFLATE application/xml\nAddOutputFilterByType DEFLATE application/xhtml+xml\nAddOutputFilterByType DEFLATE application/rss+xml\nAddOutputFilterByType DEFLATE application/javascript\nAddOutputFilterByType DEFLATE application/x-javascript\n"
},
{
"code": null,
"e": 3040,
"s": 2624,
"text": "AddOutputFilterByType DEFLATE text/plain\nAddOutputFilterByType DEFLATE text/html\nAddOutputFilterByType DEFLATE text/xml\nAddOutputFilterByType DEFLATE text/css\nAddOutputFilterByType DEFLATE application/xml\nAddOutputFilterByType DEFLATE application/xhtml+xml\nAddOutputFilterByType DEFLATE application/rss+xml\nAddOutputFilterByType DEFLATE application/javascript\nAddOutputFilterByType DEFLATE application/x-javascript\n"
},
{
"code": null,
"e": 3092,
"s": 3040,
"text": "Restart the Apache Serversudo service httpd restart"
},
{
"code": null,
"e": 3119,
"s": 3092,
"text": "sudo service httpd restart"
},
{
"code": null,
"e": 3199,
"s": 3119,
"text": "Approach 2: HTML code can be minified with ob_start() function with a callback."
},
{
"code": "<?phpob_start(\"minifier\");function minifier($code) { $search = array( // Remove whitespaces after tags '/\\>[^\\S ]+/s', // Remove whitespaces before tags '/[^\\S ]+\\</s', // Remove multiple whitespace sequences '/(\\s)+/s', // Removes comments '/<!--(.|\\s)*?-->/' ); $replace = array('>', '<', '\\\\1'); $code = preg_replace($search, $replace, $code); return $code;}?><!DOCTYPE html><html> <head> <!-- title of page --> <title>Demo for minifier</title> </head> <body> <!-- body of page --> <h1>Hello World</h1> </body> </html> <?phpob_end_flush();?>",
"e": 3875,
"s": 3199,
"text": null
},
{
"code": null,
"e": 3883,
"s": 3875,
"text": "Output:"
},
{
"code": null,
"e": 3990,
"s": 3883,
"text": "<!DOCTYPE html><html><head><title>Demo for minifier</title></head><body><h1>Hello World</h1></body></html>"
},
{
"code": null,
"e": 4335,
"s": 3990,
"text": "Approach 3: Using HTMLMinifier plugin: HTML Minifier is a server-side source code minifier designed to optimise HTML, CSS and JavaScript output sent out to the client by removing unnecessary whitespaces, comments and newlines. HTMLMinifier offers a variety of optimisation options in the plugin that can be selected as per the user requirement."
},
{
"code": null,
"e": 4362,
"s": 4335,
"text": "Steps to use HTMLMinifier:"
},
{
"code": null,
"e": 4740,
"s": 4362,
"text": "Download the HTMLMinifier file from https://www.terresquall.com/download/HTMLMinifier.phpInclude the following code into the php file<?php // Import the HTMLMinifierrequire_once 'myfolder/HTMLMinifier.php'; // HTML source to be minified$htmlpage = file_get_contents('./mypage.html'); // Minified version of the pageecho HTMLMinifier::process($htmlpage); ?> Run the php file"
},
{
"code": null,
"e": 4830,
"s": 4740,
"text": "Download the HTMLMinifier file from https://www.terresquall.com/download/HTMLMinifier.php"
},
{
"code": null,
"e": 5103,
"s": 4830,
"text": "Include the following code into the php file<?php // Import the HTMLMinifierrequire_once 'myfolder/HTMLMinifier.php'; // HTML source to be minified$htmlpage = file_get_contents('./mypage.html'); // Minified version of the pageecho HTMLMinifier::process($htmlpage); ?> "
},
{
"code": "<?php // Import the HTMLMinifierrequire_once 'myfolder/HTMLMinifier.php'; // HTML source to be minified$htmlpage = file_get_contents('./mypage.html'); // Minified version of the pageecho HTMLMinifier::process($htmlpage); ?> ",
"e": 5332,
"s": 5103,
"text": null
},
{
"code": null,
"e": 5349,
"s": 5332,
"text": "Run the php file"
},
{
"code": null,
"e": 5358,
"s": 5349,
"text": "PHP-Misc"
},
{
"code": null,
"e": 5365,
"s": 5358,
"text": "Picked"
},
{
"code": null,
"e": 5369,
"s": 5365,
"text": "PHP"
},
{
"code": null,
"e": 5382,
"s": 5369,
"text": "PHP Programs"
},
{
"code": null,
"e": 5399,
"s": 5382,
"text": "Web Technologies"
},
{
"code": null,
"e": 5426,
"s": 5399,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5430,
"s": 5426,
"text": "PHP"
},
{
"code": null,
"e": 5528,
"s": 5430,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5573,
"s": 5528,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 5585,
"s": 5573,
"text": "PHP Cookies"
},
{
"code": null,
"e": 5618,
"s": 5585,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 5668,
"s": 5618,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 5708,
"s": 5668,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 5745,
"s": 5708,
"text": "How to get the file size using PHP ?"
},
{
"code": null,
"e": 5791,
"s": 5745,
"text": "String comparison using == vs strcmp() in PHP"
},
{
"code": null,
"e": 5850,
"s": 5791,
"text": "How to calculate the difference between two dates in PHP ?"
},
{
"code": null,
"e": 5908,
"s": 5850,
"text": "How to create comma separated list from an array in PHP ?"
}
] |
HeapSort - GeeksforGeeks
|
28 Jun, 2021
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element ... More on Heap Sort
(A)
(B)
(C)
(d)
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Software Testing - Web Based Testing
What are the different ways of Data Representation?
Bash Script - Command Substitution
SDE SHEET - A Complete Guide for SDE Preparation
7 Highest Paying Programming Languages For Freelancers in 2022
DSA Sheet by Love Babbar
How to Create a Shell Script in linux
How To Convert Numpy Array To Tensor?
7 Best React Project Ideas For Beginners in 2022
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 29850,
"s": 29577,
"text": "Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element ... More on Heap Sort "
},
{
"code": null,
"e": 29871,
"s": 29850,
"text": "(A) \n(B) \n(C) \n(d) "
},
{
"code": null,
"e": 29971,
"s": 29873,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30045,
"s": 29971,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 30082,
"s": 30045,
"text": "Software Testing - Web Based Testing"
},
{
"code": null,
"e": 30134,
"s": 30082,
"text": "What are the different ways of Data Representation?"
},
{
"code": null,
"e": 30169,
"s": 30134,
"text": "Bash Script - Command Substitution"
},
{
"code": null,
"e": 30218,
"s": 30169,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30281,
"s": 30218,
"text": "7 Highest Paying Programming Languages For Freelancers in 2022"
},
{
"code": null,
"e": 30306,
"s": 30281,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30344,
"s": 30306,
"text": "How to Create a Shell Script in linux"
},
{
"code": null,
"e": 30382,
"s": 30344,
"text": "How To Convert Numpy Array To Tensor?"
}
] |
Python program to check the validity of a Password?
|
Here given a password, our task is to check that this Password is valid or not. Here we use re module that provide regular expression and re.search() is used for checking the validation of alphabets, digits or special characters.
Step 1: first we take an alphanumeric string as a password.
Step 2: first check that this string should minimum 8 characters.
Step 3: the alphabets must be between a-z.
Step 4: At least one alphabet should be in Uppercase A-Z.
Step 5: At least 1 number or digit between 0-9.
Step 6: At least 1 character from [_ or @ or $].
# Python program to check valid password
import re
passw = input("Enter Password ::>")
fl = 0
while True:
if (len(passw)<8):
fl= -1
break
elif not re.search("[a-z]", passw):
fl = -1
break
elif not re.search("[A-Z]", passw):
fl = -1
break
elif not re.search("[0-9]", passw):
fl = -1
break
elif not re.search("[_@$]", passw):
fl = -1
break
elif re.search("\s", passw):
fl = -1
break
else:
fl = 0
print(" This Is Valid Password")
break
if fl ==-1:
print("Not a Valid Password")
Enter Password ::> vbnA@hj9
This Is Valid Password
|
[
{
"code": null,
"e": 1417,
"s": 1187,
"text": "Here given a password, our task is to check that this Password is valid or not. Here we use re module that provide regular expression and re.search() is used for checking the validation of alphabets, digits or special characters."
},
{
"code": null,
"e": 1742,
"s": 1417,
"text": "Step 1: first we take an alphanumeric string as a password.\nStep 2: first check that this string should minimum 8 characters.\nStep 3: the alphabets must be between a-z.\nStep 4: At least one alphabet should be in Uppercase A-Z.\nStep 5: At least 1 number or digit between 0-9.\nStep 6: At least 1 character from [_ or @ or $].\n"
},
{
"code": null,
"e": 2351,
"s": 1742,
"text": "# Python program to check valid password \nimport re \npassw = input(\"Enter Password ::>\")\nfl = 0\nwhile True: \n if (len(passw)<8): \n fl= -1\n break\n elif not re.search(\"[a-z]\", passw): \n fl = -1\n break\n elif not re.search(\"[A-Z]\", passw): \n fl = -1\n break\n elif not re.search(\"[0-9]\", passw): \n fl = -1\n break\n elif not re.search(\"[_@$]\", passw): \n fl = -1\n break\n elif re.search(\"\\s\", passw): \n fl = -1\n break\n else: \n fl = 0\n print(\" This Is Valid Password\") \n break\nif fl ==-1: \n print(\"Not a Valid Password\") "
},
{
"code": null,
"e": 2403,
"s": 2351,
"text": "Enter Password ::> vbnA@hj9\nThis Is Valid Password\n"
}
] |
Display Only Integer Values on ggplot2 Axis in R
|
23 May, 2021
A dataframe to be plotted can support multiple data types in it. Sometimes a float value isnβt appropriate since it hampers the clarity and readability of the plot. Thus, if these values were plotted as integers it would easier and clearer. In this article, we will be looking at the approach to display only values on ggplot2 axis in the r language.
In this approach of displaying only integer values on ggplot2 axis, user needs to first import and load the ggplot2 library and than call the geom_point() function present in the ggplot2 package and then pass the required parameters to the function and further this function will be returning the plot of the given values.
To load and install ggplot2 package user need to follow the below syntax.
Syntax:
install.packages(βggplot2β)
library(βggplot2β)
Here we will plot a scatter plot and for that geom_point() is used. This function is used to plot scatter plot which is most useful for displaying the relationship between two continuous variables.
Syntax:
geom_point(mapping = NULL,data = NULL,stat = βidentityβ,position = βidentityβ,...,na.rm = FALSE,show.legend = NA, inherit.aes = TRUE)
Dataset in consideration :
Let us first see how a regular plot without any modification of this dataframe would appear.
Example:
R
library("ggplot2") gfg_data <- data.frame(x=c(1,2,3,4,5,6,7,8,9,10), y=c(7,9,1,4,5,6,2,5,8,1)) gfg_plot <- ggplot(gfg_data, aes(x, y)) + geom_point() gfg_plot
Output:
Now we will be modifying the axis values of the plot plotted by ggplot2 using geom_point() function, this improving user needs to first load and install the scales library in R programming language, then, call the scale_x_continuous() and scale_y_continuous() function which basically removes non-integer numbers from ggplot2 axes needs from scales library and pass the required parameter into this function and in return, this function will modify the plot created by ggplot2 to the well-scaled plot to the user in r language.
scale_x_continuous() and scale_y_continuous() functions are used to make continuous position scales (x & y) or removes non-integer numbers.
Syntax:
scale_x_continuous(..., expand = waiver())
scale_y_continuous(..., expand = waiver())
Parameter:
...:-common continuous scale parameters: name, breaks, labels, na.value, limits and trans.
expand:-a numeric vector of length two giving multiplicative and additive expansion constants.
Example:
R
library("ggplot2")library("scales") gfg_data <- data.frame(x=c(1,2,3,4,5,6,7,8,9,10), y=c(7,9,1,4,5,6,2,5,8,1)) gfg_plot <- ggplot(gfg_data, aes(x, y)) + geom_point()gfg_plot + scale_x_continuous(breaks = pretty_breaks())+ scale_y_continuous(breaks = pretty_breaks())
Output:
Picked
R-ggplot
R Language
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?
R - if statement
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 379,
"s": 28,
"text": "A dataframe to be plotted can support multiple data types in it. Sometimes a float value isnβt appropriate since it hampers the clarity and readability of the plot. Thus, if these values were plotted as integers it would easier and clearer. In this article, we will be looking at the approach to display only values on ggplot2 axis in the r language."
},
{
"code": null,
"e": 703,
"s": 379,
"text": "In this approach of displaying only integer values on ggplot2 axis, user needs to first import and load the ggplot2 library and than call the geom_point() function present in the ggplot2 package and then pass the required parameters to the function and further this function will be returning the plot of the given values."
},
{
"code": null,
"e": 777,
"s": 703,
"text": "To load and install ggplot2 package user need to follow the below syntax."
},
{
"code": null,
"e": 785,
"s": 777,
"text": "Syntax:"
},
{
"code": null,
"e": 821,
"s": 785,
"text": "install.packages(βggplot2β) "
},
{
"code": null,
"e": 840,
"s": 821,
"text": "library(βggplot2β)"
},
{
"code": null,
"e": 1038,
"s": 840,
"text": "Here we will plot a scatter plot and for that geom_point() is used. This function is used to plot scatter plot which is most useful for displaying the relationship between two continuous variables."
},
{
"code": null,
"e": 1046,
"s": 1038,
"text": "Syntax:"
},
{
"code": null,
"e": 1180,
"s": 1046,
"text": "geom_point(mapping = NULL,data = NULL,stat = βidentityβ,position = βidentityβ,...,na.rm = FALSE,show.legend = NA, inherit.aes = TRUE)"
},
{
"code": null,
"e": 1207,
"s": 1180,
"text": "Dataset in consideration :"
},
{
"code": null,
"e": 1300,
"s": 1207,
"text": "Let us first see how a regular plot without any modification of this dataframe would appear."
},
{
"code": null,
"e": 1309,
"s": 1300,
"text": "Example:"
},
{
"code": null,
"e": 1311,
"s": 1309,
"text": "R"
},
{
"code": "library(\"ggplot2\") gfg_data <- data.frame(x=c(1,2,3,4,5,6,7,8,9,10), y=c(7,9,1,4,5,6,2,5,8,1)) gfg_plot <- ggplot(gfg_data, aes(x, y)) + geom_point() gfg_plot",
"e": 1495,
"s": 1311,
"text": null
},
{
"code": null,
"e": 1503,
"s": 1495,
"text": "Output:"
},
{
"code": null,
"e": 2031,
"s": 1503,
"text": "Now we will be modifying the axis values of the plot plotted by ggplot2 using geom_point() function, this improving user needs to first load and install the scales library in R programming language, then, call the scale_x_continuous() and scale_y_continuous() function which basically removes non-integer numbers from ggplot2 axes needs from scales library and pass the required parameter into this function and in return, this function will modify the plot created by ggplot2 to the well-scaled plot to the user in r language."
},
{
"code": null,
"e": 2171,
"s": 2031,
"text": "scale_x_continuous() and scale_y_continuous() functions are used to make continuous position scales (x & y) or removes non-integer numbers."
},
{
"code": null,
"e": 2179,
"s": 2171,
"text": "Syntax:"
},
{
"code": null,
"e": 2222,
"s": 2179,
"text": "scale_x_continuous(..., expand = waiver())"
},
{
"code": null,
"e": 2265,
"s": 2222,
"text": "scale_y_continuous(..., expand = waiver())"
},
{
"code": null,
"e": 2276,
"s": 2265,
"text": "Parameter:"
},
{
"code": null,
"e": 2367,
"s": 2276,
"text": "...:-common continuous scale parameters: name, breaks, labels, na.value, limits and trans."
},
{
"code": null,
"e": 2462,
"s": 2367,
"text": "expand:-a numeric vector of length two giving multiplicative and additive expansion constants."
},
{
"code": null,
"e": 2471,
"s": 2462,
"text": "Example:"
},
{
"code": null,
"e": 2473,
"s": 2471,
"text": "R"
},
{
"code": "library(\"ggplot2\")library(\"scales\") gfg_data <- data.frame(x=c(1,2,3,4,5,6,7,8,9,10), y=c(7,9,1,4,5,6,2,5,8,1)) gfg_plot <- ggplot(gfg_data, aes(x, y)) + geom_point()gfg_plot + scale_x_continuous(breaks = pretty_breaks())+ scale_y_continuous(breaks = pretty_breaks())",
"e": 2768,
"s": 2473,
"text": null
},
{
"code": null,
"e": 2776,
"s": 2768,
"text": "Output:"
},
{
"code": null,
"e": 2783,
"s": 2776,
"text": "Picked"
},
{
"code": null,
"e": 2792,
"s": 2783,
"text": "R-ggplot"
},
{
"code": null,
"e": 2803,
"s": 2792,
"text": "R Language"
},
{
"code": null,
"e": 2901,
"s": 2803,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2953,
"s": 2901,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3011,
"s": 2953,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3046,
"s": 3011,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3084,
"s": 3046,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3101,
"s": 3084,
"text": "R - if statement"
},
{
"code": null,
"e": 3150,
"s": 3101,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3187,
"s": 3150,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3230,
"s": 3187,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3267,
"s": 3230,
"text": "How to import an Excel File into R ?"
}
] |
Variation in Nim Game
|
15 Jun, 2022
Prerequisites: Sprague Gruncy theorem Grundy NumbersNim is a famous game in which two players take turns removing items from distinct piles. During each turn, a player must remove one or more items from a single, non-empty pile. The winner of the game is whichever player removes the last item from the last non-empty pile.
Now, For each non-empty pile, either player can remove zero items from that pile and have it count as their move; however, this move can only be performed once per pile by either player. Given the number of items in each pile, determine who will win the game; Player 1 or player 2. If player 1 starts the game and both plays optimally.
Examples:
Input : 3 [18, 47, 34]
Output : Player 2 wins
G = g(18)^g(47)^g(34) = (17)^(48)^(33) = 0
Grundy number(G), for this game is zero.
Player 2 wins.
Input : 3 [32, 49, 58]
Output : Player 1 wins
G = g(31)^g(50)^g(57) = (17)^(48)^(33) = 20
Grundy number(G), for this game is non-zero.
Player 1 wins.
Approach: Grundy number for each pile is calculated based on the number of stones.To compensate the zero move we will have to modify grundy values we used in standard nim game. If pile size is odd; grundy number is size+1 and if pile size is even; grundy number is size-1. We XOR all the grundy number values to check if final Grundy number(G) of game is non zero or not to decide who is winner of game.
Explanation: Grundy number of a state is the smallest positive integer that cannot be reached in one valid move. So, we need to calculate mex value for each n, bottom up wise so that we can induce the grundy number for each n. where n is the pile size.
Winning state: A tuple of values from where the current player will win the game no matter what opponent does. (If G!=0) Losing state: A tuple of values from where the current player will lose the game no matter what opponent does. (If G=0)
For a given pile size n, we have two states:
(1) n with no zero moves available,
grundy number will same as standard nim game.
(2) n with zero moves available, we can
reach above state and other states with
zero moves remaining.
For, n = 0, g(0) = 0, empty pile
For, n = 1, we can reach two states:
(1) n = 0 (zero move not used)
(2) n = 1 (zero move used)
Therefore, g(1) = mex{0, 1} which implies
that g(1)=2.
For, n = 2, we can reach :
(1) n = 0 (zero move not used) state
because this is a valid move.
(2) n = 1 (zero move not used) is a valid
move, whose grundy number is 2.
Therefore, g(2) = mex{0,2} which implies
that g(2)=1.
note that n=1 (zero move used) is not a valid
move.
If we try to build a solution bottom-up
like this, it turns out that if n is even,
the grundy number is n - 1 and when it is odd,
the grundy is n + 1.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program for the variation// in nim game#include <bits/stdc++.h>using namespace std; // Function to return final// grundy Number(G) of gameint solve(int p[], int n){ int G = 0; for (int i = 0; i < n; i++) { // if pile size is odd if (p[i] & 1) // We XOR pile size+1 G ^= (p[i] + 1); else // if pile size is even // We XOR pile size-1 G ^= (p[i] - 1); } return G;} // driver programint main(){ // Game with 3 piles int n = 3; // pile with different sizes int p[3] = { 32, 49, 58 }; // Function to return result of game int res = solve(p, n); if (res == 0) // if G is zero cout << "Player 2 wins"; else // if G is non zero cout << "Player 1 wins"; return 0;}
// Java program for the variation// in nim gameclass GFG { // Function to return final // grundy Number(G) of game static int solve(int p[], int n) { int G = 0; for (int i = 0; i < n; i++) { // if pile size is odd if (p[i]%2!=0) // We XOR pile size+1 G ^= (p[i] + 1); else // if pile size is even // We XOR pile size-1 G ^= (p[i] - 1); } return G; } //Driver code public static void main (String[] args) { // Game with 3 piles int n = 3; // pile with different sizes int p[] = { 32, 49, 58 }; // Function to return result of game int res = solve(p, n); if (res == 0) // if G is zero System.out.print("Player 2 wins"); else // if G is non zero System.out.print("Player 1 wins"); }} // This code is contributed by Anant Agarwal.
# Python3 program for the# variation in nim game # Function to return final# grundy Number(G) of gamedef solve(p, n): G = 0 for i in range(n): # if pile size is odd if (p[i] % 2 != 0): # We XOR pile size+1 G ^= (p[i] + 1) # if pile size is even else: # We XOR pile size-1 G ^= (p[i] - 1) return G # Driver code # Game with 3 pilesn = 3 # pile with different sizesp = [32, 49, 58] # Function to return result of gameres = solve(p, n) if (res == 0): # if G is zero print("Player 2 wins") else: # if G is non zero print("Player 1 wins") # This code is contributed by Anant Agarwal.
// C# program for the variation// in nim gameusing System;class GFG { // Function to return final // grundy Number(G) of game static int solve(int[] p, int n) { int G = 0; for (int i = 0; i < n; i++) { // if pile size is odd if (p[i] % 2 != 0) // We XOR pile size+1 G ^= (p[i] + 1); else // if pile size is even // We XOR pile size-1 G ^= (p[i] - 1); } return G; } // Driver code public static void Main() { // Game with 3 piles int n = 3; // pile with different sizes int[] p = { 32, 49, 58 }; // Function to return result of game int res = solve(p, n); if (res == 0) // if G is zero Console.WriteLine("Player 2 wins"); else // if G is non zero Console.WriteLine("Player 1 wins"); }} // This code is contributed by vt_m.
<?php// php program for the variation// in nim game // Function to return final// grundy Number(G) of gamefunction solve($p,$n){ $G = 0; for ($i = 0; $i < $n; $i++) { // if pile size is odd if ($p[$i] & 1) // We XOR pile size+1 $G ^= ($p[$i] + 1); else // if pile size is even // We XOR pile size-1 $G ^= ($p[$i] - 1); } return $G;} // Driver Code // Game with 3 piles $n = 3; // pile with different sizes $p= array( 32, 49, 58 ); // Function to return result of game $res = solve($p, $n); if ($res == 0) // if G is zero echo "Player 2 wins"; else // if G is non zero echo "Player 1 wins"; // This code is contributed by mits?>
<script> // Javascript program for the variation// in nim game // Function to return final// grundy Number(G) of gamefunction solve(p, n){ let G = 0; for(let i = 0; i < n; i++) { // If pile size is odd if (p[i] % 2 != 0) // We XOR pile size+1 G ^= (p[i] + 1); // If pile size is even else // We XOR pile size-1 G ^= (p[i] - 1); } return G;} // Driver code // Game with 3 pileslet n = 3; // Pile with different sizeslet p = [ 32, 49, 58 ]; // Function to return result of gamelet res = solve(p, n); // If G is zeroif (res == 0) document.write("Player 2 wins"); // If G is non zeroelse document.write("Player 1 wins"); // This code is contributed by sanjoy_62 </script>
Output:
Player 1 wins
Time Complexity: O(n)Space Complexity: O(n)
Mithun Kumar
Akanksha_Rai
ad_1608
sanjoy_62
AshokJaiswal
ranjanrohit840
Bit Magic
Competitive Programming
Game Theory
Technical Scripter
Bit Magic
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 379,
"s": 54,
"text": "Prerequisites: Sprague Gruncy theorem Grundy NumbersNim is a famous game in which two players take turns removing items from distinct piles. During each turn, a player must remove one or more items from a single, non-empty pile. The winner of the game is whichever player removes the last item from the last non-empty pile. "
},
{
"code": null,
"e": 715,
"s": 379,
"text": "Now, For each non-empty pile, either player can remove zero items from that pile and have it count as their move; however, this move can only be performed once per pile by either player. Given the number of items in each pile, determine who will win the game; Player 1 or player 2. If player 1 starts the game and both plays optimally."
},
{
"code": null,
"e": 726,
"s": 715,
"text": "Examples: "
},
{
"code": null,
"e": 1024,
"s": 726,
"text": "Input : 3 [18, 47, 34]\nOutput : Player 2 wins\nG = g(18)^g(47)^g(34) = (17)^(48)^(33) = 0\nGrundy number(G), for this game is zero.\nPlayer 2 wins. \n\nInput : 3 [32, 49, 58]\nOutput : Player 1 wins\nG = g(31)^g(50)^g(57) = (17)^(48)^(33) = 20\nGrundy number(G), for this game is non-zero.\nPlayer 1 wins. "
},
{
"code": null,
"e": 1428,
"s": 1024,
"text": "Approach: Grundy number for each pile is calculated based on the number of stones.To compensate the zero move we will have to modify grundy values we used in standard nim game. If pile size is odd; grundy number is size+1 and if pile size is even; grundy number is size-1. We XOR all the grundy number values to check if final Grundy number(G) of game is non zero or not to decide who is winner of game."
},
{
"code": null,
"e": 1681,
"s": 1428,
"text": "Explanation: Grundy number of a state is the smallest positive integer that cannot be reached in one valid move. So, we need to calculate mex value for each n, bottom up wise so that we can induce the grundy number for each n. where n is the pile size."
},
{
"code": null,
"e": 1924,
"s": 1681,
"text": "Winning state: A tuple of values from where the current player will win the game no matter what opponent does. (If G!=0) Losing state: A tuple of values from where the current player will lose the game no matter what opponent does. (If G=0) "
},
{
"code": null,
"e": 2776,
"s": 1924,
"text": "For a given pile size n, we have two states:\n(1) n with no zero moves available, \ngrundy number will same as standard nim game.\n(2) n with zero moves available, we can\nreach above state and other states with \nzero moves remaining. \n\nFor, n = 0, g(0) = 0, empty pile\n\nFor, n = 1, we can reach two states:\n(1) n = 0 (zero move not used)\n(2) n = 1 (zero move used) \nTherefore, g(1) = mex{0, 1} which implies\nthat g(1)=2.\n\nFor, n = 2, we can reach :\n(1) n = 0 (zero move not used) state \nbecause this is a valid move.\n(2) n = 1 (zero move not used) is a valid\n move, whose grundy number is 2.\nTherefore, g(2) = mex{0,2} which implies \nthat g(2)=1. \nnote that n=1 (zero move used) is not a valid\nmove.\n\nIf we try to build a solution bottom-up\nlike this, it turns out that if n is even, \nthe grundy number is n - 1 and when it is odd,\nthe grundy is n + 1."
},
{
"code": null,
"e": 2824,
"s": 2776,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 2828,
"s": 2824,
"text": "C++"
},
{
"code": null,
"e": 2833,
"s": 2828,
"text": "Java"
},
{
"code": null,
"e": 2841,
"s": 2833,
"text": "Python3"
},
{
"code": null,
"e": 2844,
"s": 2841,
"text": "C#"
},
{
"code": null,
"e": 2848,
"s": 2844,
"text": "PHP"
},
{
"code": null,
"e": 2859,
"s": 2848,
"text": "Javascript"
},
{
"code": "// CPP program for the variation// in nim game#include <bits/stdc++.h>using namespace std; // Function to return final// grundy Number(G) of gameint solve(int p[], int n){ int G = 0; for (int i = 0; i < n; i++) { // if pile size is odd if (p[i] & 1) // We XOR pile size+1 G ^= (p[i] + 1); else // if pile size is even // We XOR pile size-1 G ^= (p[i] - 1); } return G;} // driver programint main(){ // Game with 3 piles int n = 3; // pile with different sizes int p[3] = { 32, 49, 58 }; // Function to return result of game int res = solve(p, n); if (res == 0) // if G is zero cout << \"Player 2 wins\"; else // if G is non zero cout << \"Player 1 wins\"; return 0;}",
"e": 3659,
"s": 2859,
"text": null
},
{
"code": "// Java program for the variation// in nim gameclass GFG { // Function to return final // grundy Number(G) of game static int solve(int p[], int n) { int G = 0; for (int i = 0; i < n; i++) { // if pile size is odd if (p[i]%2!=0) // We XOR pile size+1 G ^= (p[i] + 1); else // if pile size is even // We XOR pile size-1 G ^= (p[i] - 1); } return G; } //Driver code public static void main (String[] args) { // Game with 3 piles int n = 3; // pile with different sizes int p[] = { 32, 49, 58 }; // Function to return result of game int res = solve(p, n); if (res == 0) // if G is zero System.out.print(\"Player 2 wins\"); else // if G is non zero System.out.print(\"Player 1 wins\"); }} // This code is contributed by Anant Agarwal.",
"e": 4696,
"s": 3659,
"text": null
},
{
"code": "# Python3 program for the# variation in nim game # Function to return final# grundy Number(G) of gamedef solve(p, n): G = 0 for i in range(n): # if pile size is odd if (p[i] % 2 != 0): # We XOR pile size+1 G ^= (p[i] + 1) # if pile size is even else: # We XOR pile size-1 G ^= (p[i] - 1) return G # Driver code # Game with 3 pilesn = 3 # pile with different sizesp = [32, 49, 58] # Function to return result of gameres = solve(p, n) if (res == 0): # if G is zero print(\"Player 2 wins\") else: # if G is non zero print(\"Player 1 wins\") # This code is contributed by Anant Agarwal.",
"e": 5399,
"s": 4696,
"text": null
},
{
"code": "// C# program for the variation// in nim gameusing System;class GFG { // Function to return final // grundy Number(G) of game static int solve(int[] p, int n) { int G = 0; for (int i = 0; i < n; i++) { // if pile size is odd if (p[i] % 2 != 0) // We XOR pile size+1 G ^= (p[i] + 1); else // if pile size is even // We XOR pile size-1 G ^= (p[i] - 1); } return G; } // Driver code public static void Main() { // Game with 3 piles int n = 3; // pile with different sizes int[] p = { 32, 49, 58 }; // Function to return result of game int res = solve(p, n); if (res == 0) // if G is zero Console.WriteLine(\"Player 2 wins\"); else // if G is non zero Console.WriteLine(\"Player 1 wins\"); }} // This code is contributed by vt_m.",
"e": 6372,
"s": 5399,
"text": null
},
{
"code": "<?php// php program for the variation// in nim game // Function to return final// grundy Number(G) of gamefunction solve($p,$n){ $G = 0; for ($i = 0; $i < $n; $i++) { // if pile size is odd if ($p[$i] & 1) // We XOR pile size+1 $G ^= ($p[$i] + 1); else // if pile size is even // We XOR pile size-1 $G ^= ($p[$i] - 1); } return $G;} // Driver Code // Game with 3 piles $n = 3; // pile with different sizes $p= array( 32, 49, 58 ); // Function to return result of game $res = solve($p, $n); if ($res == 0) // if G is zero echo \"Player 2 wins\"; else // if G is non zero echo \"Player 1 wins\"; // This code is contributed by mits?>",
"e": 7141,
"s": 6372,
"text": null
},
{
"code": "<script> // Javascript program for the variation// in nim game // Function to return final// grundy Number(G) of gamefunction solve(p, n){ let G = 0; for(let i = 0; i < n; i++) { // If pile size is odd if (p[i] % 2 != 0) // We XOR pile size+1 G ^= (p[i] + 1); // If pile size is even else // We XOR pile size-1 G ^= (p[i] - 1); } return G;} // Driver code // Game with 3 pileslet n = 3; // Pile with different sizeslet p = [ 32, 49, 58 ]; // Function to return result of gamelet res = solve(p, n); // If G is zeroif (res == 0) document.write(\"Player 2 wins\"); // If G is non zeroelse document.write(\"Player 1 wins\"); // This code is contributed by sanjoy_62 </script>",
"e": 7952,
"s": 7141,
"text": null
},
{
"code": null,
"e": 7961,
"s": 7952,
"text": "Output: "
},
{
"code": null,
"e": 7975,
"s": 7961,
"text": "Player 1 wins"
},
{
"code": null,
"e": 8020,
"s": 7975,
"text": "Time Complexity: O(n)Space Complexity: O(n) "
},
{
"code": null,
"e": 8033,
"s": 8020,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8046,
"s": 8033,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 8054,
"s": 8046,
"text": "ad_1608"
},
{
"code": null,
"e": 8064,
"s": 8054,
"text": "sanjoy_62"
},
{
"code": null,
"e": 8077,
"s": 8064,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 8092,
"s": 8077,
"text": "ranjanrohit840"
},
{
"code": null,
"e": 8102,
"s": 8092,
"text": "Bit Magic"
},
{
"code": null,
"e": 8126,
"s": 8102,
"text": "Competitive Programming"
},
{
"code": null,
"e": 8138,
"s": 8126,
"text": "Game Theory"
},
{
"code": null,
"e": 8157,
"s": 8138,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8167,
"s": 8157,
"text": "Bit Magic"
},
{
"code": null,
"e": 8179,
"s": 8167,
"text": "Game Theory"
}
] |
Java Examples - Display a colors in a frame
|
How to display colours in a frame?
Following example displays how to a display all the colors in a frame using setRGB method of image class.
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Main extends JComponent {
BufferedImage image;
public void initialize() {
int width = getSize().width;
int height = getSize().height;
int[] data = new int[width * height];
int index = 0;
for (int i = 0; i < height; i++) {
int red = (i * 255) / (height - 1);
for (int j = 0; j < width; j++) {
int green = (j * 255) / (width - 1);
int blue = 128;
data[index++] = (red<<16) | (green<<8) | blue;
}
}
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, width, height, data, 0, width);
}
public void paint(Graphics g) {
if (image == null)
initialize();
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) {
JFrame f = new JFrame("Display Colours");
f.getContentPane().add(new Main());
f.setSize(300, 300);
f.setLocation(100, 100);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setVisible(true);
}
}
The above code sample will produce the following result.
Displays all the colours in a frame.
The following is an example to display colours in a frame.
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Panel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
displayJFrame();
}
});
}
static void displayJFrame() {
JFrame frame = new JFrame("Tutorialspoint");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.red);
frame.setPreferredSize(new Dimension(400, 300));
|
[
{
"code": null,
"e": 2237,
"s": 2202,
"text": "How to display colours in a frame?"
},
{
"code": null,
"e": 2343,
"s": 2237,
"text": "Following example displays how to a display all the colors in a frame using setRGB method of image class."
},
{
"code": null,
"e": 3693,
"s": 2343,
"text": "import java.awt.Graphics;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.awt.image.BufferedImage;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\n\npublic class Main extends JComponent {\n BufferedImage image;\n public void initialize() {\n int width = getSize().width;\n int height = getSize().height;\n int[] data = new int[width * height];\n int index = 0;\n \n for (int i = 0; i < height; i++) {\n int red = (i * 255) / (height - 1);\n for (int j = 0; j < width; j++) {\n int green = (j * 255) / (width - 1);\n int blue = 128;\n data[index++] = (red<<16) | (green<<8) | blue;\n }\n }\n image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\n image.setRGB(0, 0, width, height, data, 0, width);\n }\n public void paint(Graphics g) {\n if (image == null)\n initialize();\n g.drawImage(image, 0, 0, this);\n }\n public static void main(String[] args) {\n JFrame f = new JFrame(\"Display Colours\");\n f.getContentPane().add(new Main());\n f.setSize(300, 300);\n f.setLocation(100, 100);\n f.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent e) {\n System.exit(0);\n }\n });\n f.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 3750,
"s": 3693,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3788,
"s": 3750,
"text": "Displays all the colours in a frame.\n"
},
{
"code": null,
"e": 3847,
"s": 3788,
"text": "The following is an example to display colours in a frame."
}
] |
QuickSort - GeeksforGeeks
|
28 Jun, 2021
Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways ... More on Quick Sort
2 5 1 7 9 12 11 10
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Git - Difference Between Git Fetch and Git Pull
ReactJS useNavigate() Hook
SDE SHEET - A Complete Guide for SDE Preparation
How to Install and Use NVM on Windows?
DSA Sheet by Love Babbar
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Spring Boot - Exception Handling
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 29828,
"s": 29577,
"text": "Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways ... More on Quick Sort"
},
{
"code": null,
"e": 29855,
"s": 29828,
"text": "2 5 1 7 9 12 11 10 "
},
{
"code": null,
"e": 29955,
"s": 29857,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30029,
"s": 29955,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 30082,
"s": 30029,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 30130,
"s": 30082,
"text": "Git - Difference Between Git Fetch and Git Pull"
},
{
"code": null,
"e": 30157,
"s": 30130,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 30206,
"s": 30157,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30245,
"s": 30206,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 30270,
"s": 30245,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30283,
"s": 30270,
"text": "Java Threads"
},
{
"code": null,
"e": 30335,
"s": 30283,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
}
] |
Replace Spaces in Column Names in R DataFrame
|
23 Sep, 2021
In this article, we will replace spaces in column names of a dataframe in R Programming Language.
Letβs create a Dataframe with 4 columns with 3 rows:
R
# create a dataframe with 4 columns and 3 rowsdata = data.frame("web technologies" = c("php","html","js"), "backend tech" = c("sql","oracle","mongodb"), "middle ware technology" = c("java",".net","python")) # displaydata
Output:
In the above example, we can see that there are blank spaces in column names, so we will replace that blank spaces
In this methods we will use gsub function, gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is.
Syntax: gsub(β β, βreplaceβ, colnames(dataframe))
Parameters:
first parameter takes space
second parameter takes replacing character that replaces blank space
third parameter takes column names of the dataframe by using colnames() function
Example: R program to create a dataframe and replace dataframe columns with different synbols
R
# create a dataframe with 4 columns and 3 rowsdata=data.frame("web technologies"=c("php","html","js"), "backend tech"=c("sql","oracle","mongodb"), "middle ware technology"= c("java",".net","python"), check.names=FALSE) # replace blank with underscore print( gsub(" ", "_", colnames(data))) # replace blank with dot operator print( gsub(" ", ".", colnames(data))) # replace blank with * operator print( gsub(" ", "*", colnames(data)))
Output:
[1] βweb_technologiesβ βbackend__techβ βmiddle_ware_technologyβ
[1] βweb.technologiesβ βbackend..techβ βmiddle.ware.technologyβ
[1] βweb*technologiesβ βbackend**techβ βmiddle*ware*technologyβ
We can do this by using make.names() function.
Syntax: make.names(colnames(dataframe))
Where, dataframe is the input dataframe
Example: R program to replace dataframe column names using make.names
R
# create a dataframe with 4 columns and 3 rowsdata = data.frame("web technologies" = c("php","html","js"), "backend tech" = c("sql","oracle","mongodb"), "middle ware technology" = c("java",".net","python"), check.names = FALSE) # replace blank by using make.names print( make.names(colnames(data)))
Output:
[1] βweb.technologiesβ βbackend..techβ βmiddle.ware.technologyβ
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "In this article, we will replace spaces in column names of a dataframe in R Programming Language."
},
{
"code": null,
"e": 179,
"s": 126,
"text": "Letβs create a Dataframe with 4 columns with 3 rows:"
},
{
"code": null,
"e": 181,
"s": 179,
"text": "R"
},
{
"code": "# create a dataframe with 4 columns and 3 rowsdata = data.frame(\"web technologies\" = c(\"php\",\"html\",\"js\"), \"backend tech\" = c(\"sql\",\"oracle\",\"mongodb\"), \"middle ware technology\" = c(\"java\",\".net\",\"python\")) # displaydata",
"e": 439,
"s": 181,
"text": null
},
{
"code": null,
"e": 447,
"s": 439,
"text": "Output:"
},
{
"code": null,
"e": 562,
"s": 447,
"text": "In the above example, we can see that there are blank spaces in column names, so we will replace that blank spaces"
},
{
"code": null,
"e": 764,
"s": 562,
"text": "In this methods we will use gsub function, gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is."
},
{
"code": null,
"e": 814,
"s": 764,
"text": "Syntax: gsub(β β, βreplaceβ, colnames(dataframe))"
},
{
"code": null,
"e": 826,
"s": 814,
"text": "Parameters:"
},
{
"code": null,
"e": 854,
"s": 826,
"text": "first parameter takes space"
},
{
"code": null,
"e": 923,
"s": 854,
"text": "second parameter takes replacing character that replaces blank space"
},
{
"code": null,
"e": 1004,
"s": 923,
"text": "third parameter takes column names of the dataframe by using colnames() function"
},
{
"code": null,
"e": 1098,
"s": 1004,
"text": "Example: R program to create a dataframe and replace dataframe columns with different synbols"
},
{
"code": null,
"e": 1100,
"s": 1098,
"text": "R"
},
{
"code": "# create a dataframe with 4 columns and 3 rowsdata=data.frame(\"web technologies\"=c(\"php\",\"html\",\"js\"), \"backend tech\"=c(\"sql\",\"oracle\",\"mongodb\"), \"middle ware technology\"= c(\"java\",\".net\",\"python\"), check.names=FALSE) # replace blank with underscore print( gsub(\" \", \"_\", colnames(data))) # replace blank with dot operator print( gsub(\" \", \".\", colnames(data))) # replace blank with * operator print( gsub(\" \", \"*\", colnames(data)))",
"e": 1629,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1637,
"s": 1629,
"text": "Output:"
},
{
"code": null,
"e": 1716,
"s": 1637,
"text": "[1] βweb_technologiesβ βbackend__techβ βmiddle_ware_technologyβ"
},
{
"code": null,
"e": 1795,
"s": 1716,
"text": "[1] βweb.technologiesβ βbackend..techβ βmiddle.ware.technologyβ"
},
{
"code": null,
"e": 1874,
"s": 1795,
"text": "[1] βweb*technologiesβ βbackend**techβ βmiddle*ware*technologyβ"
},
{
"code": null,
"e": 1921,
"s": 1874,
"text": "We can do this by using make.names() function."
},
{
"code": null,
"e": 1961,
"s": 1921,
"text": "Syntax: make.names(colnames(dataframe))"
},
{
"code": null,
"e": 2001,
"s": 1961,
"text": "Where, dataframe is the input dataframe"
},
{
"code": null,
"e": 2071,
"s": 2001,
"text": "Example: R program to replace dataframe column names using make.names"
},
{
"code": null,
"e": 2073,
"s": 2071,
"text": "R"
},
{
"code": "# create a dataframe with 4 columns and 3 rowsdata = data.frame(\"web technologies\" = c(\"php\",\"html\",\"js\"), \"backend tech\" = c(\"sql\",\"oracle\",\"mongodb\"), \"middle ware technology\" = c(\"java\",\".net\",\"python\"), check.names = FALSE) # replace blank by using make.names print( make.names(colnames(data)))",
"e": 2443,
"s": 2073,
"text": null
},
{
"code": null,
"e": 2451,
"s": 2443,
"text": "Output:"
},
{
"code": null,
"e": 2530,
"s": 2451,
"text": "[1] βweb.technologiesβ βbackend..techβ βmiddle.ware.technologyβ"
},
{
"code": null,
"e": 2537,
"s": 2530,
"text": "Picked"
},
{
"code": null,
"e": 2558,
"s": 2537,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 2570,
"s": 2558,
"text": "R-DataFrame"
},
{
"code": null,
"e": 2581,
"s": 2570,
"text": "R Language"
},
{
"code": null,
"e": 2592,
"s": 2581,
"text": "R Programs"
}
] |
Lodash _.startCase() Method
|
03 Sep, 2020
The _.startCase() method is used to convert the string to start the case.
Syntax:
_.startCase( [string=''] )
Parameters: This method accepts a single parameter as mentioned above and described below:
string: This parameter holds the string to convert.
Return Value: This method returns the start of the case string.
Below example illustrate the Lodash _.startCase() method in JavaScript:
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.startCase() method console.log(_.startCase('geeks for geeks')); console.log(_.startCase('geeksforgeeks'));console.log(_.startCase('@#$%geeksforgeeks@#$%'));
Output:
'Geeks For Geeks'
'Geeksforgeeks'
'Geeksforgeeks'
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.startCase() method console.log(_.startCase(null)); console.log(_.startCase('123456789'));console.log(_.startCase("gfg.Id"));
Output:
''
'123456789'
'Gfg Id'
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Sep, 2020"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "The _.startCase() method is used to convert the string to start the case."
},
{
"code": null,
"e": 110,
"s": 102,
"text": "Syntax:"
},
{
"code": null,
"e": 138,
"s": 110,
"text": "_.startCase( [string=''] )\n"
},
{
"code": null,
"e": 229,
"s": 138,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 281,
"s": 229,
"text": "string: This parameter holds the string to convert."
},
{
"code": null,
"e": 345,
"s": 281,
"text": "Return Value: This method returns the start of the case string."
},
{
"code": null,
"e": 417,
"s": 345,
"text": "Below example illustrate the Lodash _.startCase() method in JavaScript:"
},
{
"code": null,
"e": 428,
"s": 417,
"text": "Example 1:"
},
{
"code": null,
"e": 439,
"s": 428,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.startCase() method console.log(_.startCase('geeks for geeks')); console.log(_.startCase('geeksforgeeks'));console.log(_.startCase('@#$%geeksforgeeks@#$%'));",
"e": 678,
"s": 439,
"text": null
},
{
"code": null,
"e": 686,
"s": 678,
"text": "Output:"
},
{
"code": null,
"e": 737,
"s": 686,
"text": "'Geeks For Geeks'\n'Geeksforgeeks'\n'Geeksforgeeks'\n"
},
{
"code": null,
"e": 750,
"s": 737,
"text": "Example 2: "
},
{
"code": null,
"e": 761,
"s": 750,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.startCase() method console.log(_.startCase(null)); console.log(_.startCase('123456789'));console.log(_.startCase(\"gfg.Id\"));",
"e": 968,
"s": 761,
"text": null
},
{
"code": null,
"e": 976,
"s": 968,
"text": "Output:"
},
{
"code": null,
"e": 1001,
"s": 976,
"text": "''\n'123456789'\n'Gfg Id'\n"
},
{
"code": null,
"e": 1019,
"s": 1001,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1030,
"s": 1019,
"text": "JavaScript"
},
{
"code": null,
"e": 1047,
"s": 1030,
"text": "Web Technologies"
}
] |
K-Means Clustering and PCA to categorize music by similar audio features | by Sejal Dua | Towards Data Science
|
A year ago, life was much simpler. It was a bustling Tuesday morning in early October, and I was riding the metro to my Artificial Neural Network class in downtown Copenhagen. I was browsing my Spotify library for a playlist to shuffle for the duration of my commute when I bumped into my friend Liddy. I asked for her input, and she told me something which actually kind of changed my life. She said, βOh Sejal, I am far too indecisive to pick a playlist based on my mood. I actually create a new playlist and add to it on the first day of each month.β
With the increased diversity in music that we have seen on streaming platforms such as Spotify, Apple Music, and Soundcloud in the past decade, the lines separating genres have become even more blurred than they were previously.
Genre labels are broad umbrella terms that are used to describe music that vary greatly in their characteristics. If someone asks you what kind of music you like, responding with βRockβ or βIndieβ does not really say much without namedropping a few artists.
Genres are always evolving over time. If someone says they are a fan of pop music, how do you know if they are referring to Michael Jackson or Justin Bieber?
They are often socially driven with little to do with the actual characteristics of the music.
Fortunately, there has been a movement towards labeling music solely based on musical characteristics or attributes. However, organizing music based on these audio features is still a complicated task, even for a human.
Ever since Liddy inspired me with the idea to organize my music by time period, I have been hooked. It helps me to embrace the chaos of my diverse and far-ranging music taste while still being able to compartmentalize my music based on certain phases of life.
The issue, though, is that when I clicking βShuffleβ on my 2020 playlist of 449 songs, I end up skipping 9/10 songs because I can never seem to find a song that fits the mood. So I set out to find a solution to my problem using a machine learning technique called k-means clustering and Principal Component Analysis (PCA), a dimensionality reduction technique.
The Spotify Developer API allows you to get audio features for a track. These features are described in more detail below:
acousticness: [0β1] Confidence measure of whether the track is acoustic.
danceability: [0β1] Describes how suitable a track is for dancing based on musical attributes including tempo, rhythm, stability, beat strength, and overall regularity.
energy: [0β1] Perceptual measure of intensity and activity. Energetic tracks feel fast, loud, and noisy (e.g. death metal: high energy, Bach prelude: low energy).
instrumentalness: [0β1] Predicts whether a track contains no vocals (values above 0.5 represent instrumental tracks whereas rap songs would have a score close to 0).
liveness: [0β1] Detects the presence of an audience in the recording.
loudness: [-60β0 dB] The average volume across an entire track.
speechiness: [0β1] Detects the presence of spoken words in a track (values above 0.66 describe tracks that are probably made entirely of spoken words, 0.33β0.66 describe tracks that may contain both music and speech, and values below 0.33 most likely represent music and other non-speech-like tracks).
valence: [0β1] Describes the musical positiveness conveyed by a track. Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), while tracks with low valence sound more negative (e.g. sad, depressed, angry).
tempo: [0β300 BPM] The speed or pace of a given piece, as derived from the estimated average beat duration.
I use Spotipy, which is a Python wrapper for Spotifyβs Developer API. First, we must create a token with our API credentials.
I then extracted metadata (name, artist name, and URI) for each track in the playlist and acquired the audio feature data described above.
Next, we can form our training data by excluding columns in the DataFrame that are not audio features. We also have to do one more critical step: standardization. Standardization is the process of putting different features on the same scale, with each scaled feature having a mean of 0 and a standard deviation of 1. This is important because the model is not familiar with the context of the data. If we do not standardize our X_train data, the model would place a much larger weight on tempo and loudness, since those variables vary by much more than the variables that are distributed in the range from 0 to 1. Standardization allows for all features to be treated equally by the model. We can accomplish this step by using sklearnβs StandardScaler import.
from sklearn.preprocessing import StandardScalerscaler = StandardScaler()X_std = scaler.fit_transform(df_X)
What is dimensionality reduction? Well, as we can see from the image above, it is a process that involves using linear algebraic operations to transform n-dimensional data to (n-k)-dimensional data. In this example, we are just reducing 3-dimensional data into 2-dimensional data, so n equals 3 and k equals 1. As you might imagine, some information is lost in this transformation, but we still get a fairly decent approximation with the tremendous benefit of being able to visualize the data. Moreover, we can also effectively reduce the complexity of the problem by reducing the number of variables.
Principal Component Analysis (PCA) is a dimensionality reduction approach which attempts to find the best possible subspace that explains most of the variance in the data. It works by deriving components from the original scaled features. From these components, the two most significant ones are typically plotted, depicting the simplified data space.
After fitting a PCA object to the standardized matrix, we can see how much of the variance is explained by each of the nine features.
from sklearn.decomposition import PCApca = PCA()pca.fit(X_std)evr = pca.explained_variance_ratio_print(evr)
To inform our decision of how many features to use for our k-means clustering algorithm, it is helpful to make a cumulative variance plot using the evr.cumsum() function and matplotlib.
From this plot, we can observe that each of the principal components explain a pretty considerable amount of variance. However, we do not need to keep all of these components. In general, it is a good rule of thumb to preserve around 80% of the variance. Therefore, in this instance, we can select the 6 most important principal components to incorporate in the k-means algorithm. This can be accomplished by instantiating a new PCA object with the n_components parameter set to 6.
Having finished our PCA, we now have components which explain most of the variance in the data. From this point on, it is going to be very difficult to interpret meaning when analyzing the numeric differences in tracks because the vectorized audio features have been transformed into a new subspace. However, after implementing k-means Clustering, we will be able to inspect the raw data, and we can even visualize our clusters of similar songs on the same 2D-plane.
In order to implement k-means clustering, we must select a number of clusters, k, which distinctly splits the data. Given that we do not have a desired amount of groupings for the huge playlist that we would like to split, and we want this code to be reproducible, we must use an algorithmic approach to determine the optimal value for k. There are actually numerous algorithmic approaches, including but not limited to the elbow method, the silhouette method, and the gap statistic. Letβs take a closer look into the elbow method, which is arguably the most popular technique.
The basic principle of k-means clustering is to define clusters such that the total intra-cluster variation is minimized. The within-cluster sum of squares (WCSS) is a metric which can quantify this partitioning effect. It essentially measures the compactness of the clustering. The optimal number of clusters can be found by executing a simple procedure:
Implement clustering algorithm for varying values of k, ranging from 1 to 20 clusters.For each k, compute the within-cluster sum of squares (WCSS) by storing the inertia value in a list after the model has been fitted.Plot the WCSS curve according to the number of clusters k.Look for a kink or elbow in the WCSS graph. Usually, the part of the graph before the elbow would be steeply declining, while the part after it β much smoother. [NOTE: there are ways to locate the elbow (a.k.a. βkneeβ) point programmatically, including an open source Python library called kneed or a visualization library called Yellowbrick]
Implement clustering algorithm for varying values of k, ranging from 1 to 20 clusters.
For each k, compute the within-cluster sum of squares (WCSS) by storing the inertia value in a list after the model has been fitted.
Plot the WCSS curve according to the number of clusters k.
Look for a kink or elbow in the WCSS graph. Usually, the part of the graph before the elbow would be steeply declining, while the part after it β much smoother. [NOTE: there are ways to locate the elbow (a.k.a. βkneeβ) point programmatically, including an open source Python library called kneed or a visualization library called Yellowbrick]
Running the code snippet above yields the following WCSS curve shown below. The KneeLocator method has determined that 7 is the ideal number of clusters or distinct groupings to be used in order to separate the 449 tracks in my absurdly lengthy playlist.
Now, all that is left to do is to implement k-means clustering once and for all. With the help of sklearn, we can obtain the cluster labels for each track in just 3 lines of code.
kmeans_pca = KMeans(n_clusters=n_clusters, init='k-means++', random_state=42)kmeans_pca.fit(scores_pca)df['Cluster'] = kmeans_pca.labels_
The cluster labels in the rightmost column of the DataFrame screenshot above are the βresultsβ of this ML technique. Okay... this was a bit anticlimactic. What good do these cluster labels do? Well, letβs investigate them further.
While k-means clustering is not a supervised machine learning techniqueβmeaning we cannot verify whether the results are accurate or notβwe can visualize the clusters on a 2D plane to ensure that there is some sensical separation of data based on the sources of signals that are encapsulated by the components. In the figure above, it is clear that Cluster 5 is most similar to Clusters 1 and 3 and that Cluster 4 is quite loosely defined, overlapping with a few other clusters. Despite some noise, there are clear groupings of tracks, as indicated by the concentrated areas of green, red, orange, and blue data points. Additionally, this is only a 2D visualization of a 6-dimensional vector space, so more analysis is needed in order to determine the efficacy of the k-means algorithm.
Since meaning cannot be inferred from the transformed components, letβs take a look at the raw values for the audio features of the tracks after they have been clustered. A radar chart can be really powerful in this type of analysis because it allows us to make some quick observations about each cluster.
In the figure below, the a radar trace has been plotted for the average audio feature values in each cluster, after normalizing the entire dataframe. Acousticness is a Spotify-defined variable between 0 and 1 while tempo can be in the 100s. Normalization is important because it effectively scales all variables to have values between 0 and 1, making the following visualization far more meaningful.
After a quick glance, it is evident that Cluster 2 is most acoustic-sounding, Cluster 4 consists of live-sounding tracks, Cluster 5 contains the most verbose tracks, and Cluster 6 is characterized by more instrumental tracks. Features like energy, danceability, valence, tempo, and loudness did not contain strong enough sources of signal on which to split the data. That being said, some combination of high danceability, tempo, and energy β may have characterized tracks in Cluster 1. The shapes of these traces are quite telling of which types of tracks we can expect to see in each cluster.
The code above allows us to create new Spotify playlists based on the cluster groupings of tracks after PCA and k-means. As we initially observed, Cluster 5 is characterized by tracks having high levels of βspeechinessβ. In other words, we can expect to find Rap and R&B tracks in this grouping.
As we can observe above, Burna Boy, blackbear, 6LACK, Playboi Carti, Lil Uzi Vert, Kota the Friend, A Boogie Wit da Hoodie, and Polo G are some of the artists included in this subset, which validates the conclusion suggested by the data.
Cluster 2 contains more instrumental music, as suggested by the radar chart. There are some tracks by the xx, Lauv, Henry Green, and other lesser known artists. Many of the tracks in this cluster have a very synth-y feel and not too many words.
Finally, there is one last thing we can do to analyze the findings. We can make some bar charts, plotting a particular feature for each track in a given cluster in order to see if this feature is, indeed, characteristically high with respect to the average feature value in the entire dataset.
Looking at a few select clusters (2, 5, and 6) and features of interest (acousticness, speechiness, and instrumentalness), a trend is observable in the subplots along the diagonal. In the top left subplot, the tracks in Cluster 2 have mostly above average scores for acousticness; in the middle subplot, the tracks in Cluster 5 all have above average speechiness scores; in the bottom right subplot, Cluster 6 is characterized by extremely high instrumentalness scores, relative to the average for the full dataset.
This was a fun and interesting ML project which served a practical purpose for me and potentially others. Hopefully people can use this audio-based clustering methodology and save themselves a few clicks of the βskipβ button next time they wish to listen to music of a particular mood or vibe. I believe it can be especially useful for people who curate monthly or yearly playlists which lack a cohesive theme. Additionally, it can be useful for large collaborative playlists which, at times, can feel a bit all over the place.
Thank you very much for reading! All of the source code is accessible here. If you would like to send me any feedback or inspiration, please contact me at sejaldua@gmail.com or through my website. I love connecting with people of similar interests! Also, stay tuned for a potential extension of this work! In the meantime, I will be busy thinking of better names for my new playlists because βcluster1β doesnβt have a great ring to it.
|
[
{
"code": null,
"e": 726,
"s": 172,
"text": "A year ago, life was much simpler. It was a bustling Tuesday morning in early October, and I was riding the metro to my Artificial Neural Network class in downtown Copenhagen. I was browsing my Spotify library for a playlist to shuffle for the duration of my commute when I bumped into my friend Liddy. I asked for her input, and she told me something which actually kind of changed my life. She said, βOh Sejal, I am far too indecisive to pick a playlist based on my mood. I actually create a new playlist and add to it on the first day of each month.β"
},
{
"code": null,
"e": 955,
"s": 726,
"text": "With the increased diversity in music that we have seen on streaming platforms such as Spotify, Apple Music, and Soundcloud in the past decade, the lines separating genres have become even more blurred than they were previously."
},
{
"code": null,
"e": 1213,
"s": 955,
"text": "Genre labels are broad umbrella terms that are used to describe music that vary greatly in their characteristics. If someone asks you what kind of music you like, responding with βRockβ or βIndieβ does not really say much without namedropping a few artists."
},
{
"code": null,
"e": 1371,
"s": 1213,
"text": "Genres are always evolving over time. If someone says they are a fan of pop music, how do you know if they are referring to Michael Jackson or Justin Bieber?"
},
{
"code": null,
"e": 1466,
"s": 1371,
"text": "They are often socially driven with little to do with the actual characteristics of the music."
},
{
"code": null,
"e": 1686,
"s": 1466,
"text": "Fortunately, there has been a movement towards labeling music solely based on musical characteristics or attributes. However, organizing music based on these audio features is still a complicated task, even for a human."
},
{
"code": null,
"e": 1946,
"s": 1686,
"text": "Ever since Liddy inspired me with the idea to organize my music by time period, I have been hooked. It helps me to embrace the chaos of my diverse and far-ranging music taste while still being able to compartmentalize my music based on certain phases of life."
},
{
"code": null,
"e": 2307,
"s": 1946,
"text": "The issue, though, is that when I clicking βShuffleβ on my 2020 playlist of 449 songs, I end up skipping 9/10 songs because I can never seem to find a song that fits the mood. So I set out to find a solution to my problem using a machine learning technique called k-means clustering and Principal Component Analysis (PCA), a dimensionality reduction technique."
},
{
"code": null,
"e": 2430,
"s": 2307,
"text": "The Spotify Developer API allows you to get audio features for a track. These features are described in more detail below:"
},
{
"code": null,
"e": 2503,
"s": 2430,
"text": "acousticness: [0β1] Confidence measure of whether the track is acoustic."
},
{
"code": null,
"e": 2672,
"s": 2503,
"text": "danceability: [0β1] Describes how suitable a track is for dancing based on musical attributes including tempo, rhythm, stability, beat strength, and overall regularity."
},
{
"code": null,
"e": 2835,
"s": 2672,
"text": "energy: [0β1] Perceptual measure of intensity and activity. Energetic tracks feel fast, loud, and noisy (e.g. death metal: high energy, Bach prelude: low energy)."
},
{
"code": null,
"e": 3001,
"s": 2835,
"text": "instrumentalness: [0β1] Predicts whether a track contains no vocals (values above 0.5 represent instrumental tracks whereas rap songs would have a score close to 0)."
},
{
"code": null,
"e": 3071,
"s": 3001,
"text": "liveness: [0β1] Detects the presence of an audience in the recording."
},
{
"code": null,
"e": 3135,
"s": 3071,
"text": "loudness: [-60β0 dB] The average volume across an entire track."
},
{
"code": null,
"e": 3437,
"s": 3135,
"text": "speechiness: [0β1] Detects the presence of spoken words in a track (values above 0.66 describe tracks that are probably made entirely of spoken words, 0.33β0.66 describe tracks that may contain both music and speech, and values below 0.33 most likely represent music and other non-speech-like tracks)."
},
{
"code": null,
"e": 3667,
"s": 3437,
"text": "valence: [0β1] Describes the musical positiveness conveyed by a track. Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), while tracks with low valence sound more negative (e.g. sad, depressed, angry)."
},
{
"code": null,
"e": 3775,
"s": 3667,
"text": "tempo: [0β300 BPM] The speed or pace of a given piece, as derived from the estimated average beat duration."
},
{
"code": null,
"e": 3901,
"s": 3775,
"text": "I use Spotipy, which is a Python wrapper for Spotifyβs Developer API. First, we must create a token with our API credentials."
},
{
"code": null,
"e": 4040,
"s": 3901,
"text": "I then extracted metadata (name, artist name, and URI) for each track in the playlist and acquired the audio feature data described above."
},
{
"code": null,
"e": 4801,
"s": 4040,
"text": "Next, we can form our training data by excluding columns in the DataFrame that are not audio features. We also have to do one more critical step: standardization. Standardization is the process of putting different features on the same scale, with each scaled feature having a mean of 0 and a standard deviation of 1. This is important because the model is not familiar with the context of the data. If we do not standardize our X_train data, the model would place a much larger weight on tempo and loudness, since those variables vary by much more than the variables that are distributed in the range from 0 to 1. Standardization allows for all features to be treated equally by the model. We can accomplish this step by using sklearnβs StandardScaler import."
},
{
"code": null,
"e": 4909,
"s": 4801,
"text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()X_std = scaler.fit_transform(df_X)"
},
{
"code": null,
"e": 5511,
"s": 4909,
"text": "What is dimensionality reduction? Well, as we can see from the image above, it is a process that involves using linear algebraic operations to transform n-dimensional data to (n-k)-dimensional data. In this example, we are just reducing 3-dimensional data into 2-dimensional data, so n equals 3 and k equals 1. As you might imagine, some information is lost in this transformation, but we still get a fairly decent approximation with the tremendous benefit of being able to visualize the data. Moreover, we can also effectively reduce the complexity of the problem by reducing the number of variables."
},
{
"code": null,
"e": 5863,
"s": 5511,
"text": "Principal Component Analysis (PCA) is a dimensionality reduction approach which attempts to find the best possible subspace that explains most of the variance in the data. It works by deriving components from the original scaled features. From these components, the two most significant ones are typically plotted, depicting the simplified data space."
},
{
"code": null,
"e": 5997,
"s": 5863,
"text": "After fitting a PCA object to the standardized matrix, we can see how much of the variance is explained by each of the nine features."
},
{
"code": null,
"e": 6105,
"s": 5997,
"text": "from sklearn.decomposition import PCApca = PCA()pca.fit(X_std)evr = pca.explained_variance_ratio_print(evr)"
},
{
"code": null,
"e": 6291,
"s": 6105,
"text": "To inform our decision of how many features to use for our k-means clustering algorithm, it is helpful to make a cumulative variance plot using the evr.cumsum() function and matplotlib."
},
{
"code": null,
"e": 6773,
"s": 6291,
"text": "From this plot, we can observe that each of the principal components explain a pretty considerable amount of variance. However, we do not need to keep all of these components. In general, it is a good rule of thumb to preserve around 80% of the variance. Therefore, in this instance, we can select the 6 most important principal components to incorporate in the k-means algorithm. This can be accomplished by instantiating a new PCA object with the n_components parameter set to 6."
},
{
"code": null,
"e": 7240,
"s": 6773,
"text": "Having finished our PCA, we now have components which explain most of the variance in the data. From this point on, it is going to be very difficult to interpret meaning when analyzing the numeric differences in tracks because the vectorized audio features have been transformed into a new subspace. However, after implementing k-means Clustering, we will be able to inspect the raw data, and we can even visualize our clusters of similar songs on the same 2D-plane."
},
{
"code": null,
"e": 7818,
"s": 7240,
"text": "In order to implement k-means clustering, we must select a number of clusters, k, which distinctly splits the data. Given that we do not have a desired amount of groupings for the huge playlist that we would like to split, and we want this code to be reproducible, we must use an algorithmic approach to determine the optimal value for k. There are actually numerous algorithmic approaches, including but not limited to the elbow method, the silhouette method, and the gap statistic. Letβs take a closer look into the elbow method, which is arguably the most popular technique."
},
{
"code": null,
"e": 8174,
"s": 7818,
"text": "The basic principle of k-means clustering is to define clusters such that the total intra-cluster variation is minimized. The within-cluster sum of squares (WCSS) is a metric which can quantify this partitioning effect. It essentially measures the compactness of the clustering. The optimal number of clusters can be found by executing a simple procedure:"
},
{
"code": null,
"e": 8793,
"s": 8174,
"text": "Implement clustering algorithm for varying values of k, ranging from 1 to 20 clusters.For each k, compute the within-cluster sum of squares (WCSS) by storing the inertia value in a list after the model has been fitted.Plot the WCSS curve according to the number of clusters k.Look for a kink or elbow in the WCSS graph. Usually, the part of the graph before the elbow would be steeply declining, while the part after it β much smoother. [NOTE: there are ways to locate the elbow (a.k.a. βkneeβ) point programmatically, including an open source Python library called kneed or a visualization library called Yellowbrick]"
},
{
"code": null,
"e": 8880,
"s": 8793,
"text": "Implement clustering algorithm for varying values of k, ranging from 1 to 20 clusters."
},
{
"code": null,
"e": 9013,
"s": 8880,
"text": "For each k, compute the within-cluster sum of squares (WCSS) by storing the inertia value in a list after the model has been fitted."
},
{
"code": null,
"e": 9072,
"s": 9013,
"text": "Plot the WCSS curve according to the number of clusters k."
},
{
"code": null,
"e": 9415,
"s": 9072,
"text": "Look for a kink or elbow in the WCSS graph. Usually, the part of the graph before the elbow would be steeply declining, while the part after it β much smoother. [NOTE: there are ways to locate the elbow (a.k.a. βkneeβ) point programmatically, including an open source Python library called kneed or a visualization library called Yellowbrick]"
},
{
"code": null,
"e": 9670,
"s": 9415,
"text": "Running the code snippet above yields the following WCSS curve shown below. The KneeLocator method has determined that 7 is the ideal number of clusters or distinct groupings to be used in order to separate the 449 tracks in my absurdly lengthy playlist."
},
{
"code": null,
"e": 9850,
"s": 9670,
"text": "Now, all that is left to do is to implement k-means clustering once and for all. With the help of sklearn, we can obtain the cluster labels for each track in just 3 lines of code."
},
{
"code": null,
"e": 9988,
"s": 9850,
"text": "kmeans_pca = KMeans(n_clusters=n_clusters, init='k-means++', random_state=42)kmeans_pca.fit(scores_pca)df['Cluster'] = kmeans_pca.labels_"
},
{
"code": null,
"e": 10219,
"s": 9988,
"text": "The cluster labels in the rightmost column of the DataFrame screenshot above are the βresultsβ of this ML technique. Okay... this was a bit anticlimactic. What good do these cluster labels do? Well, letβs investigate them further."
},
{
"code": null,
"e": 11006,
"s": 10219,
"text": "While k-means clustering is not a supervised machine learning techniqueβmeaning we cannot verify whether the results are accurate or notβwe can visualize the clusters on a 2D plane to ensure that there is some sensical separation of data based on the sources of signals that are encapsulated by the components. In the figure above, it is clear that Cluster 5 is most similar to Clusters 1 and 3 and that Cluster 4 is quite loosely defined, overlapping with a few other clusters. Despite some noise, there are clear groupings of tracks, as indicated by the concentrated areas of green, red, orange, and blue data points. Additionally, this is only a 2D visualization of a 6-dimensional vector space, so more analysis is needed in order to determine the efficacy of the k-means algorithm."
},
{
"code": null,
"e": 11312,
"s": 11006,
"text": "Since meaning cannot be inferred from the transformed components, letβs take a look at the raw values for the audio features of the tracks after they have been clustered. A radar chart can be really powerful in this type of analysis because it allows us to make some quick observations about each cluster."
},
{
"code": null,
"e": 11712,
"s": 11312,
"text": "In the figure below, the a radar trace has been plotted for the average audio feature values in each cluster, after normalizing the entire dataframe. Acousticness is a Spotify-defined variable between 0 and 1 while tempo can be in the 100s. Normalization is important because it effectively scales all variables to have values between 0 and 1, making the following visualization far more meaningful."
},
{
"code": null,
"e": 12307,
"s": 11712,
"text": "After a quick glance, it is evident that Cluster 2 is most acoustic-sounding, Cluster 4 consists of live-sounding tracks, Cluster 5 contains the most verbose tracks, and Cluster 6 is characterized by more instrumental tracks. Features like energy, danceability, valence, tempo, and loudness did not contain strong enough sources of signal on which to split the data. That being said, some combination of high danceability, tempo, and energy β may have characterized tracks in Cluster 1. The shapes of these traces are quite telling of which types of tracks we can expect to see in each cluster."
},
{
"code": null,
"e": 12603,
"s": 12307,
"text": "The code above allows us to create new Spotify playlists based on the cluster groupings of tracks after PCA and k-means. As we initially observed, Cluster 5 is characterized by tracks having high levels of βspeechinessβ. In other words, we can expect to find Rap and R&B tracks in this grouping."
},
{
"code": null,
"e": 12841,
"s": 12603,
"text": "As we can observe above, Burna Boy, blackbear, 6LACK, Playboi Carti, Lil Uzi Vert, Kota the Friend, A Boogie Wit da Hoodie, and Polo G are some of the artists included in this subset, which validates the conclusion suggested by the data."
},
{
"code": null,
"e": 13086,
"s": 12841,
"text": "Cluster 2 contains more instrumental music, as suggested by the radar chart. There are some tracks by the xx, Lauv, Henry Green, and other lesser known artists. Many of the tracks in this cluster have a very synth-y feel and not too many words."
},
{
"code": null,
"e": 13380,
"s": 13086,
"text": "Finally, there is one last thing we can do to analyze the findings. We can make some bar charts, plotting a particular feature for each track in a given cluster in order to see if this feature is, indeed, characteristically high with respect to the average feature value in the entire dataset."
},
{
"code": null,
"e": 13896,
"s": 13380,
"text": "Looking at a few select clusters (2, 5, and 6) and features of interest (acousticness, speechiness, and instrumentalness), a trend is observable in the subplots along the diagonal. In the top left subplot, the tracks in Cluster 2 have mostly above average scores for acousticness; in the middle subplot, the tracks in Cluster 5 all have above average speechiness scores; in the bottom right subplot, Cluster 6 is characterized by extremely high instrumentalness scores, relative to the average for the full dataset."
},
{
"code": null,
"e": 14424,
"s": 13896,
"text": "This was a fun and interesting ML project which served a practical purpose for me and potentially others. Hopefully people can use this audio-based clustering methodology and save themselves a few clicks of the βskipβ button next time they wish to listen to music of a particular mood or vibe. I believe it can be especially useful for people who curate monthly or yearly playlists which lack a cohesive theme. Additionally, it can be useful for large collaborative playlists which, at times, can feel a bit all over the place."
}
] |
Unexpected Size of Python Objects in Memory | by Naser Tamimi | Jan, 2021 | Towards Data Science | Towards Data Science
|
I was working on a large dictionary in Python for a data science project. The Resouce Monitor (a windows utility that displays information about the use of hardware) showed an enormous amount of memory usage in a short amount of time. I knew that my draft code was not optimal, but the rate of memory utilization was not making sense with the growth rate of my dictionary length. It seemed that my dictionary length did not have a linear relationship with the dictionary object's size in memory. I decided to check the size of my dictionary in memory. I was sure that there should be a Python function that gives me the answer, right? Of course, I used Google to find that magic function. After an hour of research, I joined the group of Python programmers who realized that there is no straightforward solution to this question. Why? Read this article.
If you are not familiar with how Python manages memory, I would recommend reading the following article of mine first. In a laymanβs language, it explains how Python allocates memory to objects.
towardsdatascience.com
As I explained in the article, Python objects get stored in the Heap Memory (i.e., a dynamic memory). You can get the address of an object on the Heap memory (aka the Heap) by using a function called id(). You can read more details in the above article.
But in that article, we did not discuss anything about the size of objects on the Heap. What is the size of an object in memory? Here, I give you three answers to this question. One is simple but wrong, the next one is a little bit more complex and more accurate, and the last solution is as correct as we can get.
Why should I give you a simple but wrong answer? The reason is that if you see the correct answer first, you might not understand why the answer is a little bit complicated. Also, you might not have a good understanding of the reasons behind that. After all, we are reading articles to understand the reasons behind codes and solutions; otherwise, StackOverflow is full of correct and verified solutions for almost everything.
In Python, the most basic function for measuring the size of an object in memory is sys.getsizeof(). Letβs take a look at this function using a few examples.
>>> sys.getsizeof(1)28>>> sys.getsizeof('Python')55>>> sys.getsizeof([1, 2, 3])88
These three examples show the size of an integer, a string, and a list in bytes. At first glance, everything seems good, and you wonder why this article should be written, right? Give me a few minutes, and I might convince you (as I got convinced after reading the other examples for the first time). Letβs see another example.
>>> sys.getsizeof('')49>>> sys.getsizeof('P')50>>> sys.getsizeof('Py')51>>> sys.getsizeof('Pyt')52
First, I have an empty string. It took 49 bytes! Then I have a string with only one character, and its size is 50 bytes. I added more characters, and it seems that each character adds one byte to the size of my string object. How do we explain this observation? Actually, it is easy. In Python, like almost everything else, a string is an object, not only a collection of characters. An object (in this case, a string object), in addition to its value (i.e., collection of characters), has different attributes and related components. When we create an object, Python stores all this information in memory. Therefore, we have an overhead even for an empty string.
Letβs check the same thing for a list.
>>> sys.getsizeof([])64>>> sys.getsizeof([1])72>>> sys.getsizeof([1, 2])80
We see the same story here. A list object has 64 bytes of overhead. For each additional item, its size grows by 8 bytes. Okay, it was strange first, but it makes sense now. Letβs see another example (I promise you, this one is more interesting).
>>> sys.getsizeof([1, 2])80>>> sys.getsizeof([3, 4, 5, 1])96>>> sys.getsizeof([1, 2, [3, 4, 5, 1]])88
First, I have a list of [1, 2] which takes 80 bytes of memory. I have another list of [3, 4, 5, 1] which took 96 bytes. So far, everything makes sense. For a list object, we have 64 bytes of overhead and 8 bytes for each additional item. Now, I nest the second list inside the first list. The resulting list will be something like [1, 2, [3, 4, 5, 1]] . When I get the size of this new list object, its size is 88 bytes. What?!! The size of the new nested list (i.e., 88 bytes) is even less than the size of my second list (i.e., 96 bytes). How is it possible?
Letβs playback. First, I had a list of two items (i.e., integer numbers). It took 80 bytes of memory as we expected. When we added a new item, which was a list, it added 8 bytes to my list. It seems that, no matter what, an additional item takes 8 bytes. It seems that a list object is not storing the items but a reference to items (i.e., the memory addresses). THATβS TRUE. When you create a list object, the list object by itself takes 64 bytes of memory, and each item adds 8 bytes of memory to the size of the list because of references to other objects. It means that in the previous example, the list of [1, 2, [3, 4, 5, 1]] is stored on the memory like [reference to obj1, reference to obj2, reference to obj3]. The size of each reference is 8 bytes. In this case, obj1, obj2, and obj3 are stored somewhere else in the memory. Therefore, to get the actual size of our list object, in addition to getting the size of the list, we need to include the size of each member object (which we call them items).
As we learned from the previous section, sys.getsizeof() only gives us the size of the object and its attributes on memory. It does not include the size of referenced objects (e.g., items in a list) and their attributes. To get the actual size of an object, we must iterate through all components of an object (e.g., items in a list object) and add their sizes together. The following figure is an example.
As the above figure shows, the size of an object such as [1, 2, [3, 4, 5, 1]] is 352 bytes. However, there is a mistake in this calculation. If you look at the list of objects in the figure, you see the same memory addresses on rows 2 and 8 (highlighted with *). It seems that 1 (i.e., an integer object) in the main list and 1 in the nested list are stored in the same memory address. As I explained in a previous article (link), Python stores integer numbers between [-5, 256] once and points all references to the same memory address (for memory optimization). Therefore, it is better to identify duplicates using their memory addresses (via id()) and count their memory size once. Therefore for our example, we must remove duplicates before summing their memory sizes. The following figure shows the correct answer, which is 324 bytes.
The previous solution was more accurate than what we calculated initially, but unfortunately, it still has some caveats. When you load a class, some other elements, that you cannot think of them (e.g., obj.__dict__ or obj.__slots__), might also get stored in the memory. Tracking these elements manually is hard and sometimes impossible. A better way of searching for all the elements attached to your object is to use a function from the Python Garbage Collector interface called gc.get_referents().
If you are not familiar with Python Garbage Collector, I recommend you to read this article. Garbage Collector keeps track of all objects and associated elements in the Heap and removes them when the program does not need them anymore.
Here we can take advantage of the Garbage Collector interface (link) to find all elements linked to the object that we want to know its size on the memory. The following code iterates through all objects and elements attached to the original object and adds their size to the total size of the object.
I also found a good solution provided by the following article. Although the solution works for a limited set of objects, the solution looks solid.
goshippo.com
Measuring the size of Python objects in memory is not an easy task. There is not a built-in and straightforward solution for finding the actual size of the objects. In this article, we learned why it isn't easy to measure the objects' actual size. Also, I provided a solution that works for many (not all) objects in Python.
Follow me on Twitter for the latest stories: https://twitter.com/TamimiNas
|
[
{
"code": null,
"e": 1025,
"s": 171,
"text": "I was working on a large dictionary in Python for a data science project. The Resouce Monitor (a windows utility that displays information about the use of hardware) showed an enormous amount of memory usage in a short amount of time. I knew that my draft code was not optimal, but the rate of memory utilization was not making sense with the growth rate of my dictionary length. It seemed that my dictionary length did not have a linear relationship with the dictionary object's size in memory. I decided to check the size of my dictionary in memory. I was sure that there should be a Python function that gives me the answer, right? Of course, I used Google to find that magic function. After an hour of research, I joined the group of Python programmers who realized that there is no straightforward solution to this question. Why? Read this article."
},
{
"code": null,
"e": 1220,
"s": 1025,
"text": "If you are not familiar with how Python manages memory, I would recommend reading the following article of mine first. In a laymanβs language, it explains how Python allocates memory to objects."
},
{
"code": null,
"e": 1243,
"s": 1220,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1497,
"s": 1243,
"text": "As I explained in the article, Python objects get stored in the Heap Memory (i.e., a dynamic memory). You can get the address of an object on the Heap memory (aka the Heap) by using a function called id(). You can read more details in the above article."
},
{
"code": null,
"e": 1812,
"s": 1497,
"text": "But in that article, we did not discuss anything about the size of objects on the Heap. What is the size of an object in memory? Here, I give you three answers to this question. One is simple but wrong, the next one is a little bit more complex and more accurate, and the last solution is as correct as we can get."
},
{
"code": null,
"e": 2239,
"s": 1812,
"text": "Why should I give you a simple but wrong answer? The reason is that if you see the correct answer first, you might not understand why the answer is a little bit complicated. Also, you might not have a good understanding of the reasons behind that. After all, we are reading articles to understand the reasons behind codes and solutions; otherwise, StackOverflow is full of correct and verified solutions for almost everything."
},
{
"code": null,
"e": 2397,
"s": 2239,
"text": "In Python, the most basic function for measuring the size of an object in memory is sys.getsizeof(). Letβs take a look at this function using a few examples."
},
{
"code": null,
"e": 2479,
"s": 2397,
"text": ">>> sys.getsizeof(1)28>>> sys.getsizeof('Python')55>>> sys.getsizeof([1, 2, 3])88"
},
{
"code": null,
"e": 2807,
"s": 2479,
"text": "These three examples show the size of an integer, a string, and a list in bytes. At first glance, everything seems good, and you wonder why this article should be written, right? Give me a few minutes, and I might convince you (as I got convinced after reading the other examples for the first time). Letβs see another example."
},
{
"code": null,
"e": 2906,
"s": 2807,
"text": ">>> sys.getsizeof('')49>>> sys.getsizeof('P')50>>> sys.getsizeof('Py')51>>> sys.getsizeof('Pyt')52"
},
{
"code": null,
"e": 3570,
"s": 2906,
"text": "First, I have an empty string. It took 49 bytes! Then I have a string with only one character, and its size is 50 bytes. I added more characters, and it seems that each character adds one byte to the size of my string object. How do we explain this observation? Actually, it is easy. In Python, like almost everything else, a string is an object, not only a collection of characters. An object (in this case, a string object), in addition to its value (i.e., collection of characters), has different attributes and related components. When we create an object, Python stores all this information in memory. Therefore, we have an overhead even for an empty string."
},
{
"code": null,
"e": 3609,
"s": 3570,
"text": "Letβs check the same thing for a list."
},
{
"code": null,
"e": 3684,
"s": 3609,
"text": ">>> sys.getsizeof([])64>>> sys.getsizeof([1])72>>> sys.getsizeof([1, 2])80"
},
{
"code": null,
"e": 3930,
"s": 3684,
"text": "We see the same story here. A list object has 64 bytes of overhead. For each additional item, its size grows by 8 bytes. Okay, it was strange first, but it makes sense now. Letβs see another example (I promise you, this one is more interesting)."
},
{
"code": null,
"e": 4032,
"s": 3930,
"text": ">>> sys.getsizeof([1, 2])80>>> sys.getsizeof([3, 4, 5, 1])96>>> sys.getsizeof([1, 2, [3, 4, 5, 1]])88"
},
{
"code": null,
"e": 4593,
"s": 4032,
"text": "First, I have a list of [1, 2] which takes 80 bytes of memory. I have another list of [3, 4, 5, 1] which took 96 bytes. So far, everything makes sense. For a list object, we have 64 bytes of overhead and 8 bytes for each additional item. Now, I nest the second list inside the first list. The resulting list will be something like [1, 2, [3, 4, 5, 1]] . When I get the size of this new list object, its size is 88 bytes. What?!! The size of the new nested list (i.e., 88 bytes) is even less than the size of my second list (i.e., 96 bytes). How is it possible?"
},
{
"code": null,
"e": 5605,
"s": 4593,
"text": "Letβs playback. First, I had a list of two items (i.e., integer numbers). It took 80 bytes of memory as we expected. When we added a new item, which was a list, it added 8 bytes to my list. It seems that, no matter what, an additional item takes 8 bytes. It seems that a list object is not storing the items but a reference to items (i.e., the memory addresses). THATβS TRUE. When you create a list object, the list object by itself takes 64 bytes of memory, and each item adds 8 bytes of memory to the size of the list because of references to other objects. It means that in the previous example, the list of [1, 2, [3, 4, 5, 1]] is stored on the memory like [reference to obj1, reference to obj2, reference to obj3]. The size of each reference is 8 bytes. In this case, obj1, obj2, and obj3 are stored somewhere else in the memory. Therefore, to get the actual size of our list object, in addition to getting the size of the list, we need to include the size of each member object (which we call them items)."
},
{
"code": null,
"e": 6012,
"s": 5605,
"text": "As we learned from the previous section, sys.getsizeof() only gives us the size of the object and its attributes on memory. It does not include the size of referenced objects (e.g., items in a list) and their attributes. To get the actual size of an object, we must iterate through all components of an object (e.g., items in a list object) and add their sizes together. The following figure is an example."
},
{
"code": null,
"e": 6852,
"s": 6012,
"text": "As the above figure shows, the size of an object such as [1, 2, [3, 4, 5, 1]] is 352 bytes. However, there is a mistake in this calculation. If you look at the list of objects in the figure, you see the same memory addresses on rows 2 and 8 (highlighted with *). It seems that 1 (i.e., an integer object) in the main list and 1 in the nested list are stored in the same memory address. As I explained in a previous article (link), Python stores integer numbers between [-5, 256] once and points all references to the same memory address (for memory optimization). Therefore, it is better to identify duplicates using their memory addresses (via id()) and count their memory size once. Therefore for our example, we must remove duplicates before summing their memory sizes. The following figure shows the correct answer, which is 324 bytes."
},
{
"code": null,
"e": 7353,
"s": 6852,
"text": "The previous solution was more accurate than what we calculated initially, but unfortunately, it still has some caveats. When you load a class, some other elements, that you cannot think of them (e.g., obj.__dict__ or obj.__slots__), might also get stored in the memory. Tracking these elements manually is hard and sometimes impossible. A better way of searching for all the elements attached to your object is to use a function from the Python Garbage Collector interface called gc.get_referents()."
},
{
"code": null,
"e": 7589,
"s": 7353,
"text": "If you are not familiar with Python Garbage Collector, I recommend you to read this article. Garbage Collector keeps track of all objects and associated elements in the Heap and removes them when the program does not need them anymore."
},
{
"code": null,
"e": 7891,
"s": 7589,
"text": "Here we can take advantage of the Garbage Collector interface (link) to find all elements linked to the object that we want to know its size on the memory. The following code iterates through all objects and elements attached to the original object and adds their size to the total size of the object."
},
{
"code": null,
"e": 8039,
"s": 7891,
"text": "I also found a good solution provided by the following article. Although the solution works for a limited set of objects, the solution looks solid."
},
{
"code": null,
"e": 8052,
"s": 8039,
"text": "goshippo.com"
},
{
"code": null,
"e": 8377,
"s": 8052,
"text": "Measuring the size of Python objects in memory is not an easy task. There is not a built-in and straightforward solution for finding the actual size of the objects. In this article, we learned why it isn't easy to measure the objects' actual size. Also, I provided a solution that works for many (not all) objects in Python."
}
] |
Lookup and Reference - HLOOKUP Function
|
The HLOOKUP function searches for a value in the top row of a table or an array of values, and then returns a value in the same column from a row you specify in the table or array.
You can use HLOOKUP when your comparison values are located in a row across the top of a table of data, and you want to look down a specified number of rows.
The H in HLOOKUP stands for "Horizontal". You can use VLOOKUP when your comparison values are located in a column to the left of the data you want to find.
HLOOKUP (lookup_value, table_array, row_index_num, [range_lookup])
The value to be found in the first row of the table.
Lookup_value can be a value, a reference, or a text string.
A table of information in which data is looked up.
Use a reference to a range or a range name.
The values in the first row of table_array can be text, numbers, or logical values.
See Notes Below.
The row number in table_array from which the matching value will be returned.
A row_index_num of 1 returns the first row value in table_array, a row_index_num of 2 returns the second row value in table_array, and so on.
1 β€ row_index_num β€ the number of rows in the table_array.
HLOOKUP returns the #VALUE! error value; if row_index_num is greater than,
A logical value that specifies whether you want HLOOKUP to find an exact match or an approximate match.
If TRUE or if omitted, an approximate match is returned. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned.
If FALSE, HLOOKUP will find an exact match. If one is not found, the error value #N/A is returned.
table_array
If range_lookup is TRUE, the values in the first row of table_array must be placed in ascending order: ...-2, -1, 0, 1, 2..., A-Z, FALSE, TRUE. Otherwise, HLOOKUP may not give the correct value
Uppercase and lowercase text are equivalent
Sort the values in ascending order, left to right
If range_lookup is FALSE, table_array does not need to be sorted
table_array
If range_lookup is TRUE, the values in the first row of table_array must be placed in ascending order: ...-2, -1, 0, 1, 2..., A-Z, FALSE, TRUE. Otherwise, HLOOKUP may not give the correct value
If range_lookup is TRUE, the values in the first row of table_array must be placed in ascending order: ...-2, -1, 0, 1, 2..., A-Z, FALSE, TRUE. Otherwise, HLOOKUP may not give the correct value
Uppercase and lowercase text are equivalent
Uppercase and lowercase text are equivalent
Sort the values in ascending order, left to right
Sort the values in ascending order, left to right
If range_lookup is FALSE, table_array does not need to be sorted
If range_lookup is FALSE, table_array does not need to be sorted
If row_index_num is less than 1, HLOOKUP function returns the #VALUE! error value.
If row_index_num is less than 1, HLOOKUP function returns the #VALUE! error value.
If row_index_num is not recognized as a numeric value, HLOOKUP function returns the #VALUE! error value.
If row_index_num is not recognized as a numeric value, HLOOKUP function returns the #VALUE! error value.
If row_index_num is greater than the number of rows in the table_array, HLOOKUP function returns the #REF! error value.
If row_index_num is greater than the number of rows in the table_array, HLOOKUP function returns the #REF! error value.
If HLOOKUP function cannot find lookup_value, and range_lookup is TRUE, it uses the largest value that is less than lookup_value.
If HLOOKUP function cannot find lookup_value, and range_lookup is TRUE, it uses the largest value that is less than lookup_value.
If lookup_value is smaller than the smallest value in the first row of table_array, HLOOKUP function returns the #N/A error value.
If lookup_value is smaller than the smallest value in the first row of table_array, HLOOKUP function returns the #N/A error value.
If range_lookup is FALSE and lookup_value is text, you can use the wildcard characters, question mark (?) and asterisk (*), in lookup_value. A question mark matches any single character; an asterisk matches any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) before the character.
If range_lookup is FALSE and lookup_value is text, you can use the wildcard characters, question mark (?) and asterisk (*), in lookup_value. A question mark matches any single character; an asterisk matches any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) before the character.
Excel 2007, Excel 2010, Excel 2013, Excel 2016
296 Lectures
146 hours
Arun Motoori
56 Lectures
5.5 hours
Pavan Lalwani
120 Lectures
6.5 hours
Inf Sid
134 Lectures
8.5 hours
Yoda Learning
46 Lectures
7.5 hours
William Fiset
25 Lectures
1.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2035,
"s": 1854,
"text": "The HLOOKUP function searches for a value in the top row of a table or an array of values, and then returns a value in the same column from a row you specify in the table or array."
},
{
"code": null,
"e": 2193,
"s": 2035,
"text": "You can use HLOOKUP when your comparison values are located in a row across the top of a table of data, and you want to look down a specified number of rows."
},
{
"code": null,
"e": 2349,
"s": 2193,
"text": "The H in HLOOKUP stands for \"Horizontal\". You can use VLOOKUP when your comparison values are located in a column to the left of the data you want to find."
},
{
"code": null,
"e": 2418,
"s": 2349,
"text": "HLOOKUP (lookup_value, table_array, row_index_num, [range_lookup]) \n"
},
{
"code": null,
"e": 2471,
"s": 2418,
"text": "The value to be found in the first row of the table."
},
{
"code": null,
"e": 2531,
"s": 2471,
"text": "Lookup_value can be a value, a reference, or a text string."
},
{
"code": null,
"e": 2582,
"s": 2531,
"text": "A table of information in which data is looked up."
},
{
"code": null,
"e": 2626,
"s": 2582,
"text": "Use a reference to a range or a range name."
},
{
"code": null,
"e": 2710,
"s": 2626,
"text": "The values in the first row of table_array can be text, numbers, or logical values."
},
{
"code": null,
"e": 2727,
"s": 2710,
"text": "See Notes Below."
},
{
"code": null,
"e": 2805,
"s": 2727,
"text": "The row number in table_array from which the matching value will be returned."
},
{
"code": null,
"e": 2947,
"s": 2805,
"text": "A row_index_num of 1 returns the first row value in table_array, a row_index_num of 2 returns the second row value in table_array, and so on."
},
{
"code": null,
"e": 3006,
"s": 2947,
"text": "1 β€ row_index_num β€ the number of rows in the table_array."
},
{
"code": null,
"e": 3081,
"s": 3006,
"text": "HLOOKUP returns the #VALUE! error value; if row_index_num is greater than,"
},
{
"code": null,
"e": 3185,
"s": 3081,
"text": "A logical value that specifies whether you want HLOOKUP to find an exact match or an approximate match."
},
{
"code": null,
"e": 3357,
"s": 3185,
"text": "If TRUE or if omitted, an approximate match is returned. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned."
},
{
"code": null,
"e": 3456,
"s": 3357,
"text": "If FALSE, HLOOKUP will find an exact match. If one is not found, the error value #N/A is returned."
},
{
"code": null,
"e": 3824,
"s": 3456,
"text": "table_array\n\nIf range_lookup is TRUE, the values in the first row of table_array must be placed in ascending order: ...-2, -1, 0, 1, 2..., A-Z, FALSE, TRUE. Otherwise, HLOOKUP may not give the correct value\nUppercase and lowercase text are equivalent\nSort the values in ascending order, left to right\nIf range_lookup is FALSE, table_array does not need to be sorted\n\n"
},
{
"code": null,
"e": 3836,
"s": 3824,
"text": "table_array"
},
{
"code": null,
"e": 4030,
"s": 3836,
"text": "If range_lookup is TRUE, the values in the first row of table_array must be placed in ascending order: ...-2, -1, 0, 1, 2..., A-Z, FALSE, TRUE. Otherwise, HLOOKUP may not give the correct value"
},
{
"code": null,
"e": 4224,
"s": 4030,
"text": "If range_lookup is TRUE, the values in the first row of table_array must be placed in ascending order: ...-2, -1, 0, 1, 2..., A-Z, FALSE, TRUE. Otherwise, HLOOKUP may not give the correct value"
},
{
"code": null,
"e": 4268,
"s": 4224,
"text": "Uppercase and lowercase text are equivalent"
},
{
"code": null,
"e": 4312,
"s": 4268,
"text": "Uppercase and lowercase text are equivalent"
},
{
"code": null,
"e": 4362,
"s": 4312,
"text": "Sort the values in ascending order, left to right"
},
{
"code": null,
"e": 4412,
"s": 4362,
"text": "Sort the values in ascending order, left to right"
},
{
"code": null,
"e": 4477,
"s": 4412,
"text": "If range_lookup is FALSE, table_array does not need to be sorted"
},
{
"code": null,
"e": 4542,
"s": 4477,
"text": "If range_lookup is FALSE, table_array does not need to be sorted"
},
{
"code": null,
"e": 4625,
"s": 4542,
"text": "If row_index_num is less than 1, HLOOKUP function returns the #VALUE! error value."
},
{
"code": null,
"e": 4708,
"s": 4625,
"text": "If row_index_num is less than 1, HLOOKUP function returns the #VALUE! error value."
},
{
"code": null,
"e": 4813,
"s": 4708,
"text": "If row_index_num is not recognized as a numeric value, HLOOKUP function returns the #VALUE! error value."
},
{
"code": null,
"e": 4918,
"s": 4813,
"text": "If row_index_num is not recognized as a numeric value, HLOOKUP function returns the #VALUE! error value."
},
{
"code": null,
"e": 5038,
"s": 4918,
"text": "If row_index_num is greater than the number of rows in the table_array, HLOOKUP function returns the #REF! error value."
},
{
"code": null,
"e": 5158,
"s": 5038,
"text": "If row_index_num is greater than the number of rows in the table_array, HLOOKUP function returns the #REF! error value."
},
{
"code": null,
"e": 5288,
"s": 5158,
"text": "If HLOOKUP function cannot find lookup_value, and range_lookup is TRUE, it uses the largest value that is less than lookup_value."
},
{
"code": null,
"e": 5418,
"s": 5288,
"text": "If HLOOKUP function cannot find lookup_value, and range_lookup is TRUE, it uses the largest value that is less than lookup_value."
},
{
"code": null,
"e": 5549,
"s": 5418,
"text": "If lookup_value is smaller than the smallest value in the first row of table_array, HLOOKUP function returns the #N/A error value."
},
{
"code": null,
"e": 5680,
"s": 5549,
"text": "If lookup_value is smaller than the smallest value in the first row of table_array, HLOOKUP function returns the #N/A error value."
},
{
"code": null,
"e": 6011,
"s": 5680,
"text": "If range_lookup is FALSE and lookup_value is text, you can use the wildcard characters, question mark (?) and asterisk (*), in lookup_value. A question mark matches any single character; an asterisk matches any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) before the character."
},
{
"code": null,
"e": 6342,
"s": 6011,
"text": "If range_lookup is FALSE and lookup_value is text, you can use the wildcard characters, question mark (?) and asterisk (*), in lookup_value. A question mark matches any single character; an asterisk matches any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) before the character."
},
{
"code": null,
"e": 6389,
"s": 6342,
"text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016"
},
{
"code": null,
"e": 6425,
"s": 6389,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 6439,
"s": 6425,
"text": " Arun Motoori"
},
{
"code": null,
"e": 6474,
"s": 6439,
"text": "\n 56 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6489,
"s": 6474,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 6525,
"s": 6489,
"text": "\n 120 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6534,
"s": 6525,
"text": " Inf Sid"
},
{
"code": null,
"e": 6570,
"s": 6534,
"text": "\n 134 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6585,
"s": 6570,
"text": " Yoda Learning"
},
{
"code": null,
"e": 6620,
"s": 6585,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6635,
"s": 6620,
"text": " William Fiset"
},
{
"code": null,
"e": 6670,
"s": 6635,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6684,
"s": 6670,
"text": " Sasha Miller"
},
{
"code": null,
"e": 6691,
"s": 6684,
"text": " Print"
},
{
"code": null,
"e": 6702,
"s": 6691,
"text": " Add Notes"
}
] |
How to set an Android notification to a specific date in the future?
|
This example demonstrate about How to set an Android notification to a specific date in the future.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :padding = "16dp"
tools :context = ".MainActivity" >
<TextView
android :id = "@+id/tvDate"
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :hint = "Select Date"
android :onClick = "setDate"
android :padding = "16dp" />
</RelativeLayout>
Step 3 β Add the following code to src/MainActivity.
package app.tutorialspoint.com.notifyme ;
import android.app.AlarmManager ;
import android.app.DatePickerDialog ;
import android.app.Notification ;
import android.app.PendingIntent ;
import android.content.Context ;
import android.content.Intent ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.Button ;
import android.widget.DatePicker ;
import java.text.SimpleDateFormat ;
import java.util.Calendar ;
import java.util.Date ;
import java.util.Locale ;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
Button btnDate ;
final Calendar myCalendar = Calendar. getInstance () ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
btnDate = findViewById(R.id. btnDate ) ;
}
private void scheduleNotification (Notification notification , long delay) {
Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ;
notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ;
notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ;
PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ;
AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ;
assert alarmManager != null;
alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , delay , pendingIntent) ;
}
private Notification getNotification (String content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ;
builder.setContentTitle( "Scheduled Notification" ) ;
builder.setContentText(content) ;
builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
builder.setAutoCancel( true ) ;
builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
return builder.build() ;
}
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet (DatePicker view , int year , int monthOfYear , int dayOfMonth) {
myCalendar .set(Calendar. YEAR , year) ;
myCalendar .set(Calendar. MONTH , monthOfYear) ;
myCalendar .set(Calendar. DAY_OF_MONTH , dayOfMonth) ;
updateLabel() ;
}
} ;
public void setDate (View view) {
new DatePickerDialog(
MainActivity. this, date ,
myCalendar .get(Calendar. YEAR ) ,
myCalendar .get(Calendar. MONTH ) ,
myCalendar .get(Calendar. DAY_OF_MONTH )
).show() ;
}
private void updateLabel () {
String myFormat = "dd/MM/yy" ; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat , Locale. getDefault ()) ;
Date date = myCalendar .getTime() ;
btnDate .setText(sdf.format(date)) ;
scheduleNotification(getNotification( btnDate .getText().toString()) , date.getTime()) ;
}
}
Step 4 β Add the following code to src/MyNotificationPublisher.
package app.tutorialspoint.com.notifyme ;
import android.app.Notification ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.content.BroadcastReceiver ;
import android.content.Context ;
import android.content.Intent ;
import static app.tutorialspoint.com.notifyme.MainActivity. NOTIFICATION_CHANNEL_ID ;
public class MyNotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id" ;
public static String NOTIFICATION = "notification" ;
public void onReceive (Context context , Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ;
Notification notification = intent.getParcelableExtra( NOTIFICATION ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel) ;
}
int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ;
assert notificationManager != null;
notificationManager.notify(id , notification) ;
}
}
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.tutorialspoint.com.notifyme" >
<uses-permission android :name = "android.permission.VIBRATE" />
<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>
<receiver android :name= ".MyNotificationPublisher" />
</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 Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "This example demonstrate about How to set an Android notification to a specific date in the future."
},
{
"code": null,
"e": 1291,
"s": 1162,
"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": 1356,
"s": 1291,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1946,
"s": 1356,
"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\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :padding = \"16dp\"\n tools :context = \".MainActivity\" >\n <TextView\n android :id = \"@+id/tvDate\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :hint = \"Select Date\"\n android :onClick = \"setDate\"\n android :padding = \"16dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1999,
"s": 1946,
"text": "Step 3 β Add the following code to src/MainActivity."
},
{
"code": null,
"e": 5285,
"s": 1999,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.AlarmManager ;\nimport android.app.DatePickerDialog ;\nimport android.app.Notification ;\nimport android.app.PendingIntent ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.Button ;\nimport android.widget.DatePicker ;\nimport java.text.SimpleDateFormat ;\nimport java.util.Calendar ;\nimport java.util.Date ;\nimport java.util.Locale ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n Button btnDate ;\n final Calendar myCalendar = Calendar. getInstance () ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n btnDate = findViewById(R.id. btnDate ) ;\n }\n private void scheduleNotification (Notification notification , long delay) {\n Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ;\n notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ;\n notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ;\n PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ;\n AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ;\n assert alarmManager != null;\n alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , delay , pendingIntent) ;\n }\n private Notification getNotification (String content) {\n NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ;\n builder.setContentTitle( \"Scheduled Notification\" ) ;\n builder.setContentText(content) ;\n builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n builder.setAutoCancel( true ) ;\n builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n return builder.build() ;\n }\n DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {\n @Override\n public void onDateSet (DatePicker view , int year , int monthOfYear , int dayOfMonth) {\n myCalendar .set(Calendar. YEAR , year) ;\n myCalendar .set(Calendar. MONTH , monthOfYear) ;\n myCalendar .set(Calendar. DAY_OF_MONTH , dayOfMonth) ;\n updateLabel() ;\n }\n } ;\n public void setDate (View view) {\n new DatePickerDialog(\n MainActivity. this, date ,\n myCalendar .get(Calendar. YEAR ) ,\n myCalendar .get(Calendar. MONTH ) ,\n myCalendar .get(Calendar. DAY_OF_MONTH )\n ).show() ;\n }\n private void updateLabel () {\n String myFormat = \"dd/MM/yy\" ; //In which you need put here\n SimpleDateFormat sdf = new SimpleDateFormat(myFormat , Locale. getDefault ()) ;\n Date date = myCalendar .getTime() ;\n btnDate .setText(sdf.format(date)) ;\n scheduleNotification(getNotification( btnDate .getText().toString()) , date.getTime()) ;\n }\n}"
},
{
"code": null,
"e": 5349,
"s": 5285,
"text": "Step 4 β Add the following code to src/MyNotificationPublisher."
},
{
"code": null,
"e": 6741,
"s": 5349,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.Notification ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.content.BroadcastReceiver ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport static app.tutorialspoint.com.notifyme.MainActivity. NOTIFICATION_CHANNEL_ID ;\npublic class MyNotificationPublisher extends BroadcastReceiver {\n public static String NOTIFICATION_ID = \"notification-id\" ;\n public static String NOTIFICATION = \"notification\" ;\n public void onReceive (Context context , Intent intent) {\n NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ;\n Notification notification = intent.getParcelableExtra( NOTIFICATION ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n assert notificationManager != null;\n notificationManager.createNotificationChannel(notificationChannel) ;\n }\n int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ;\n assert notificationManager != null;\n notificationManager.notify(id , notification) ;\n }\n}"
},
{
"code": null,
"e": 6796,
"s": 6741,
"text": "Step 5 β Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 7656,
"s": 6796,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\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 <receiver android :name= \".MyNotificationPublisher\" />\n </application>\n</manifest>"
},
{
"code": null,
"e": 8003,
"s": 7656,
"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 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": 8045,
"s": 8003,
"text": "Click here to download the project code"
}
] |
How Automated Data Validation using Pandera Made Me More Productive! | by Pratik Gandhi | Towards Data Science
|
Data is called as the new oil of 21st Century. It is very important to juggle with the data to extract and use the correct information to solve our problems. Working with data can be exciting and sometimes tedious for people. As it is rightly said, βData Scientists spend 80% of their time cleaning the dataβ. Being a part of that pack, I go through the same process when encountering a new dataset. The same activity is not limited to until the Machine Learning(ML) system is implemented and deployed to production. When generating predictions in real time, the data might change due to unintuitive and unforseeable circumstances like error due to human interference, wrong data submitted, a new trend in data, problem while recording data, and many more. A simple ML system with multiple steps involved looks like shown in the diagram below:
This needs to be slightly shifted by introducing or labeling another component explicitly, after data preparation and before feature engineering we name as Data Validation:
The article is focused on why data validation is important and how can one use different strategies to seemlessly integrate it in their pipeline. After some work, I learnt how to implement scripts that would do data validation to save some of the time. Above that, I automated them using some of the pre-built packages, stepping up my game!
Almost 85% of projects will not make it to production as per Gartner. Machine Learning (ML) Pipelines usually face several hiccups when pushed in production. One of the major issues I have quite often experienced is the compromise of data quality. Spending multiple hours of a day, several times a month maybe, and figuring out that the data that came through was unacceptable because of some reason can be quite relieving but frustrating at the same time. Many reasons can contribute that leads to data type getting changed like, text getting introduced instead of an integer, an integer was on outlier (probably 10 times higher) or an entire specific column was not received in the data feed, to mention a few. That is why adding this extra step is so important. Validating manually can take some extra effort and time. Making it automated(to an extent) could reduce the burden of the Data Science team. There are some major benefits I see by integrating an automated data validation in the pipeline:
Saves time by a couple of hours
Less frustration among team members
More productive by focusing on other areas
Trying to make your production model more accurate ;)
Python community has already built some outstanding packages to take care of these issues in a very smart way. I am going to share a few of them which I have explored and how I engineered my scripts to make them part of my pipeline.
Data Source: I took a very recent dataset to show how one can implement these packages. Here is the link to get the data.
Pandera provides a very simple and flexible API for performing data validation for data frame or series data. It also helps in performing complex statistical validation like hypothesis testing like two_sample_ttest. More details about the package and usage can be found here.
Take a sample of 10 rows from the dataset:
As we can see, there are multiple columns of different data types: String, Int, Float, Datetime. We need to define the schema of the data we expect. I have defined a simple schema without any strict rules for data validation checks as seen in the code above. Based on the expected data type, we can either use pa.Int for Integer, pa.String for String, pa.Float for float or pa.DateTime if there is a date and time. Here we set nullable = True if we expect NaN values else False. Moreover, if we set coerce = True, it will convert the column into the expected datatype without giving any errors. For e.g. converting float to int, int to string, etc. On validating the data, the output will the data frame itself, as it passes all the checks (try it!!!). If it fails, the output would look something like:
Traceback (most recent call last):...ValueError: cannot convert float NaN to integer
There are some amazing capabilities that I have explored about Pandera which I will try to explain with as much detail as I can.
Sometimes, columns might be optional and not required. In such a case, we can set required = False. By default required = True for all columns
As we see in the screenshot below, it returned data as output without any errors.
Try setting required=True for the same column and run the above code again.
By default, if a new column is added to the data frame and not defined in the schema, no error will be raised. However, if you want to you can set strict = True.
Running the code above we see below that it throws the errors that βextra_columnβ is not defined in the schema.
If you see my code, I have added lazy = True which gives a more detailed view as follows:
Index can also be validated if there is any specific pattern or holds any special importance in the dataset. For example, see below:
I created and set that column as an index to show how we can do Index validation. Outside the parenthesis of the schema, one can specify the index format that is expected. Again the output is the same as before
Here we performed a single index validation. MultiIndex validation can be performed in a similar way. Check out here.
Once we have defined the schema to validate the data, it is possible to transform the schema in the pipeline itself, after new columns have been introduced because of additional computation (which happens 100% of the time). Letβs say initially we only have Id, County, Province_State, Country_Region, Population as the columns. We add new columns Weight, Date, Target, TargetValue to the schema as follows:
On printing the schema as we show above, we get the following:
On the other hand, we can also remove some columns from the schema if needed as below:
One can do a more detailed check on the column using Check object as follows:
Pandera has some pre-built checks that can be directly used like greater_than_or_equal_to, less_than. A custom check can also be passed for e.g. here we have used lambda argument to calculate the length of the string. This is one of the best functionalities in Pandera and can bring a lot more value to the data validation strategy. Find more details here
I create separate scripts that run and gives a report of the validation, once the final data has been received before it goes to the next step. People can integrate them as a part of pre-processing as well.
One can also use them as decorators directly. See how here.
Apart from using directly on a data frame, it can also be applied to a series, a specific column check, or even an element-wise check.
Because of the flexibility regex operations can also be carried out on the data using Pandera.
Importantly, you would not have a perfect data validation schema right in first go. More than likely, you will make data validation schema βperfectβ and ML pipeline more robust by incorporating different validation strategies as you encounter data in real time, over a long course of period.
As the name of the package suggests, you can set expectations for the data to be validated. Honestly, I got so comfortable with Pandera, that I have not got a chance to explore to the full potential. It seems to be quite easy to implement and straight forward package to use. Below is a small snippet of the implementation of the same data:
This is another package whose syntax is similar to Pandera. It can be more applied when data is in a dictionary form or JSON format.
More details about the package can be found here.
This is another great package if your data is obtained via XML, JSON or HTML form post. In other words, it is beneficial to validate any type of strings, mappings, and lists type of data. Below are some of their useful links:
Github: https://github.com/Pylons/colander
Documentation: https://docs.pylonsproject.org/projects/colander/en/latest/
JsonSchema is an implementation of JSON schema for Python. As the name suggests, this package is very helpful for validating JSON data. Take the following example with valid JSON data and invalid JSON data:
On running the invalid data, it will throw an error:
As we can see, the price is expected to be number but string was provided rather. More details about it can be found here.
The post might seem to be mostly dominated by Pandera, as it is one of the packages that I use often. Writing this post was purely to share the voyage I embarked on. I am sure one can benefit more from these packages for their specific use case. Often walking the extra mile can achieve extraordinary results. Data validation is definitely that βextra mileβ. Developing data validation strategies might feel extra work but one can definitely benefit a lot if such a habit of creating automated scripts is formed, even for taking care of small things.
Please, feel free to share your comments and suggestions if you have any!
|
[
{
"code": null,
"e": 1016,
"s": 172,
"text": "Data is called as the new oil of 21st Century. It is very important to juggle with the data to extract and use the correct information to solve our problems. Working with data can be exciting and sometimes tedious for people. As it is rightly said, βData Scientists spend 80% of their time cleaning the dataβ. Being a part of that pack, I go through the same process when encountering a new dataset. The same activity is not limited to until the Machine Learning(ML) system is implemented and deployed to production. When generating predictions in real time, the data might change due to unintuitive and unforseeable circumstances like error due to human interference, wrong data submitted, a new trend in data, problem while recording data, and many more. A simple ML system with multiple steps involved looks like shown in the diagram below:"
},
{
"code": null,
"e": 1189,
"s": 1016,
"text": "This needs to be slightly shifted by introducing or labeling another component explicitly, after data preparation and before feature engineering we name as Data Validation:"
},
{
"code": null,
"e": 1530,
"s": 1189,
"text": "The article is focused on why data validation is important and how can one use different strategies to seemlessly integrate it in their pipeline. After some work, I learnt how to implement scripts that would do data validation to save some of the time. Above that, I automated them using some of the pre-built packages, stepping up my game!"
},
{
"code": null,
"e": 2533,
"s": 1530,
"text": "Almost 85% of projects will not make it to production as per Gartner. Machine Learning (ML) Pipelines usually face several hiccups when pushed in production. One of the major issues I have quite often experienced is the compromise of data quality. Spending multiple hours of a day, several times a month maybe, and figuring out that the data that came through was unacceptable because of some reason can be quite relieving but frustrating at the same time. Many reasons can contribute that leads to data type getting changed like, text getting introduced instead of an integer, an integer was on outlier (probably 10 times higher) or an entire specific column was not received in the data feed, to mention a few. That is why adding this extra step is so important. Validating manually can take some extra effort and time. Making it automated(to an extent) could reduce the burden of the Data Science team. There are some major benefits I see by integrating an automated data validation in the pipeline:"
},
{
"code": null,
"e": 2565,
"s": 2533,
"text": "Saves time by a couple of hours"
},
{
"code": null,
"e": 2601,
"s": 2565,
"text": "Less frustration among team members"
},
{
"code": null,
"e": 2644,
"s": 2601,
"text": "More productive by focusing on other areas"
},
{
"code": null,
"e": 2698,
"s": 2644,
"text": "Trying to make your production model more accurate ;)"
},
{
"code": null,
"e": 2931,
"s": 2698,
"text": "Python community has already built some outstanding packages to take care of these issues in a very smart way. I am going to share a few of them which I have explored and how I engineered my scripts to make them part of my pipeline."
},
{
"code": null,
"e": 3053,
"s": 2931,
"text": "Data Source: I took a very recent dataset to show how one can implement these packages. Here is the link to get the data."
},
{
"code": null,
"e": 3329,
"s": 3053,
"text": "Pandera provides a very simple and flexible API for performing data validation for data frame or series data. It also helps in performing complex statistical validation like hypothesis testing like two_sample_ttest. More details about the package and usage can be found here."
},
{
"code": null,
"e": 3372,
"s": 3329,
"text": "Take a sample of 10 rows from the dataset:"
},
{
"code": null,
"e": 4176,
"s": 3372,
"text": "As we can see, there are multiple columns of different data types: String, Int, Float, Datetime. We need to define the schema of the data we expect. I have defined a simple schema without any strict rules for data validation checks as seen in the code above. Based on the expected data type, we can either use pa.Int for Integer, pa.String for String, pa.Float for float or pa.DateTime if there is a date and time. Here we set nullable = True if we expect NaN values else False. Moreover, if we set coerce = True, it will convert the column into the expected datatype without giving any errors. For e.g. converting float to int, int to string, etc. On validating the data, the output will the data frame itself, as it passes all the checks (try it!!!). If it fails, the output would look something like:"
},
{
"code": null,
"e": 4261,
"s": 4176,
"text": "Traceback (most recent call last):...ValueError: cannot convert float NaN to integer"
},
{
"code": null,
"e": 4390,
"s": 4261,
"text": "There are some amazing capabilities that I have explored about Pandera which I will try to explain with as much detail as I can."
},
{
"code": null,
"e": 4533,
"s": 4390,
"text": "Sometimes, columns might be optional and not required. In such a case, we can set required = False. By default required = True for all columns"
},
{
"code": null,
"e": 4615,
"s": 4533,
"text": "As we see in the screenshot below, it returned data as output without any errors."
},
{
"code": null,
"e": 4691,
"s": 4615,
"text": "Try setting required=True for the same column and run the above code again."
},
{
"code": null,
"e": 4853,
"s": 4691,
"text": "By default, if a new column is added to the data frame and not defined in the schema, no error will be raised. However, if you want to you can set strict = True."
},
{
"code": null,
"e": 4965,
"s": 4853,
"text": "Running the code above we see below that it throws the errors that βextra_columnβ is not defined in the schema."
},
{
"code": null,
"e": 5055,
"s": 4965,
"text": "If you see my code, I have added lazy = True which gives a more detailed view as follows:"
},
{
"code": null,
"e": 5188,
"s": 5055,
"text": "Index can also be validated if there is any specific pattern or holds any special importance in the dataset. For example, see below:"
},
{
"code": null,
"e": 5399,
"s": 5188,
"text": "I created and set that column as an index to show how we can do Index validation. Outside the parenthesis of the schema, one can specify the index format that is expected. Again the output is the same as before"
},
{
"code": null,
"e": 5517,
"s": 5399,
"text": "Here we performed a single index validation. MultiIndex validation can be performed in a similar way. Check out here."
},
{
"code": null,
"e": 5924,
"s": 5517,
"text": "Once we have defined the schema to validate the data, it is possible to transform the schema in the pipeline itself, after new columns have been introduced because of additional computation (which happens 100% of the time). Letβs say initially we only have Id, County, Province_State, Country_Region, Population as the columns. We add new columns Weight, Date, Target, TargetValue to the schema as follows:"
},
{
"code": null,
"e": 5987,
"s": 5924,
"text": "On printing the schema as we show above, we get the following:"
},
{
"code": null,
"e": 6074,
"s": 5987,
"text": "On the other hand, we can also remove some columns from the schema if needed as below:"
},
{
"code": null,
"e": 6152,
"s": 6074,
"text": "One can do a more detailed check on the column using Check object as follows:"
},
{
"code": null,
"e": 6508,
"s": 6152,
"text": "Pandera has some pre-built checks that can be directly used like greater_than_or_equal_to, less_than. A custom check can also be passed for e.g. here we have used lambda argument to calculate the length of the string. This is one of the best functionalities in Pandera and can bring a lot more value to the data validation strategy. Find more details here"
},
{
"code": null,
"e": 6715,
"s": 6508,
"text": "I create separate scripts that run and gives a report of the validation, once the final data has been received before it goes to the next step. People can integrate them as a part of pre-processing as well."
},
{
"code": null,
"e": 6775,
"s": 6715,
"text": "One can also use them as decorators directly. See how here."
},
{
"code": null,
"e": 6910,
"s": 6775,
"text": "Apart from using directly on a data frame, it can also be applied to a series, a specific column check, or even an element-wise check."
},
{
"code": null,
"e": 7005,
"s": 6910,
"text": "Because of the flexibility regex operations can also be carried out on the data using Pandera."
},
{
"code": null,
"e": 7297,
"s": 7005,
"text": "Importantly, you would not have a perfect data validation schema right in first go. More than likely, you will make data validation schema βperfectβ and ML pipeline more robust by incorporating different validation strategies as you encounter data in real time, over a long course of period."
},
{
"code": null,
"e": 7638,
"s": 7297,
"text": "As the name of the package suggests, you can set expectations for the data to be validated. Honestly, I got so comfortable with Pandera, that I have not got a chance to explore to the full potential. It seems to be quite easy to implement and straight forward package to use. Below is a small snippet of the implementation of the same data:"
},
{
"code": null,
"e": 7771,
"s": 7638,
"text": "This is another package whose syntax is similar to Pandera. It can be more applied when data is in a dictionary form or JSON format."
},
{
"code": null,
"e": 7821,
"s": 7771,
"text": "More details about the package can be found here."
},
{
"code": null,
"e": 8047,
"s": 7821,
"text": "This is another great package if your data is obtained via XML, JSON or HTML form post. In other words, it is beneficial to validate any type of strings, mappings, and lists type of data. Below are some of their useful links:"
},
{
"code": null,
"e": 8090,
"s": 8047,
"text": "Github: https://github.com/Pylons/colander"
},
{
"code": null,
"e": 8165,
"s": 8090,
"text": "Documentation: https://docs.pylonsproject.org/projects/colander/en/latest/"
},
{
"code": null,
"e": 8372,
"s": 8165,
"text": "JsonSchema is an implementation of JSON schema for Python. As the name suggests, this package is very helpful for validating JSON data. Take the following example with valid JSON data and invalid JSON data:"
},
{
"code": null,
"e": 8425,
"s": 8372,
"text": "On running the invalid data, it will throw an error:"
},
{
"code": null,
"e": 8548,
"s": 8425,
"text": "As we can see, the price is expected to be number but string was provided rather. More details about it can be found here."
},
{
"code": null,
"e": 9099,
"s": 8548,
"text": "The post might seem to be mostly dominated by Pandera, as it is one of the packages that I use often. Writing this post was purely to share the voyage I embarked on. I am sure one can benefit more from these packages for their specific use case. Often walking the extra mile can achieve extraordinary results. Data validation is definitely that βextra mileβ. Developing data validation strategies might feel extra work but one can definitely benefit a lot if such a habit of creating automated scripts is formed, even for taking care of small things."
}
] |
Differences between Bit Rate and Baud Rate
|
Both Bit rate and Baud rate are used in data communication. Bit rate and Baud rate are related using below formula.
Bit Rate = Baud rate x the number of bit per baud
Following are the important differences between Pure Aloha and Slotted Aloha.
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "Both Bit rate and Baud rate are used in data communication. Bit rate and Baud rate are related using below formula."
},
{
"code": null,
"e": 1228,
"s": 1178,
"text": "Bit Rate = Baud rate x the number of bit per baud"
},
{
"code": null,
"e": 1306,
"s": 1228,
"text": "Following are the important differences between Pure Aloha and Slotted Aloha."
}
] |
Kernel Regression β with example and code | by Niranjan Pramanik, Ph.D. | Towards Data Science
|
In this article, how kernel function is used as a weighing function to develop non-parametric regression model is discussed. In the beginning of the article, a brief discussion about properties of kernel functions and steps to build kernels around data points are presented.
In non-parametric statistics, a kernel is a weighting function which satisfies the following properties.
A kernel function must be symmetrical. Mathematically this property can be expressed as K (-u) = K (+u). The symmetric property of kernel function enables its maximum value (max(K(u)) to lie in the middle of the curve.
A kernel function must be symmetrical. Mathematically this property can be expressed as K (-u) = K (+u). The symmetric property of kernel function enables its maximum value (max(K(u)) to lie in the middle of the curve.
2. The area under the curve of the function must be equal to one. Mathematically, this property is expressed as:
3. Value of kernel function can not be negative i.e. K(u) β₯ 0 for all ββ < u < β.
In this article, Gaussian kernel function is used to calculate kernels for the data points. The equation for Gaussian kernel is:
Where xi is the observed data point. x is the value where kernel function is computed and h is called the bandwidth. Bandwidth in kernel regression is called the smoothing parameter because it controls variance and bias in the output. The effect of bandwidth value on model prediction is discussed later in this article.
Consider there are six data points each showing mark obtained by individual student in a subject. The steps to construct kernel at each data point using Gaussian kernel function is mentioned below.
xi = {65, 75, 67, 79, 81, 91} Where x1 = 65, x2 = 75 ... x6 = 91.
Three inputs are required to construct a kernel curve around a data point.
i. Observation data point, xi
ii. Value of h
iii. Linearly spaced series of data points which includes observed data points where K values need to be estimated. As for example, Xj = {50,51,52 .... 99}
The steps to calculate K values for all values of Xj for a given value of xi and h is shown in the table below, where xi = 65 and h = 5.5. The last column in the table shows the ordinates of the kernel for xi = 65.
Xj and K are plotted below to visualize the kernel. Note that x-axis in the plot is Xj on which kernel curves are built at xi as mean and h as standard deviation as in the case of Gaussian distribution.
Similarly, at all six observed data points, kernel values are estimated and plotted as below. It is observed that value of K is nearly 0 for Xj values those are quite far from xi. For instance, kernel value at Xj = 99 is zero for xi = 65.
In this section, kernel values are used to derive weights to predict outputs from given inputs. Steps involved to calculate weights and finally to use them in predicting output variable, y from predictor variable, x is explained in detail in the following sections. Letβs start with an example to clearly understand how kernel regression works.
In this example, a kernel regression model is developed to predict river flow from catchment area. As shown in the data below, there exists a non-linear relationship between catchment area (in square mile) and river flow (in cubic feet per sec). The output, y is the river flow and input, x is the catchment area in this example.
Initially, kernels are estimated as described in the previous sections using a bandwidth value for all inputs. Then used them to calculate weights. In this example, a bandwidth value of 10 is used to explain kernel regression. However, bandwidth value needs to be optimized to fit the data appropriately. The plotted kernels at different values of x are shown in the figure below.
It is important to understand that kernels are developed at all values of xi. The fundamental calculation behind kernel regression is to estimate weighted sum of all observed y values for a given predictor value, xi. Weights are nothing but the kernel values, scaled between 0 and 1, intersecting the line perpendicular to x-axis at given xi (as shown in the figure below for this example).
The star marks in the above show the intersection points and their corresponding kernel values. The kernel values are scaled between 0 and 1 to use them as weights. Following equation is used to scale the kernel values between 0 and 1.
Where wi is the weight for input i and n is the total number of data points. The output y for x = 50 is computed as the weighted sum of all observed y values as shown in the equation below.
Where y11 is the river flow for Area = 11 and w11 is the corresponding weight and it goes like this for other terms in the equation.
Following table shows the steps involved in calculating weights from kernel values for input x = 50. The last column in the table provides final output i.e. computed river flow from an area of 50 square miles.
Similarly, for all values of x, weights are estimated as mentioned in the table above and used to calculate corresponding y values. The predicted river flow values for different area inputs are shown in the table as well as in the plot below.
Above calculation is based on a bandwidth value of 10. Kernel bandwidth influences prediction by a huge margin as shown in the figures below.
A small value of bandwidth over-fits data because of narrower kernel which gives high weight to the βyiβ of βxiβ in the training data set when predicted for xi. Low bandwidth produces lot of variance in the output which does not look realistic whereas high value of bandwidth over-smooths the output which fails to reveal true relationship between input and output. Therefore to attain a bias-variance trade-off, bandwidth should be optimized in kernel regression.
#Kernel regressiondata <- data.frame(Area = c(11,22,33,44,50,56,67,70,78,89,90,100), RiverFlow = c(2337,2750,2301,2500,1700,2100,1100,1750,1000,1642, 2000,1932)) x <- data$Areay <- data$RiverFlow#function to calculate Gaussian kernelgausinKernel <- function(x,b){ K <- (1/((sqrt(2*pi))))*exp(-0.5 *(x/b)^2) return(K)}b <- 10 #bandwidthkdeEstimateyX <- seq(5,110,1)ykernel <- NULLfor(xesti in kdeEstimateyX){ xx <- xesti - x K <-gausinKernel(xx,b) Ksum <- sum(K) weight <- K/Ksum yk <- sum(weight*y) xkyk <- c(xesti,yk) ykernel <- rbind(ykernel,xkyk)}plot(x,y,xlab = "Area", ylab = "Flow", col = 'blue', cex = 2)lines(ykernel[,1],ykernel[,2], col = 'red', lwd = 2)
R. Tibshirani and L. Wasserman, Nonparametric Regression, Statistical Machine Learning (2015) β lecture note of Carnegie Mellon University
|
[
{
"code": null,
"e": 447,
"s": 172,
"text": "In this article, how kernel function is used as a weighing function to develop non-parametric regression model is discussed. In the beginning of the article, a brief discussion about properties of kernel functions and steps to build kernels around data points are presented."
},
{
"code": null,
"e": 552,
"s": 447,
"text": "In non-parametric statistics, a kernel is a weighting function which satisfies the following properties."
},
{
"code": null,
"e": 771,
"s": 552,
"text": "A kernel function must be symmetrical. Mathematically this property can be expressed as K (-u) = K (+u). The symmetric property of kernel function enables its maximum value (max(K(u)) to lie in the middle of the curve."
},
{
"code": null,
"e": 990,
"s": 771,
"text": "A kernel function must be symmetrical. Mathematically this property can be expressed as K (-u) = K (+u). The symmetric property of kernel function enables its maximum value (max(K(u)) to lie in the middle of the curve."
},
{
"code": null,
"e": 1103,
"s": 990,
"text": "2. The area under the curve of the function must be equal to one. Mathematically, this property is expressed as:"
},
{
"code": null,
"e": 1185,
"s": 1103,
"text": "3. Value of kernel function can not be negative i.e. K(u) β₯ 0 for all ββ < u < β."
},
{
"code": null,
"e": 1314,
"s": 1185,
"text": "In this article, Gaussian kernel function is used to calculate kernels for the data points. The equation for Gaussian kernel is:"
},
{
"code": null,
"e": 1635,
"s": 1314,
"text": "Where xi is the observed data point. x is the value where kernel function is computed and h is called the bandwidth. Bandwidth in kernel regression is called the smoothing parameter because it controls variance and bias in the output. The effect of bandwidth value on model prediction is discussed later in this article."
},
{
"code": null,
"e": 1833,
"s": 1635,
"text": "Consider there are six data points each showing mark obtained by individual student in a subject. The steps to construct kernel at each data point using Gaussian kernel function is mentioned below."
},
{
"code": null,
"e": 1899,
"s": 1833,
"text": "xi = {65, 75, 67, 79, 81, 91} Where x1 = 65, x2 = 75 ... x6 = 91."
},
{
"code": null,
"e": 1974,
"s": 1899,
"text": "Three inputs are required to construct a kernel curve around a data point."
},
{
"code": null,
"e": 2004,
"s": 1974,
"text": "i. Observation data point, xi"
},
{
"code": null,
"e": 2019,
"s": 2004,
"text": "ii. Value of h"
},
{
"code": null,
"e": 2175,
"s": 2019,
"text": "iii. Linearly spaced series of data points which includes observed data points where K values need to be estimated. As for example, Xj = {50,51,52 .... 99}"
},
{
"code": null,
"e": 2390,
"s": 2175,
"text": "The steps to calculate K values for all values of Xj for a given value of xi and h is shown in the table below, where xi = 65 and h = 5.5. The last column in the table shows the ordinates of the kernel for xi = 65."
},
{
"code": null,
"e": 2593,
"s": 2390,
"text": "Xj and K are plotted below to visualize the kernel. Note that x-axis in the plot is Xj on which kernel curves are built at xi as mean and h as standard deviation as in the case of Gaussian distribution."
},
{
"code": null,
"e": 2832,
"s": 2593,
"text": "Similarly, at all six observed data points, kernel values are estimated and plotted as below. It is observed that value of K is nearly 0 for Xj values those are quite far from xi. For instance, kernel value at Xj = 99 is zero for xi = 65."
},
{
"code": null,
"e": 3177,
"s": 2832,
"text": "In this section, kernel values are used to derive weights to predict outputs from given inputs. Steps involved to calculate weights and finally to use them in predicting output variable, y from predictor variable, x is explained in detail in the following sections. Letβs start with an example to clearly understand how kernel regression works."
},
{
"code": null,
"e": 3507,
"s": 3177,
"text": "In this example, a kernel regression model is developed to predict river flow from catchment area. As shown in the data below, there exists a non-linear relationship between catchment area (in square mile) and river flow (in cubic feet per sec). The output, y is the river flow and input, x is the catchment area in this example."
},
{
"code": null,
"e": 3888,
"s": 3507,
"text": "Initially, kernels are estimated as described in the previous sections using a bandwidth value for all inputs. Then used them to calculate weights. In this example, a bandwidth value of 10 is used to explain kernel regression. However, bandwidth value needs to be optimized to fit the data appropriately. The plotted kernels at different values of x are shown in the figure below."
},
{
"code": null,
"e": 4279,
"s": 3888,
"text": "It is important to understand that kernels are developed at all values of xi. The fundamental calculation behind kernel regression is to estimate weighted sum of all observed y values for a given predictor value, xi. Weights are nothing but the kernel values, scaled between 0 and 1, intersecting the line perpendicular to x-axis at given xi (as shown in the figure below for this example)."
},
{
"code": null,
"e": 4515,
"s": 4279,
"text": "The star marks in the above show the intersection points and their corresponding kernel values. The kernel values are scaled between 0 and 1 to use them as weights. Following equation is used to scale the kernel values between 0 and 1."
},
{
"code": null,
"e": 4705,
"s": 4515,
"text": "Where wi is the weight for input i and n is the total number of data points. The output y for x = 50 is computed as the weighted sum of all observed y values as shown in the equation below."
},
{
"code": null,
"e": 4838,
"s": 4705,
"text": "Where y11 is the river flow for Area = 11 and w11 is the corresponding weight and it goes like this for other terms in the equation."
},
{
"code": null,
"e": 5048,
"s": 4838,
"text": "Following table shows the steps involved in calculating weights from kernel values for input x = 50. The last column in the table provides final output i.e. computed river flow from an area of 50 square miles."
},
{
"code": null,
"e": 5291,
"s": 5048,
"text": "Similarly, for all values of x, weights are estimated as mentioned in the table above and used to calculate corresponding y values. The predicted river flow values for different area inputs are shown in the table as well as in the plot below."
},
{
"code": null,
"e": 5433,
"s": 5291,
"text": "Above calculation is based on a bandwidth value of 10. Kernel bandwidth influences prediction by a huge margin as shown in the figures below."
},
{
"code": null,
"e": 5898,
"s": 5433,
"text": "A small value of bandwidth over-fits data because of narrower kernel which gives high weight to the βyiβ of βxiβ in the training data set when predicted for xi. Low bandwidth produces lot of variance in the output which does not look realistic whereas high value of bandwidth over-smooths the output which fails to reveal true relationship between input and output. Therefore to attain a bias-variance trade-off, bandwidth should be optimized in kernel regression."
},
{
"code": null,
"e": 6611,
"s": 5898,
"text": "#Kernel regressiondata <- data.frame(Area = c(11,22,33,44,50,56,67,70,78,89,90,100), RiverFlow = c(2337,2750,2301,2500,1700,2100,1100,1750,1000,1642, 2000,1932)) x <- data$Areay <- data$RiverFlow#function to calculate Gaussian kernelgausinKernel <- function(x,b){ K <- (1/((sqrt(2*pi))))*exp(-0.5 *(x/b)^2) return(K)}b <- 10 #bandwidthkdeEstimateyX <- seq(5,110,1)ykernel <- NULLfor(xesti in kdeEstimateyX){ xx <- xesti - x K <-gausinKernel(xx,b) Ksum <- sum(K) weight <- K/Ksum yk <- sum(weight*y) xkyk <- c(xesti,yk) ykernel <- rbind(ykernel,xkyk)}plot(x,y,xlab = \"Area\", ylab = \"Flow\", col = 'blue', cex = 2)lines(ykernel[,1],ykernel[,2], col = 'red', lwd = 2)"
}
] |
Monads in Scala - GeeksforGeeks
|
24 Aug, 2020
In Scala, Monads is a construction which performs successive calculations. It is an object which covers the other object. It is worth noting that here, the output of an operation at some step is an input to another computations, which is a parent to the recent step of the program stated. Monad is neither a class nor a trait, it is a concept. The maximum collections of the Scala are Monads but not all the Monads are collections, there are several Monads which are containers like Options in Scala. In short, we can say that in Scala the data types that implements map as well as flatMap() like Options, Lists, etc. are called as Monads.
The objects are enclosed with Monads as it yields the following two functions:
unit() : It is like void in Java, it does not returns any data types.flatMap() : It is similar to the map() in Scala but it returns a series in place of returning a single component.
unit() : It is like void in Java, it does not returns any data types.
flatMap() : It is similar to the map() in Scala but it returns a series in place of returning a single component.
Letβs see an example to illustrate it explicitly.
var x = Seq("Geeks", "For", "Geeks")
Letβs apply map() on the sequence given.
// Applying map()
var y = x.map(_.toUpperCase)
// Output
List(GEEKS, FOR, GEEKS)
Now, letβs apply flatMap() on the sequence given.
// Applying flatMap()
var z = x.flatMap(_.toUpperCase)
// Output
List(G, E, E, K, S, F, O, R, G, E, E, K, S)
So, when a flatMap is applied on the Sequence stated above then a List is returned where the inner grouping is removed and a sequence is generated.
Note: Collections that support map as well as flatMap are called as monadic. Now, letβs see some examples of Monads in Scala.
Examples of collection supporting map as well as flatMap.Example :
// Scala program of Monads // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating list of numbers val list1 = List(1, 2, 3, 4) val list2 = List(5, 6, 7, 8) // Applying 'flatMap' and 'map' val z = list1 flatMap { q => list2 map { r => q + r } } // Displays output println(z) }}
List(6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12)
Letβs see now, how the output is computed.
// Applying map() we get list like belowList(List((1+5), (1+6), (1+7), (1+8)), List((2+5), (2+6), (2+7), (2+8)),List((3+5), (3+6), (3+7), (3+8)), List((4+5), (4+6), (4+7), (4+8)))
After evaluation we get,
List(List(6, 7, 8, 9), List(7, 8, 9, 10), List(8, 9, 10, 11), List(9, 10, 11, 12))
So, we get a List of Lists and for each operation we have a different list after applying map(), now letβs apply flatMap().
// Applying flatMap() we get a list like belowList(6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12)
So, when we apply flatMap() the inner grouping is removed.
Example :
// Scala program of Monads // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating list of numbers val x = (1 to 3).toList val y = (1 to 7 by 2).toList // Applying 'flatMap'and 'map' val z = x flatMap { s => y map { t => s * t } } // Displays output println(z) }}
List(1, 3, 5, 7, 2, 6, 10, 14, 3, 9, 15, 21)
Here, List(x) = (1, 2, 3) and List(y) = (1, 3, 5, 7) then letβs see now, how the output is computed.
// Applying map() we get list like belowList(List((1*1), (1*3), (1*5), (1*7)), List((2*1), (2*3), (2*5), (2*7)),List((3*1), (3*3), (3*5), (3*7)))
And after evaluation we get,
List(List(1, 3,, 5, 7), List(2, 6, 10, 14), List(3, 9, 15, 21))
Now, letβs apply flatMap().
// Applying flatMap() we get a list like below
List(1, 3, 5, 7, 2, 6, 10, 14, 3, 9, 15, 21)
Therefore, the internal grouping is removed.
mail2taras
Picked
Scala
scala-collection
Scala-Map
Scala
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Lists
Class and Object in Scala
Scala Tutorial β Learn Scala with Step By Step Guide
Inheritance in Scala
Scala Singleton and Companion Objects
Operators in Scala
Scala Constructors
How to install Scala on Windows?
Hello World in Scala
Throw Keyword in Scala
|
[
{
"code": null,
"e": 23876,
"s": 23848,
"text": "\n24 Aug, 2020"
},
{
"code": null,
"e": 24516,
"s": 23876,
"text": "In Scala, Monads is a construction which performs successive calculations. It is an object which covers the other object. It is worth noting that here, the output of an operation at some step is an input to another computations, which is a parent to the recent step of the program stated. Monad is neither a class nor a trait, it is a concept. The maximum collections of the Scala are Monads but not all the Monads are collections, there are several Monads which are containers like Options in Scala. In short, we can say that in Scala the data types that implements map as well as flatMap() like Options, Lists, etc. are called as Monads."
},
{
"code": null,
"e": 24595,
"s": 24516,
"text": "The objects are enclosed with Monads as it yields the following two functions:"
},
{
"code": null,
"e": 24778,
"s": 24595,
"text": "unit() : It is like void in Java, it does not returns any data types.flatMap() : It is similar to the map() in Scala but it returns a series in place of returning a single component."
},
{
"code": null,
"e": 24848,
"s": 24778,
"text": "unit() : It is like void in Java, it does not returns any data types."
},
{
"code": null,
"e": 24962,
"s": 24848,
"text": "flatMap() : It is similar to the map() in Scala but it returns a series in place of returning a single component."
},
{
"code": null,
"e": 25012,
"s": 24962,
"text": "Letβs see an example to illustrate it explicitly."
},
{
"code": null,
"e": 25050,
"s": 25012,
"text": "var x = Seq(\"Geeks\", \"For\", \"Geeks\")\n"
},
{
"code": null,
"e": 25091,
"s": 25050,
"text": "Letβs apply map() on the sequence given."
},
{
"code": null,
"e": 25174,
"s": 25091,
"text": "// Applying map()\n var y = x.map(_.toUpperCase)\n// Output\nList(GEEKS, FOR, GEEKS)\n"
},
{
"code": null,
"e": 25224,
"s": 25174,
"text": "Now, letβs apply flatMap() on the sequence given."
},
{
"code": null,
"e": 25334,
"s": 25224,
"text": "// Applying flatMap()\nvar z = x.flatMap(_.toUpperCase)\n// Output\nList(G, E, E, K, S, F, O, R, G, E, E, K, S)\n"
},
{
"code": null,
"e": 25482,
"s": 25334,
"text": "So, when a flatMap is applied on the Sequence stated above then a List is returned where the inner grouping is removed and a sequence is generated."
},
{
"code": null,
"e": 25608,
"s": 25482,
"text": "Note: Collections that support map as well as flatMap are called as monadic. Now, letβs see some examples of Monads in Scala."
},
{
"code": null,
"e": 25675,
"s": 25608,
"text": "Examples of collection supporting map as well as flatMap.Example :"
},
{
"code": "// Scala program of Monads // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating list of numbers val list1 = List(1, 2, 3, 4) val list2 = List(5, 6, 7, 8) // Applying 'flatMap' and 'map' val z = list1 flatMap { q => list2 map { r => q + r } } // Displays output println(z) }} ",
"e": 26124,
"s": 25675,
"text": null
},
{
"code": null,
"e": 26184,
"s": 26124,
"text": "List(6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12)\n"
},
{
"code": null,
"e": 26227,
"s": 26184,
"text": "Letβs see now, how the output is computed."
},
{
"code": null,
"e": 26407,
"s": 26227,
"text": "// Applying map() we get list like belowList(List((1+5), (1+6), (1+7), (1+8)), List((2+5), (2+6), (2+7), (2+8)),List((3+5), (3+6), (3+7), (3+8)), List((4+5), (4+6), (4+7), (4+8)))"
},
{
"code": null,
"e": 26432,
"s": 26407,
"text": "After evaluation we get,"
},
{
"code": null,
"e": 26515,
"s": 26432,
"text": "List(List(6, 7, 8, 9), List(7, 8, 9, 10), List(8, 9, 10, 11), List(9, 10, 11, 12))"
},
{
"code": null,
"e": 26639,
"s": 26515,
"text": "So, we get a List of Lists and for each operation we have a different list after applying map(), now letβs apply flatMap()."
},
{
"code": null,
"e": 26744,
"s": 26639,
"text": "// Applying flatMap() we get a list like belowList(6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12)"
},
{
"code": null,
"e": 26803,
"s": 26744,
"text": "So, when we apply flatMap() the inner grouping is removed."
},
{
"code": null,
"e": 26813,
"s": 26803,
"text": "Example :"
},
{
"code": "// Scala program of Monads // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating list of numbers val x = (1 to 3).toList val y = (1 to 7 by 2).toList // Applying 'flatMap'and 'map' val z = x flatMap { s => y map { t => s * t } } // Displays output println(z) }} ",
"e": 27226,
"s": 26813,
"text": null
},
{
"code": null,
"e": 27272,
"s": 27226,
"text": "List(1, 3, 5, 7, 2, 6, 10, 14, 3, 9, 15, 21)\n"
},
{
"code": null,
"e": 27373,
"s": 27272,
"text": "Here, List(x) = (1, 2, 3) and List(y) = (1, 3, 5, 7) then letβs see now, how the output is computed."
},
{
"code": null,
"e": 27519,
"s": 27373,
"text": "// Applying map() we get list like belowList(List((1*1), (1*3), (1*5), (1*7)), List((2*1), (2*3), (2*5), (2*7)),List((3*1), (3*3), (3*5), (3*7)))"
},
{
"code": null,
"e": 27548,
"s": 27519,
"text": "And after evaluation we get,"
},
{
"code": null,
"e": 27612,
"s": 27548,
"text": "List(List(1, 3,, 5, 7), List(2, 6, 10, 14), List(3, 9, 15, 21))"
},
{
"code": null,
"e": 27640,
"s": 27612,
"text": "Now, letβs apply flatMap()."
},
{
"code": null,
"e": 27733,
"s": 27640,
"text": "// Applying flatMap() we get a list like below\nList(1, 3, 5, 7, 2, 6, 10, 14, 3, 9, 15, 21)\n"
},
{
"code": null,
"e": 27778,
"s": 27733,
"text": "Therefore, the internal grouping is removed."
},
{
"code": null,
"e": 27789,
"s": 27778,
"text": "mail2taras"
},
{
"code": null,
"e": 27796,
"s": 27789,
"text": "Picked"
},
{
"code": null,
"e": 27802,
"s": 27796,
"text": "Scala"
},
{
"code": null,
"e": 27819,
"s": 27802,
"text": "scala-collection"
},
{
"code": null,
"e": 27829,
"s": 27819,
"text": "Scala-Map"
},
{
"code": null,
"e": 27835,
"s": 27829,
"text": "Scala"
},
{
"code": null,
"e": 27854,
"s": 27835,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27952,
"s": 27854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27961,
"s": 27952,
"text": "Comments"
},
{
"code": null,
"e": 27974,
"s": 27961,
"text": "Old Comments"
},
{
"code": null,
"e": 27986,
"s": 27974,
"text": "Scala Lists"
},
{
"code": null,
"e": 28012,
"s": 27986,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 28065,
"s": 28012,
"text": "Scala Tutorial β Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 28086,
"s": 28065,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 28124,
"s": 28086,
"text": "Scala Singleton and Companion Objects"
},
{
"code": null,
"e": 28143,
"s": 28124,
"text": "Operators in Scala"
},
{
"code": null,
"e": 28162,
"s": 28143,
"text": "Scala Constructors"
},
{
"code": null,
"e": 28195,
"s": 28162,
"text": "How to install Scala on Windows?"
},
{
"code": null,
"e": 28216,
"s": 28195,
"text": "Hello World in Scala"
}
] |
MySQL statement to copy data from one table and insert into another table
|
For this, you can use INSERT INTO....SELECT statement. Let us first create a table β
mysql> create table DemoTabe1 (Marks int);
Query OK, 0 rows affected (0.66 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTabe1 values(68);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTabe1 values(89);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTabe1 values(99);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTabe1 values(39);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTabe1 values(49);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement β
mysql> select *from DemoTabe1;
This will produce the following output β
+-------+
| Marks |
+-------+
| 68 |
| 89 |
| 99 |
| 39 |
| 49 |
+-------+
5 rows in set (0.00 sec)
Following is the query to create second table β
mysql> create table DemoTabe2 (Score int);
Query OK, 0 rows affected (0.66 sec)
Here is the query for inserting data to another table β
mysql> insert into DemoTabe2(Score) select Marks from DemoTabe1;
Query OK, 5 rows affected (0.16 sec)
Records: 5 Duplicates: 0 Warnings: 0
Display all records from the table using select statement β
mysql> select *from DemoTabe2;
This will produce the following output. Now the same records are visible in the second table β
+-------+
| Score |
+-------+
| 68 |
| 89 |
| 99 |
| 39 |
| 49 |
+-------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "For this, you can use INSERT INTO....SELECT statement. Let us first create a table β"
},
{
"code": null,
"e": 1227,
"s": 1147,
"text": "mysql> create table DemoTabe1 (Marks int);\nQuery OK, 0 rows affected (0.66 sec)"
},
{
"code": null,
"e": 1283,
"s": 1227,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1668,
"s": 1283,
"text": "mysql> insert into DemoTabe1 values(68);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTabe1 values(89);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTabe1 values(99);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTabe1 values(39);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTabe1 values(49);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1728,
"s": 1668,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1759,
"s": 1728,
"text": "mysql> select *from DemoTabe1;"
},
{
"code": null,
"e": 1800,
"s": 1759,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 1915,
"s": 1800,
"text": "+-------+\n| Marks |\n+-------+\n| 68 |\n| 89 |\n| 99 |\n| 39 |\n| 49 |\n+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1963,
"s": 1915,
"text": "Following is the query to create second table β"
},
{
"code": null,
"e": 2043,
"s": 1963,
"text": "mysql> create table DemoTabe2 (Score int);\nQuery OK, 0 rows affected (0.66 sec)"
},
{
"code": null,
"e": 2099,
"s": 2043,
"text": "Here is the query for inserting data to another table β"
},
{
"code": null,
"e": 2238,
"s": 2099,
"text": "mysql> insert into DemoTabe2(Score) select Marks from DemoTabe1;\nQuery OK, 5 rows affected (0.16 sec)\nRecords: 5 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2298,
"s": 2238,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 2329,
"s": 2298,
"text": "mysql> select *from DemoTabe2;"
},
{
"code": null,
"e": 2424,
"s": 2329,
"text": "This will produce the following output. Now the same records are visible in the second table β"
},
{
"code": null,
"e": 2539,
"s": 2424,
"text": "+-------+\n| Score |\n+-------+\n| 68 |\n| 89 |\n| 99 |\n| 39 |\n| 49 |\n+-------+\n5 rows in set (0.00 sec)"
}
] |
Finding n most frequent words from a sentence in JavaScript
|
For the purpose of this question, we define a sentence as a string that contains English alphabets and punctuations and a word is a substring of that sentence joined together by whitespaces.
We are required to write a JavaScript function that takes in a sentence string, str, as the first argument and a number, num, as the second argument. The function should first count the frequency of each word in the sentence and then return an array of length num containing num most frequent words placed according to decreasing frequencies.
For example β
If the input sentence and the number is β
const str = 'i am a good coder and i know that i can solve a problem';
const num = 2;
Then the output should be β
const output = ['i', 'a'];
because 'i' appears for 3 times while 'a' appears for 2 times in the array and they are the 2 most frequent words in the string.
The code for this will be β
Live Demo
const str = 'i am a good coder and i know that i can solve a problem';
const num = 2;
const findMostFrequent = (str = '', num = 1) => {
const strArr = str.split(' ');
const map = {};
strArr.forEach(word => {
if(map.hasOwnProperty(word)){
map[word]++;
}else{
map[word] = 1;
}
});
const frequencyArr = Object.keys(map).map(key => [key, map[key]]);
frequencyArr.sort((a, b) => b[1] - a[1]);
return frequencyArr.slice(0, num).map(el => el[0]);
};
console.log(findMostFrequent(str, num));
And the output in the console will be β
[ 'i', 'a' ]
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "For the purpose of this question, we define a sentence as a string that contains English alphabets and punctuations and a word is a substring of that sentence joined together by whitespaces."
},
{
"code": null,
"e": 1596,
"s": 1253,
"text": "We are required to write a JavaScript function that takes in a sentence string, str, as the first argument and a number, num, as the second argument. The function should first count the frequency of each word in the sentence and then return an array of length num containing num most frequent words placed according to decreasing frequencies."
},
{
"code": null,
"e": 1610,
"s": 1596,
"text": "For example β"
},
{
"code": null,
"e": 1652,
"s": 1610,
"text": "If the input sentence and the number is β"
},
{
"code": null,
"e": 1738,
"s": 1652,
"text": "const str = 'i am a good coder and i know that i can solve a problem';\nconst num = 2;"
},
{
"code": null,
"e": 1766,
"s": 1738,
"text": "Then the output should be β"
},
{
"code": null,
"e": 1793,
"s": 1766,
"text": "const output = ['i', 'a'];"
},
{
"code": null,
"e": 1922,
"s": 1793,
"text": "because 'i' appears for 3 times while 'a' appears for 2 times in the array and they are the 2 most frequent words in the string."
},
{
"code": null,
"e": 1950,
"s": 1922,
"text": "The code for this will be β"
},
{
"code": null,
"e": 1961,
"s": 1950,
"text": " Live Demo"
},
{
"code": null,
"e": 2502,
"s": 1961,
"text": "const str = 'i am a good coder and i know that i can solve a problem';\nconst num = 2;\nconst findMostFrequent = (str = '', num = 1) => {\n const strArr = str.split(' ');\n const map = {};\n strArr.forEach(word => {\n if(map.hasOwnProperty(word)){\n map[word]++;\n }else{\n map[word] = 1;\n }\n });\n const frequencyArr = Object.keys(map).map(key => [key, map[key]]);\n frequencyArr.sort((a, b) => b[1] - a[1]);\n return frequencyArr.slice(0, num).map(el => el[0]);\n};\nconsole.log(findMostFrequent(str, num));"
},
{
"code": null,
"e": 2542,
"s": 2502,
"text": "And the output in the console will be β"
},
{
"code": null,
"e": 2555,
"s": 2542,
"text": "[ 'i', 'a' ]"
}
] |
Cascade notation in Dart Programming
|
Cascade notation is used when we want to operate a sequence of operations on the same object. The cascade notation is denoted by the (..) symbol.
It is similar to method chaining that we have in other programming languages and it does save us plenty of steps and need of temporary variable.
Consider the following example for a representation of how the cascade notation works in Dart.
Live Demo
class Sample{
var a;
var b;
void showA(x){
this.a = x;
}
void showB(y){
this.b = y;
}
void printValues(){
print(this.a);
print(this.b);
}
}
void main(){
Sample sampleOne = new Sample();
sampleOne.showA(2);
sampleOne.showB(3);
sampleOne.printValues();
Sample sampleTwo = new Sample();
sampleTwo..showA(2)
..showB(3)
..printValues();
}
In the above example, we have two objects created of a single class and we are calling three methods that are present in the above class. When we call the three methods on the object instance sampleOne, we are explicitly typing the name of the object three times followed by the dot notation and the call to methods.
In the second case, the sampleTwo is written only once and we made use of the cascade operator to call the methods we want.
It should be noted that we can't have semicolons(;) between the consecutive method calls as it will confuse the compiler and we will get an error.
2
3
2
3
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "Cascade notation is used when we want to operate a sequence of operations on the same object. The cascade notation is denoted by the (..) symbol."
},
{
"code": null,
"e": 1353,
"s": 1208,
"text": "It is similar to method chaining that we have in other programming languages and it does save us plenty of steps and need of temporary variable."
},
{
"code": null,
"e": 1448,
"s": 1353,
"text": "Consider the following example for a representation of how the cascade notation works in Dart."
},
{
"code": null,
"e": 1459,
"s": 1448,
"text": " Live Demo"
},
{
"code": null,
"e": 1866,
"s": 1459,
"text": "class Sample{\n var a;\n var b;\n void showA(x){\n this.a = x;\n }\n void showB(y){\n this.b = y;\n }\n void printValues(){\n print(this.a);\n print(this.b);\n }\n}\nvoid main(){\n Sample sampleOne = new Sample();\n sampleOne.showA(2);\n sampleOne.showB(3);\n sampleOne.printValues();\n\n Sample sampleTwo = new Sample();\n sampleTwo..showA(2)\n ..showB(3)\n ..printValues();\n}"
},
{
"code": null,
"e": 2183,
"s": 1866,
"text": "In the above example, we have two objects created of a single class and we are calling three methods that are present in the above class. When we call the three methods on the object instance sampleOne, we are explicitly typing the name of the object three times followed by the dot notation and the call to methods."
},
{
"code": null,
"e": 2307,
"s": 2183,
"text": "In the second case, the sampleTwo is written only once and we made use of the cascade operator to call the methods we want."
},
{
"code": null,
"e": 2454,
"s": 2307,
"text": "It should be noted that we can't have semicolons(;) between the consecutive method calls as it will confuse the compiler and we will get an error."
},
{
"code": null,
"e": 2462,
"s": 2454,
"text": "2\n3\n2\n3"
}
] |
BitArray.LeftShift() Method in C# with Examples - GeeksforGeeks
|
27 Mar, 2019
BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.LeftShift(Int32) method is used to shift the bits of the bit array to the left by one position and adds zeros on the shifted position. Original BitArray object will be modified on performing the operation Left shift.
Syntax: public System.Collections.BitArray LeftShift (int count);
Parameter:count is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 through positive 2,147,483,647.
Return value : It returns Bit Array.
Example 1: Suppose we have the bit array 10011 we want to shift it Left by two positions.
The final result is 00110.
// C# program to illustrate the// BitArray.LeftShift() Methodusing System;using System.Collections; class GeeksforGeeks { // Main Method public static void Main() { // Creating a BitArray BitArray BitArr = new BitArray(5); // Initializing values in BitArr BitArr[0] = true; BitArr[1] = true; BitArr[2] = false; BitArr[3] = false; BitArr[4] = true; // function calling Display(BitArr.LeftShift(2)); } // Displaying the result public static void Display(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }}
False
False
True
True
False
Example 2: Suppose we have the bit array 100011 we want to shift it left by three positions.
The final result is 000100.
// C# program to illustrate the// BitArray.LeftShift() Methodusing System;using System.Collections; class GeeksforGeeks { // Main Method public static void Main() { // Creating a BitArray BitArray BitArr = new BitArray(6); // Initializing values in BitArr BitArr[0] = true; BitArr[1] = false; BitArr[2] = false; BitArr[3] = false; BitArr[4] = true; BitArr[5] = true; // function calling Display(BitArr.LeftShift(3)); } // Displaying the result public static void Display(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }}
False
False
False
True
False
False
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray.leftshift?view=netcore-2.2
CSharp-Collections-BitArray
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
|
[
{
"code": null,
"e": 24003,
"s": 23975,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 24428,
"s": 24003,
"text": "BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.LeftShift(Int32) method is used to shift the bits of the bit array to the left by one position and adds zeros on the shifted position. Original BitArray object will be modified on performing the operation Left shift."
},
{
"code": null,
"e": 24494,
"s": 24428,
"text": "Syntax: public System.Collections.BitArray LeftShift (int count);"
},
{
"code": null,
"e": 24652,
"s": 24494,
"text": "Parameter:count is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 through positive 2,147,483,647."
},
{
"code": null,
"e": 24689,
"s": 24652,
"text": "Return value : It returns Bit Array."
},
{
"code": null,
"e": 24779,
"s": 24689,
"text": "Example 1: Suppose we have the bit array 10011 we want to shift it Left by two positions."
},
{
"code": null,
"e": 24806,
"s": 24779,
"text": "The final result is 00110."
},
{
"code": "// C# program to illustrate the// BitArray.LeftShift() Methodusing System;using System.Collections; class GeeksforGeeks { // Main Method public static void Main() { // Creating a BitArray BitArray BitArr = new BitArray(5); // Initializing values in BitArr BitArr[0] = true; BitArr[1] = true; BitArr[2] = false; BitArr[3] = false; BitArr[4] = true; // function calling Display(BitArr.LeftShift(2)); } // Displaying the result public static void Display(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }}",
"e": 25478,
"s": 24806,
"text": null
},
{
"code": null,
"e": 25507,
"s": 25478,
"text": "False\nFalse\nTrue\nTrue\nFalse\n"
},
{
"code": null,
"e": 25600,
"s": 25507,
"text": "Example 2: Suppose we have the bit array 100011 we want to shift it left by three positions."
},
{
"code": null,
"e": 25628,
"s": 25600,
"text": "The final result is 000100."
},
{
"code": "// C# program to illustrate the// BitArray.LeftShift() Methodusing System;using System.Collections; class GeeksforGeeks { // Main Method public static void Main() { // Creating a BitArray BitArray BitArr = new BitArray(6); // Initializing values in BitArr BitArr[0] = true; BitArr[1] = false; BitArr[2] = false; BitArr[3] = false; BitArr[4] = true; BitArr[5] = true; // function calling Display(BitArr.LeftShift(3)); } // Displaying the result public static void Display(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }}",
"e": 26326,
"s": 25628,
"text": null
},
{
"code": null,
"e": 26362,
"s": 26326,
"text": "False\nFalse\nFalse\nTrue\nFalse\nFalse\n"
},
{
"code": null,
"e": 26373,
"s": 26362,
"text": "Reference:"
},
{
"code": null,
"e": 26472,
"s": 26373,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray.leftshift?view=netcore-2.2"
},
{
"code": null,
"e": 26500,
"s": 26472,
"text": "CSharp-Collections-BitArray"
},
{
"code": null,
"e": 26529,
"s": 26500,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 26543,
"s": 26529,
"text": "CSharp-method"
},
{
"code": null,
"e": 26546,
"s": 26543,
"text": "C#"
},
{
"code": null,
"e": 26644,
"s": 26546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26653,
"s": 26644,
"text": "Comments"
},
{
"code": null,
"e": 26666,
"s": 26653,
"text": "Old Comments"
},
{
"code": null,
"e": 26689,
"s": 26666,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 26717,
"s": 26689,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 26763,
"s": 26717,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26778,
"s": 26763,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26818,
"s": 26778,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26836,
"s": 26818,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26867,
"s": 26836,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 26890,
"s": 26867,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26912,
"s": 26890,
"text": "C# | Class and Object"
}
] |
Python Modules
|
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
To create a module just save the code you want in a file with the file extension .py:
Save this code in a file named mymodule.py
Now we can use the module we just created, by using the import statement:
Import the module named mymodule, and call the greeting function:
Note: When using a function from a module, use the syntax: module_name.function_name.
The module can contain functions, as already described, but also variables of
all types (arrays, dictionaries, objects etc):
Save this code in the file mymodule.py
Import the module named mymodule, and access the person1 dictionary:
You can name the module file whatever you like, but it must have the file extension
.py
You can create an alias when you import a module, by using the as keyword:
Create an alias for mymodule called mx:
There are several built-in modules in Python, which you can import whenever you like.
Import and use the platform module:
There is a built-in function to list all the function names (or variable
names) in a module. The dir() function:
List all the defined names belonging to the platform module:
Note: The dir() function can be used on all
modules, also the ones you create yourself.
You can choose to import only parts from a module, by using the from keyword.
The module named mymodule has one function
and one dictionary:
Import only the person1 dictionary from the module:
Note: When importing using the from
keyword, do not use the module name when referring to elements in the module.
Example: person1["age"], not
mymodule.person1["age"]
What is the correct syntax to import a module named "mymodule"?
mymodule
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 52,
"s": 0,
"text": "Consider a module to be the same as a code library."
},
{
"code": null,
"e": 130,
"s": 52,
"text": "A file containing a set of functions you want to include in your application."
},
{
"code": null,
"e": 216,
"s": 130,
"text": "To create a module just save the code you want in a file with the file extension .py:"
},
{
"code": null,
"e": 259,
"s": 216,
"text": "Save this code in a file named mymodule.py"
},
{
"code": null,
"e": 333,
"s": 259,
"text": "Now we can use the module we just created, by using the import statement:"
},
{
"code": null,
"e": 399,
"s": 333,
"text": "Import the module named mymodule, and call the greeting function:"
},
{
"code": null,
"e": 485,
"s": 399,
"text": "Note: When using a function from a module, use the syntax: module_name.function_name."
},
{
"code": null,
"e": 611,
"s": 485,
"text": "The module can contain functions, as already described, but also variables of \nall types (arrays, dictionaries, objects etc):"
},
{
"code": null,
"e": 650,
"s": 611,
"text": "Save this code in the file mymodule.py"
},
{
"code": null,
"e": 719,
"s": 650,
"text": "Import the module named mymodule, and access the person1 dictionary:"
},
{
"code": null,
"e": 808,
"s": 719,
"text": "You can name the module file whatever you like, but it must have the file extension \n.py"
},
{
"code": null,
"e": 883,
"s": 808,
"text": "You can create an alias when you import a module, by using the as keyword:"
},
{
"code": null,
"e": 923,
"s": 883,
"text": "Create an alias for mymodule called mx:"
},
{
"code": null,
"e": 1009,
"s": 923,
"text": "There are several built-in modules in Python, which you can import whenever you like."
},
{
"code": null,
"e": 1045,
"s": 1009,
"text": "Import and use the platform module:"
},
{
"code": null,
"e": 1159,
"s": 1045,
"text": "There is a built-in function to list all the function names (or variable \nnames) in a module. The dir() function:"
},
{
"code": null,
"e": 1220,
"s": 1159,
"text": "List all the defined names belonging to the platform module:"
},
{
"code": null,
"e": 1311,
"s": 1220,
"text": "Note: The dir() function can be used on all \n modules, also the ones you create yourself."
},
{
"code": null,
"e": 1389,
"s": 1311,
"text": "You can choose to import only parts from a module, by using the from keyword."
},
{
"code": null,
"e": 1453,
"s": 1389,
"text": "The module named mymodule has one function \nand one dictionary:"
},
{
"code": null,
"e": 1505,
"s": 1453,
"text": "Import only the person1 dictionary from the module:"
},
{
"code": null,
"e": 1678,
"s": 1505,
"text": "Note: When importing using the from \n keyword, do not use the module name when referring to elements in the module. \n Example: person1[\"age\"], not\nmymodule.person1[\"age\"]"
},
{
"code": null,
"e": 1742,
"s": 1678,
"text": "What is the correct syntax to import a module named \"mymodule\"?"
},
{
"code": null,
"e": 1753,
"s": 1742,
"text": " mymodule\n"
},
{
"code": null,
"e": 1772,
"s": 1753,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1805,
"s": 1772,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1847,
"s": 1805,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1954,
"s": 1847,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1973,
"s": 1954,
"text": "help@w3schools.com"
}
] |
flush - Unix, Linux Command
|
flush [generic Postfix daemon options]
The record is implemented as a per-destination logfile with
as contents the queue IDs of deferred mail. A logfile is
append-only, and is truncated when delivery is requested
for the corresponding destination. A destination is the
part on the right-hand side of the right-most @ in
an email address.
Per-destination logfiles of deferred mail are maintained only for
eligible destinations. The list of eligible destinations is
specified with the fast_flush_domains configuration parameter,
which defaults to $relay_domains.
This server implements the following requests:
Delete empty per-destination logfiles that were not updated in
$fast_flush_purge_time days.
This request completes in the background.
Upon receipt of a request to deliver mail for an eligible
destination, the flush(8) server requests delivery of all messages
that are listed in that destinationβs logfile, regardless of the
recipients of those messages. This is not an issue for mail
that is sent to a relay_domains destination because
such mail typically only has recipients in one domain.
The text below provides only a parameter summary. See
postconf(5) for more details including examples.
/var/spool/postfix/flush, "fast flush" logfiles.
smtpd(8), SMTP server
qmgr(8), queue manager
postconf(5), configuration parameters
master(5), generic daemon options
master(8), process manager
syslogd(8), system logging
ETRN_README, Postfix ETRN howto
This service was introduced with Postfix version 1.0.
Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA
Advertisements
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": 10617,
"s": 10577,
"text": "flush [generic Postfix daemon options]\n"
},
{
"code": null,
"e": 10918,
"s": 10617,
"text": "\nThe record is implemented as a per-destination logfile with\nas contents the queue IDs of deferred mail. A logfile is\nappend-only, and is truncated when delivery is requested\nfor the corresponding destination. A destination is the\npart on the right-hand side of the right-most @ in\nan email address.\n"
},
{
"code": null,
"e": 11143,
"s": 10918,
"text": "\nPer-destination logfiles of deferred mail are maintained only for\neligible destinations. The list of eligible destinations is\nspecified with the fast_flush_domains configuration parameter,\nwhich defaults to $relay_domains.\n"
},
{
"code": null,
"e": 11192,
"s": 11143,
"text": "\nThis server implements the following requests:\n"
},
{
"code": null,
"e": 11286,
"s": 11192,
"text": "\nDelete empty per-destination logfiles that were not updated in\n$fast_flush_purge_time days.\n"
},
{
"code": null,
"e": 11330,
"s": 11286,
"text": "\nThis request completes in the background.\n"
},
{
"code": null,
"e": 11691,
"s": 11332,
"text": "\nUpon receipt of a request to deliver mail for an eligible\ndestination, the flush(8) server requests delivery of all messages\nthat are listed in that destinationβs logfile, regardless of the\nrecipients of those messages. This is not an issue for mail\nthat is sent to a relay_domains destination because\nsuch mail typically only has recipients in one domain.\n"
},
{
"code": null,
"e": 11798,
"s": 11693,
"text": "\nThe text below provides only a parameter summary. See\npostconf(5) for more details including examples.\n"
},
{
"code": null,
"e": 11848,
"s": 11798,
"text": "/var/spool/postfix/flush, \"fast flush\" logfiles.\n"
},
{
"code": null,
"e": 12020,
"s": 11848,
"text": "smtpd(8), SMTP server\nqmgr(8), queue manager\npostconf(5), configuration parameters\nmaster(5), generic daemon options\nmaster(8), process manager\nsyslogd(8), system logging\n"
},
{
"code": null,
"e": 12055,
"s": 12022,
"text": "ETRN_README, Postfix ETRN howto\n"
},
{
"code": null,
"e": 12112,
"s": 12057,
"text": "This service was introduced with Postfix version 1.0.\n"
},
{
"code": null,
"e": 12197,
"s": 12112,
"text": "Wietse Venema\nIBM T.J. Watson Research\nP.O. Box 704\nYorktown Heights, NY 10598, USA\n"
},
{
"code": null,
"e": 12214,
"s": 12197,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 12249,
"s": 12214,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12277,
"s": 12249,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12311,
"s": 12277,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12328,
"s": 12311,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12361,
"s": 12328,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12372,
"s": 12361,
"text": " Pradeep D"
},
{
"code": null,
"e": 12407,
"s": 12372,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12423,
"s": 12407,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12456,
"s": 12423,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12468,
"s": 12456,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12500,
"s": 12468,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12508,
"s": 12500,
"text": " Uplatz"
},
{
"code": null,
"e": 12515,
"s": 12508,
"text": " Print"
},
{
"code": null,
"e": 12526,
"s": 12515,
"text": " Add Notes"
}
] |
How to set automatic delay for ToolTip in C#? - GeeksforGeeks
|
19 Jul, 2019
In Windows Forms, the ToolTip represents a tiny pop-up box which appears when you place your pointer or cursor on the control and the purpose of this control is it provides a brief description about the control present in the windows form. In ToolTip, you can set the automatic delay for the ToolTip using AutomaticDelay Property.This property allows you to set a solo delay values for the AutoPopDelay, InitialDelay, and ReshowDelay properties. Whenever the value of AutomaticDelay property, then the following values set by default:
For AutoPopDelay property: The default value is 10 times the value of AutomaticDelay property.
For InitialDelay property: The default value is equal to the value of the AutomaticDelay property.
For ReshowDelay property: The default value is 1/5 of the value of the AutomaticDelay property.
The values of these properties can also be set independently. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the value of the AutomaticDelay property as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the ToolTip from the ToolBox and drop it on the form. When you drag and drop this ToolTip on the form it will automatically add to the properties(named as ToolTip on ToolTip1) of every controls present in the current windows from.
Step 3: After drag and drop you will go to the properties of the ToolTip and set the value of the AutomaticDelay property.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the AutomaticDelay property of ToolTip programmatically with the help of given syntax:
public int AutomaticDelay { get; set; }
Here, the value of this property is of System.Int32 type and the delay is always in milliseconds. The default value of this property is 500. The following steps show how to set the AutomaticDelay property of the ToolTip dynamically:
Step 1: Create a ToolTip using the ToolTip() constructor is provided by the ToolTip class.// Creating a ToolTip
ToolTip t = new ToolTip();
// Creating a ToolTip
ToolTip t = new ToolTip();
Step 2: After creating Tooltip, set the AutomaticDelay property of the Tooltip provided by the ToolTip class.// Setting the AutomaticDelay property
t.AutomaticDelay = 600;
// Setting the AutomaticDelay property
t.AutomaticDelay = 600;
Step 3: And last add this ToolTip to the controls using SetToolTip() method. This method contains the control name and the text which you want to display in the ToolTip box.t.SetToolTip(box1, "Name should start with Capital letter");Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(140, 122); l1.Text = "Name"; // Adding this Label // control to the form this.Controls.Add(l1); // Creating and setting the // properties of the TextBox TextBox box1 = new TextBox(); box1.Location = new Point(248, 119); box1.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box1); // Creating and setting // the properties of the Label Label l2 = new Label(); l2.Location = new Point(140, 152); l2.Text = "Password"; // Adding this Label // control to the form this.Controls.Add(l2); // Creating and setting the // properties of the TextBox TextBox box2 = new TextBox(); box2.Location = new Point(248, 145); box2.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box2); // Creating and setting the // properties of the ToolTip ToolTip t = new ToolTip(); t.Active = true; t.AutoPopDelay = 4000; t.InitialDelay = 600; t.IsBalloon = true; t.ToolTipIcon = ToolTipIcon.Info; t.ToolTipTitle = "Important"; t.AutomaticDelay = 600; t.SetToolTip(box1, "Name should start with Capital letter"); t.SetToolTip(box2, "Password should be greater than 8 words"); }}}Output:
t.SetToolTip(box1, "Name should start with Capital letter");
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(140, 122); l1.Text = "Name"; // Adding this Label // control to the form this.Controls.Add(l1); // Creating and setting the // properties of the TextBox TextBox box1 = new TextBox(); box1.Location = new Point(248, 119); box1.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box1); // Creating and setting // the properties of the Label Label l2 = new Label(); l2.Location = new Point(140, 152); l2.Text = "Password"; // Adding this Label // control to the form this.Controls.Add(l2); // Creating and setting the // properties of the TextBox TextBox box2 = new TextBox(); box2.Location = new Point(248, 145); box2.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box2); // Creating and setting the // properties of the ToolTip ToolTip t = new ToolTip(); t.Active = true; t.AutoPopDelay = 4000; t.InitialDelay = 600; t.IsBalloon = true; t.ToolTipIcon = ToolTipIcon.Info; t.ToolTipTitle = "Important"; t.AutomaticDelay = 600; t.SetToolTip(box1, "Name should start with Capital letter"); t.SetToolTip(box2, "Password should be greater than 8 words"); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Abstract Classes
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Data Types
C# | Arrays
HashSet in C# with Examples
|
[
{
"code": null,
"e": 25567,
"s": 25539,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 26102,
"s": 25567,
"text": "In Windows Forms, the ToolTip represents a tiny pop-up box which appears when you place your pointer or cursor on the control and the purpose of this control is it provides a brief description about the control present in the windows form. In ToolTip, you can set the automatic delay for the ToolTip using AutomaticDelay Property.This property allows you to set a solo delay values for the AutoPopDelay, InitialDelay, and ReshowDelay properties. Whenever the value of AutomaticDelay property, then the following values set by default:"
},
{
"code": null,
"e": 26197,
"s": 26102,
"text": "For AutoPopDelay property: The default value is 10 times the value of AutomaticDelay property."
},
{
"code": null,
"e": 26296,
"s": 26197,
"text": "For InitialDelay property: The default value is equal to the value of the AutomaticDelay property."
},
{
"code": null,
"e": 26392,
"s": 26296,
"text": "For ReshowDelay property: The default value is 1/5 of the value of the AutomaticDelay property."
},
{
"code": null,
"e": 26503,
"s": 26392,
"text": "The values of these properties can also be set independently. You can set this property in two different ways:"
},
{
"code": null,
"e": 26622,
"s": 26503,
"text": "1. Design-Time: It is the easiest way to set the value of the AutomaticDelay property as shown in the following steps:"
},
{
"code": null,
"e": 26738,
"s": 26622,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 26982,
"s": 26738,
"text": "Step 2: Drag the ToolTip from the ToolBox and drop it on the form. When you drag and drop this ToolTip on the form it will automatically add to the properties(named as ToolTip on ToolTip1) of every controls present in the current windows from."
},
{
"code": null,
"e": 27112,
"s": 26982,
"text": "Step 3: After drag and drop you will go to the properties of the ToolTip and set the value of the AutomaticDelay property.Output:"
},
{
"code": null,
"e": 27120,
"s": 27112,
"text": "Output:"
},
{
"code": null,
"e": 27299,
"s": 27120,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the AutomaticDelay property of ToolTip programmatically with the help of given syntax:"
},
{
"code": null,
"e": 27339,
"s": 27299,
"text": "public int AutomaticDelay { get; set; }"
},
{
"code": null,
"e": 27572,
"s": 27339,
"text": "Here, the value of this property is of System.Int32 type and the delay is always in milliseconds. The default value of this property is 500. The following steps show how to set the AutomaticDelay property of the ToolTip dynamically:"
},
{
"code": null,
"e": 27712,
"s": 27572,
"text": "Step 1: Create a ToolTip using the ToolTip() constructor is provided by the ToolTip class.// Creating a ToolTip\nToolTip t = new ToolTip();\n"
},
{
"code": null,
"e": 27762,
"s": 27712,
"text": "// Creating a ToolTip\nToolTip t = new ToolTip();\n"
},
{
"code": null,
"e": 27935,
"s": 27762,
"text": "Step 2: After creating Tooltip, set the AutomaticDelay property of the Tooltip provided by the ToolTip class.// Setting the AutomaticDelay property\nt.AutomaticDelay = 600;\n"
},
{
"code": null,
"e": 27999,
"s": 27935,
"text": "// Setting the AutomaticDelay property\nt.AutomaticDelay = 600;\n"
},
{
"code": null,
"e": 30239,
"s": 27999,
"text": "Step 3: And last add this ToolTip to the controls using SetToolTip() method. This method contains the control name and the text which you want to display in the ToolTip box.t.SetToolTip(box1, \"Name should start with Capital letter\");Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(140, 122); l1.Text = \"Name\"; // Adding this Label // control to the form this.Controls.Add(l1); // Creating and setting the // properties of the TextBox TextBox box1 = new TextBox(); box1.Location = new Point(248, 119); box1.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box1); // Creating and setting // the properties of the Label Label l2 = new Label(); l2.Location = new Point(140, 152); l2.Text = \"Password\"; // Adding this Label // control to the form this.Controls.Add(l2); // Creating and setting the // properties of the TextBox TextBox box2 = new TextBox(); box2.Location = new Point(248, 145); box2.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box2); // Creating and setting the // properties of the ToolTip ToolTip t = new ToolTip(); t.Active = true; t.AutoPopDelay = 4000; t.InitialDelay = 600; t.IsBalloon = true; t.ToolTipIcon = ToolTipIcon.Info; t.ToolTipTitle = \"Important\"; t.AutomaticDelay = 600; t.SetToolTip(box1, \"Name should start with Capital letter\"); t.SetToolTip(box2, \"Password should be greater than 8 words\"); }}}Output:"
},
{
"code": null,
"e": 30300,
"s": 30239,
"text": "t.SetToolTip(box1, \"Name should start with Capital letter\");"
},
{
"code": null,
"e": 30309,
"s": 30300,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(140, 122); l1.Text = \"Name\"; // Adding this Label // control to the form this.Controls.Add(l1); // Creating and setting the // properties of the TextBox TextBox box1 = new TextBox(); box1.Location = new Point(248, 119); box1.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box1); // Creating and setting // the properties of the Label Label l2 = new Label(); l2.Location = new Point(140, 152); l2.Text = \"Password\"; // Adding this Label // control to the form this.Controls.Add(l2); // Creating and setting the // properties of the TextBox TextBox box2 = new TextBox(); box2.Location = new Point(248, 145); box2.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box2); // Creating and setting the // properties of the ToolTip ToolTip t = new ToolTip(); t.Active = true; t.AutoPopDelay = 4000; t.InitialDelay = 600; t.IsBalloon = true; t.ToolTipIcon = ToolTipIcon.Info; t.ToolTipTitle = \"Important\"; t.AutomaticDelay = 600; t.SetToolTip(box1, \"Name should start with Capital letter\"); t.SetToolTip(box2, \"Password should be greater than 8 words\"); }}}",
"e": 32301,
"s": 30309,
"text": null
},
{
"code": null,
"e": 32309,
"s": 32301,
"text": "Output:"
},
{
"code": null,
"e": 32312,
"s": 32309,
"text": "C#"
},
{
"code": null,
"e": 32410,
"s": 32312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32438,
"s": 32410,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 32453,
"s": 32438,
"text": "C# | Delegates"
},
{
"code": null,
"e": 32475,
"s": 32453,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 32498,
"s": 32475,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 32520,
"s": 32498,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 32560,
"s": 32520,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 32591,
"s": 32560,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 32607,
"s": 32591,
"text": "C# | Data Types"
},
{
"code": null,
"e": 32619,
"s": 32607,
"text": "C# | Arrays"
}
] |
Parsing | Set 1 (Introduction, Ambiguity and Parsers) - GeeksforGeeks
|
12 Nov, 2021
In this article, we will study various types of parses. It is one of the most important topics in Compiler from a GATE point of view. The working of various parsers will be explained from a GATE question-solving point of view. Prerequisite β basic knowledge of grammars, parse trees, ambiguity.
In the syntax analysis phase, a compiler verifies whether or not the tokens generated by the lexical analyzer are grouped according to the syntactic rules of the language. This is done by a parser. The parser obtains a string of tokens from the lexical analyzer and verifies that the string can be the grammar for the source language. It detects and reports any syntax errors and produces a parse tree from which intermediate code can be generated.
Before going to types of parsers we will discuss some ideas about some important things required for understanding parsing.
Context-Free Grammars: The syntax of a programming language is described by context-free grammar (CFG). CFG consists of a set of terminals, a set of non-terminals, a start symbol, and a set of productions. Notation β ? ? ? where ? is a is a single variable [V] ? ? (V+T)*
Ambiguity A grammar that produces more than one parse tree for some sentence is said to be ambiguous. Eg- consider a grammar S -> aS | Sa | a Now for string aaa, we will have 4 parse trees, hence ambiguous
For more information refer to quiz.geeksforgeeks.org/ambiguous-grammar/
Removing Left Recursion : A grammar is left recursive if it has a nonterminal (variable) S such that there is a derivation S -> SΞ± | Ξ² where Ξ±? (V+T)* and Ξ² ? (V+T)* (sequence of terminals and non-terminals that do not start with S) Due to the presence of left recursion some top-down parsers enter into an infinite loop so we have to eliminate left recursion. Let the productions are of the form A -> AΞ±1 | AΞ±2 | AΞ±3 | ..... | AΞ±m | Ξ²1 | Ξ²2 | .... | Ξ²n Where no Ξ²i begins with an A . then we replace the A-productions by A -> Ξ²1 Aβ | Ξ²2 Aβ | ..... | Ξ²n Aβ Aβ -> Ξ±1Aβ | Ξ±2Aβ | Ξ±3Aβ| ..... | Ξ±mAβ | Ξ΅ The nonterminal A generates the same strings as before but is no longer left recursive. Letβs look at some examples to understand better
Removing Left Factoring : A grammar is said to be left factored when it is of the form β A -> Ξ±Ξ²1 | Ξ±Ξ²2 | Ξ±Ξ²3 | ...... | Ξ±Ξ²n | Ξ³ i.e the productions start with the same terminal (or set of terminals). On seeing the input Ξ± we cannot immediately tell which production to choose to expand A. Left factoring is a grammar transformation that is useful for producing grammar suitable for predictive or top-down parsing. When the choice between two alternative A-productions is not clear, we may be able to rewrite the productions to defer the decision until enough of the input has been seen to make the right choice. For the grammar A -> Ξ±Ξ²1 | Ξ±Ξ²2 | Ξ±Ξ²3 | ...... | Ξ±Ξ²n | Ξ³ The equivalent left factored grammar will be β A -> Ξ±Aβ | Ξ³ Aβ -> Ξ²1 | Ξ²2 | Ξ²3 | ...... | Ξ²n
The process of deriving the string from the given grammar is known as derivation (parsing). Depending upon how derivation is done we have two kinds of parsers:-
Top-Down ParserBottom-Up Parser
Top-Down Parser
Bottom-Up Parser
We will be studying the parsers from the GATE point of view.
Top-Down Parser Top-down parsing attempts to build the parse tree from root to leaf. The top-down parser will start from the start symbol and proceed to the string. It follows the leftmost derivation. In leftmost derivation, the leftmost non-terminal in each sentential is always chosen.
Recursive Descent Parsing
S()
{ Choose any S production, S ->X1X2.....Xk;
for (i = 1 to k)
{
If ( Xi is a non-terminal)
Call procedure Xi();
else if ( Xi equals the current input, increment input)
Else /* error has occurred, backtrack and try another possibility */
}
}
Lets understand it better with an example
A recursive descent parsing program consists of a set of procedures, one for each nonterminal. Execution begins with the procedure for the start symbol which halts if its procedure body scans the entire input string.
Non-Recursive Predictive Parsing : This type of parsing does not require backtracking. Predictive parsers can be constructed for LL(1) grammar, the first βLβ stands for scanning the input from left to right, the second βLβ stands for leftmost derivation, and β1β for using one input symbol lookahead at each step to make parsing action decisions. Before moving on to LL(1) parsers please go through FIRST and FOLLOW https://www.geeksforgeeks.org/first-set-in-syntax-analysis/ https://www.geeksforgeeks.org/follow-set-in-syntax-analysis/
Construction of LL(1)predictive parsing table
For each production A -> Ξ± repeat following steps β Add A -> Ξ± under M[A, b] for all b in FIRST(Ξ±) If FIRST(Ξ±) contains Ξ΅ then add A -> Ξ± under M[A,c] for all c in FOLLOW(A). Size of parsing table = (No. of terminals + 1) * #variables
Eg β consider the grammar S -> (L) | a L -> SLβ Lβ -> Ξ΅ | SLβ
For any grammar if M have multiple entries than it is not LL(1) grammar Eg β S -> iEtSSβ/a Sβ ->eS/Ξ΅ E -> b
Important Notes
1. If a grammar contain left factoring then it can not be LL(1)
Eg - S -> aS | a ---- both productions go in a
2. If a grammar contain left recursion it can not be LL(1)
Eg - S -> Sa | b
S -> Sa goes to FIRST(S) = b
S -> b goes to b, thus b has 2 entries hence not LL(1)
3. If a grammar is ambiguous then it can not be LL(1)
4. Every regular grammar need not be LL(1) because
regular grammar may contain left factoring, left recursion or ambiguity.
We will discuss the Bottom-Up parser in the next article (Set 2).
This article is contributed by Parul Sharma
aaqib
komandurisrikar
jominjose
vaibhavsinghtanwar
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Construction of LL(1) Parsing Table
Types of Parsers in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Difference between Compiler and Interpreter
Peephole Optimization in Compiler Design
Recursive Descent Parser
Input Buffering in Compiler Design
Issues in the design of a code generator
Introduction to YACC
Introduction of Assembler
|
[
{
"code": null,
"e": 25342,
"s": 25314,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 25639,
"s": 25342,
"text": "In this article, we will study various types of parses. It is one of the most important topics in Compiler from a GATE point of view. The working of various parsers will be explained from a GATE question-solving point of view. Prerequisite β basic knowledge of grammars, parse trees, ambiguity. "
},
{
"code": null,
"e": 26090,
"s": 25639,
"text": "In the syntax analysis phase, a compiler verifies whether or not the tokens generated by the lexical analyzer are grouped according to the syntactic rules of the language. This is done by a parser. The parser obtains a string of tokens from the lexical analyzer and verifies that the string can be the grammar for the source language. It detects and reports any syntax errors and produces a parse tree from which intermediate code can be generated. "
},
{
"code": null,
"e": 26215,
"s": 26090,
"text": "Before going to types of parsers we will discuss some ideas about some important things required for understanding parsing. "
},
{
"code": null,
"e": 26490,
"s": 26215,
"text": "Context-Free Grammars: The syntax of a programming language is described by context-free grammar (CFG). CFG consists of a set of terminals, a set of non-terminals, a start symbol, and a set of productions. Notation β ? ? ? where ? is a is a single variable [V] ? ? (V+T)* "
},
{
"code": null,
"e": 26698,
"s": 26490,
"text": "Ambiguity A grammar that produces more than one parse tree for some sentence is said to be ambiguous. Eg- consider a grammar S -> aS | Sa | a Now for string aaa, we will have 4 parse trees, hence ambiguous "
},
{
"code": null,
"e": 26771,
"s": 26698,
"text": "For more information refer to quiz.geeksforgeeks.org/ambiguous-grammar/ "
},
{
"code": null,
"e": 27509,
"s": 26771,
"text": "Removing Left Recursion : A grammar is left recursive if it has a nonterminal (variable) S such that there is a derivation S -> SΞ± | Ξ² where Ξ±? (V+T)* and Ξ² ? (V+T)* (sequence of terminals and non-terminals that do not start with S) Due to the presence of left recursion some top-down parsers enter into an infinite loop so we have to eliminate left recursion. Let the productions are of the form A -> AΞ±1 | AΞ±2 | AΞ±3 | ..... | AΞ±m | Ξ²1 | Ξ²2 | .... | Ξ²n Where no Ξ²i begins with an A . then we replace the A-productions by A -> Ξ²1 Aβ | Ξ²2 Aβ | ..... | Ξ²n Aβ Aβ -> Ξ±1Aβ | Ξ±2Aβ | Ξ±3Aβ| ..... | Ξ±mAβ | Ξ΅ The nonterminal A generates the same strings as before but is no longer left recursive. Letβs look at some examples to understand better "
},
{
"code": null,
"e": 28272,
"s": 27509,
"text": "Removing Left Factoring : A grammar is said to be left factored when it is of the form β A -> Ξ±Ξ²1 | Ξ±Ξ²2 | Ξ±Ξ²3 | ...... | Ξ±Ξ²n | Ξ³ i.e the productions start with the same terminal (or set of terminals). On seeing the input Ξ± we cannot immediately tell which production to choose to expand A. Left factoring is a grammar transformation that is useful for producing grammar suitable for predictive or top-down parsing. When the choice between two alternative A-productions is not clear, we may be able to rewrite the productions to defer the decision until enough of the input has been seen to make the right choice. For the grammar A -> Ξ±Ξ²1 | Ξ±Ξ²2 | Ξ±Ξ²3 | ...... | Ξ±Ξ²n | Ξ³ The equivalent left factored grammar will be β A -> Ξ±Aβ | Ξ³ Aβ -> Ξ²1 | Ξ²2 | Ξ²3 | ...... | Ξ²n "
},
{
"code": null,
"e": 28435,
"s": 28272,
"text": "The process of deriving the string from the given grammar is known as derivation (parsing). Depending upon how derivation is done we have two kinds of parsers:- "
},
{
"code": null,
"e": 28467,
"s": 28435,
"text": "Top-Down ParserBottom-Up Parser"
},
{
"code": null,
"e": 28483,
"s": 28467,
"text": "Top-Down Parser"
},
{
"code": null,
"e": 28500,
"s": 28483,
"text": "Bottom-Up Parser"
},
{
"code": null,
"e": 28562,
"s": 28500,
"text": "We will be studying the parsers from the GATE point of view. "
},
{
"code": null,
"e": 28851,
"s": 28562,
"text": "Top-Down Parser Top-down parsing attempts to build the parse tree from root to leaf. The top-down parser will start from the start symbol and proceed to the string. It follows the leftmost derivation. In leftmost derivation, the leftmost non-terminal in each sentential is always chosen. "
},
{
"code": null,
"e": 28879,
"s": 28851,
"text": "Recursive Descent Parsing "
},
{
"code": null,
"e": 29185,
"s": 28879,
"text": "S()\n{ Choose any S production, S ->X1X2.....Xk;\n for (i = 1 to k)\n {\n If ( Xi is a non-terminal)\n Call procedure Xi();\n else if ( Xi equals the current input, increment input)\n Else /* error has occurred, backtrack and try another possibility */\n }\n}"
},
{
"code": null,
"e": 29229,
"s": 29185,
"text": "Lets understand it better with an example "
},
{
"code": null,
"e": 29447,
"s": 29229,
"text": "A recursive descent parsing program consists of a set of procedures, one for each nonterminal. Execution begins with the procedure for the start symbol which halts if its procedure body scans the entire input string. "
},
{
"code": null,
"e": 29985,
"s": 29447,
"text": "Non-Recursive Predictive Parsing : This type of parsing does not require backtracking. Predictive parsers can be constructed for LL(1) grammar, the first βLβ stands for scanning the input from left to right, the second βLβ stands for leftmost derivation, and β1β for using one input symbol lookahead at each step to make parsing action decisions. Before moving on to LL(1) parsers please go through FIRST and FOLLOW https://www.geeksforgeeks.org/first-set-in-syntax-analysis/ https://www.geeksforgeeks.org/follow-set-in-syntax-analysis/ "
},
{
"code": null,
"e": 30032,
"s": 29985,
"text": "Construction of LL(1)predictive parsing table "
},
{
"code": null,
"e": 30268,
"s": 30032,
"text": "For each production A -> Ξ± repeat following steps β Add A -> Ξ± under M[A, b] for all b in FIRST(Ξ±) If FIRST(Ξ±) contains Ξ΅ then add A -> Ξ± under M[A,c] for all c in FOLLOW(A). Size of parsing table = (No. of terminals + 1) * #variables "
},
{
"code": null,
"e": 30332,
"s": 30268,
"text": "Eg β consider the grammar S -> (L) | a L -> SLβ Lβ -> Ξ΅ | SLβ "
},
{
"code": null,
"e": 30443,
"s": 30334,
"text": "For any grammar if M have multiple entries than it is not LL(1) grammar Eg β S -> iEtSSβ/a Sβ ->eS/Ξ΅ E -> b "
},
{
"code": null,
"e": 30463,
"s": 30445,
"text": "Important Notes "
},
{
"code": null,
"e": 31001,
"s": 30463,
"text": " 1. If a grammar contain left factoring then it can not be LL(1)\n Eg - S -> aS | a ---- both productions go in a\n 2. If a grammar contain left recursion it can not be LL(1)\n Eg - S -> Sa | b \n S -> Sa goes to FIRST(S) = b\n S -> b goes to b, thus b has 2 entries hence not LL(1)\n 3. If a grammar is ambiguous then it can not be LL(1)\n 4. Every regular grammar need not be LL(1) because \n regular grammar may contain left factoring, left recursion or ambiguity. "
},
{
"code": null,
"e": 31070,
"s": 31003,
"text": "We will discuss the Bottom-Up parser in the next article (Set 2). "
},
{
"code": null,
"e": 31115,
"s": 31070,
"text": "This article is contributed by Parul Sharma "
},
{
"code": null,
"e": 31121,
"s": 31115,
"text": "aaqib"
},
{
"code": null,
"e": 31137,
"s": 31121,
"text": "komandurisrikar"
},
{
"code": null,
"e": 31147,
"s": 31137,
"text": "jominjose"
},
{
"code": null,
"e": 31166,
"s": 31147,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 31182,
"s": 31166,
"text": "Compiler Design"
},
{
"code": null,
"e": 31280,
"s": 31182,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31316,
"s": 31280,
"text": "Construction of LL(1) Parsing Table"
},
{
"code": null,
"e": 31352,
"s": 31316,
"text": "Types of Parsers in Compiler Design"
},
{
"code": null,
"e": 31410,
"s": 31352,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 31454,
"s": 31410,
"text": "Difference between Compiler and Interpreter"
},
{
"code": null,
"e": 31495,
"s": 31454,
"text": "Peephole Optimization in Compiler Design"
},
{
"code": null,
"e": 31520,
"s": 31495,
"text": "Recursive Descent Parser"
},
{
"code": null,
"e": 31555,
"s": 31520,
"text": "Input Buffering in Compiler Design"
},
{
"code": null,
"e": 31596,
"s": 31555,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 31617,
"s": 31596,
"text": "Introduction to YACC"
}
] |
Check if two numbers have same number of digits - GeeksforGeeks
|
10 May, 2021
Given two integers A and B, the task is to check whether both the numbers have an equal number of digits.Examples:
Input: A = 12, B = 1 Output: NoInput: A = 20, B = 99 Output: Yes
Approach: While both the numbers are > 0, keep dividing both the numbers by 10. Finally, check if both the numbers are 0. If any one of them is not 0 then they had an unequal numbers of digits.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that return true if A and B// have same number of digitsbool sameLength(int A, int B){ while (A > 0 && B > 0) { A = A / 10; B = B / 10; } // Both must be 0 now if // they had same lengths if (A == 0 && B == 0) return true; return false;} // Driver codeint main(){ int A = 21, B = 1; if (sameLength(A, B)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachimport java.io.*; class GFG{ // Function that return true if A and B// have same number of digitsstatic boolean sameLength(int A, int B){ while ((A > 0) && (B > 0)) { A = A / 10; B = B / 10; } // Both must be 0 now if // they had same lengths if ((A == 0 )&& (B == 0)) return true; return false;} // Driver codepublic static void main (String[] args){ int A = 21, B = 1; if (sameLength(A, B)) System.out.println ("Yes"); else System.out.println("No"); }} // This code is contributed by @tushil.
# Python implementation of the approach # Function that return true if A and B# have same number of digitsdef sameLength(A, B): while (A > 0 and B > 0): A = A / 10; B = B / 10; # Both must be 0 now if # they had same lengths if (A == 0 and B == 0): return True; return False; # Driver codeA = 21; B = 1; if (sameLength(A, B)): print("Yes");else: print("No"); # This code contributed by PrinciRaj1992
// C# implementation of the approachusing System; class GFG{ // Function that return true if A and B// have same number of digitsstatic bool sameLength(int A, int B){ while ((A > 0) && (B > 0)) { A = A / 10; B = B / 10; } // Both must be 0 now if // they had same lengths if ((A == 0 )&& (B == 0)) return true; return false;} // Driver codestatic public void Main (){ int A = 21, B = 1; if (sameLength(A, B)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by ajit..
<script> // Javascript implementation of the approach // Function that return true if A and B// have same number of digitsfunction sameLength(A, B){ while (A > 0 && B > 0) { A = parseInt(A / 10); B = parseInt(B / 10); } // Both must be 0 now if // they had same lengths if (A == 0 && B == 0) return true; return false;} // Driver code let A = 21, B = 1; if (sameLength(A, B)) document.write("Yes"); else document.write("No"); </script>
No
jit_t
princiraj1992
souravmahato348
number-digits
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
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Sieve of Eratosthenes
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 26563,
"s": 26535,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 26680,
"s": 26563,
"text": "Given two integers A and B, the task is to check whether both the numbers have an equal number of digits.Examples: "
},
{
"code": null,
"e": 26747,
"s": 26680,
"text": "Input: A = 12, B = 1 Output: NoInput: A = 20, B = 99 Output: Yes "
},
{
"code": null,
"e": 26993,
"s": 26747,
"text": "Approach: While both the numbers are > 0, keep dividing both the numbers by 10. Finally, check if both the numbers are 0. If any one of them is not 0 then they had an unequal numbers of digits.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26997,
"s": 26993,
"text": "C++"
},
{
"code": null,
"e": 27002,
"s": 26997,
"text": "Java"
},
{
"code": null,
"e": 27010,
"s": 27002,
"text": "Python3"
},
{
"code": null,
"e": 27013,
"s": 27010,
"text": "C#"
},
{
"code": null,
"e": 27024,
"s": 27013,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that return true if A and B// have same number of digitsbool sameLength(int A, int B){ while (A > 0 && B > 0) { A = A / 10; B = B / 10; } // Both must be 0 now if // they had same lengths if (A == 0 && B == 0) return true; return false;} // Driver codeint main(){ int A = 21, B = 1; if (sameLength(A, B)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 27536,
"s": 27024,
"text": null
},
{
"code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function that return true if A and B// have same number of digitsstatic boolean sameLength(int A, int B){ while ((A > 0) && (B > 0)) { A = A / 10; B = B / 10; } // Both must be 0 now if // they had same lengths if ((A == 0 )&& (B == 0)) return true; return false;} // Driver codepublic static void main (String[] args){ int A = 21, B = 1; if (sameLength(A, B)) System.out.println (\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by @tushil.",
"e": 28140,
"s": 27536,
"text": null
},
{
"code": " # Python implementation of the approach # Function that return true if A and B# have same number of digitsdef sameLength(A, B): while (A > 0 and B > 0): A = A / 10; B = B / 10; # Both must be 0 now if # they had same lengths if (A == 0 and B == 0): return True; return False; # Driver codeA = 21; B = 1; if (sameLength(A, B)): print(\"Yes\");else: print(\"No\"); # This code contributed by PrinciRaj1992",
"e": 28588,
"s": 28140,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that return true if A and B// have same number of digitsstatic bool sameLength(int A, int B){ while ((A > 0) && (B > 0)) { A = A / 10; B = B / 10; } // Both must be 0 now if // they had same lengths if ((A == 0 )&& (B == 0)) return true; return false;} // Driver codestatic public void Main (){ int A = 21, B = 1; if (sameLength(A, B)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by ajit..",
"e": 29181,
"s": 28588,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that return true if A and B// have same number of digitsfunction sameLength(A, B){ while (A > 0 && B > 0) { A = parseInt(A / 10); B = parseInt(B / 10); } // Both must be 0 now if // they had same lengths if (A == 0 && B == 0) return true; return false;} // Driver code let A = 21, B = 1; if (sameLength(A, B)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 29681,
"s": 29181,
"text": null
},
{
"code": null,
"e": 29684,
"s": 29681,
"text": "No"
},
{
"code": null,
"e": 29692,
"s": 29686,
"text": "jit_t"
},
{
"code": null,
"e": 29706,
"s": 29692,
"text": "princiraj1992"
},
{
"code": null,
"e": 29722,
"s": 29706,
"text": "souravmahato348"
},
{
"code": null,
"e": 29736,
"s": 29722,
"text": "number-digits"
},
{
"code": null,
"e": 29749,
"s": 29736,
"text": "Mathematical"
},
{
"code": null,
"e": 29762,
"s": 29749,
"text": "Mathematical"
},
{
"code": null,
"e": 29860,
"s": 29762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29884,
"s": 29860,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 29927,
"s": 29884,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29941,
"s": 29927,
"text": "Prime Numbers"
},
{
"code": null,
"e": 29983,
"s": 29941,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 30056,
"s": 29983,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 30078,
"s": 30056,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 30099,
"s": 30078,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 30142,
"s": 30099,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 30176,
"s": 30142,
"text": "Program for factorial of a number"
}
] |
HTTPS in Node.js - GeeksforGeeks
|
14 Oct, 2021
HTTP: When the data transfer in HTTP protocol it just travels in the clear text format. HTTPS: It simply makes encryption when the request is traveling from the browser to the web server so it is tough to sniff that information. It basically works on two things:
SSL (Secure Socket Layer)
TLS (Transport layer security)
Both of these use a PKI (Public Key Infrastructure)
If you canβt afford an SSL Certificate then the other alternative is that there are a lot of payment service that can provide you an API to integrate in your website i.e you can have your website on a non secure channel (HTTP) and whenever there is a payment then just redirect the user to that payment gateway service.
HTTPS is a separate module in Node.js and is used to communicate over a secure channel with the client. HTTPS is the HTTP protocol on top of SSL/TLS(secure HTTP protocol).
There are various advantages to this additional layer:
Integrity and Confidentiality are guaranteed, as the connection is encrypted in an asymmetric manner.
We get authentication by having keys and certificates.
An Example to setup HTTPS server with Node.Js is as follows:
We will first create an homepage.html file, this homepage.html file will have an HTML code of creating a web page i.e the page that will be displayed when the user asks for it or enter the URL of the same.
homepage.html file will also have a resource homepage.css
When the browser tries to get the resource homepage.css it will throw it to the server, the server will create a response header, so the browser knows how to parse the file.
The code shown below is written in a third file saved as .js file.
javascript
<script>(function() { // Reading and writing to files in Node.js// working with directories or file systemvar fs = require("fs"); // Responsible for creating HTTPS server// taking options for the server// options like where your certificates // and private key files are located// also take actual request and response server// code for parsing web pages from filesvar https = require("https"); // Helps with mimetypes in creating our response headervar path = require("path"); // "text/css" is added in response header // so browser knows how to handle it var mimetypes = { "css":"text/css", "html":"text/html"}; // Options is used by the servers// pfx handles the certificate filevar options = { pfx: fs.readFileSync("ssl/cert.pfx"), passphrase: "encrypted"}; var server = https.createServer(options, function(request, response) { // If the url is empty if (request.url == "" || request.url == "/") { request.url = "homepage.html"; } // __dirname is the directory where we are getting // these files from __dirname holds the file route // request.url is the index.html we made earlier // function is the callback function that holds two // parameters fs.readFile(__dirname + "/" + request.url, function(err, content) { if (err) { console.log("Error: " + err); } else { // 200 is code for OK // content-Type is the object or the content header response.writeHead(200, {'Content-Type':mimetypes[path.extname(request.url).split(".")[1]]}); response.write(content); } // This will send our response back to the browser response.end(); });}); server.listen("port number", "IP Address", function() { console.log("Server has started!");}); })();</script>
Output: Whatever the port number and IP Address is given to the server.listen it will execute that only web page whenever requested. And this web page will be an HTTPS.
kashishsoda
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Node.js Export Module
Mongoose find() Function
How to connect Node.js with React.js ?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n14 Oct, 2021"
},
{
"code": null,
"e": 26532,
"s": 26267,
"text": "HTTP: When the data transfer in HTTP protocol it just travels in the clear text format. HTTPS: It simply makes encryption when the request is traveling from the browser to the web server so it is tough to sniff that information. It basically works on two things: "
},
{
"code": null,
"e": 26558,
"s": 26532,
"text": "SSL (Secure Socket Layer)"
},
{
"code": null,
"e": 26589,
"s": 26558,
"text": "TLS (Transport layer security)"
},
{
"code": null,
"e": 26643,
"s": 26589,
"text": "Both of these use a PKI (Public Key Infrastructure) "
},
{
"code": null,
"e": 26963,
"s": 26643,
"text": "If you canβt afford an SSL Certificate then the other alternative is that there are a lot of payment service that can provide you an API to integrate in your website i.e you can have your website on a non secure channel (HTTP) and whenever there is a payment then just redirect the user to that payment gateway service."
},
{
"code": null,
"e": 27135,
"s": 26963,
"text": "HTTPS is a separate module in Node.js and is used to communicate over a secure channel with the client. HTTPS is the HTTP protocol on top of SSL/TLS(secure HTTP protocol)."
},
{
"code": null,
"e": 27192,
"s": 27135,
"text": "There are various advantages to this additional layer: "
},
{
"code": null,
"e": 27294,
"s": 27192,
"text": "Integrity and Confidentiality are guaranteed, as the connection is encrypted in an asymmetric manner."
},
{
"code": null,
"e": 27349,
"s": 27294,
"text": "We get authentication by having keys and certificates."
},
{
"code": null,
"e": 27412,
"s": 27349,
"text": "An Example to setup HTTPS server with Node.Js is as follows: "
},
{
"code": null,
"e": 27618,
"s": 27412,
"text": "We will first create an homepage.html file, this homepage.html file will have an HTML code of creating a web page i.e the page that will be displayed when the user asks for it or enter the URL of the same."
},
{
"code": null,
"e": 27676,
"s": 27618,
"text": "homepage.html file will also have a resource homepage.css"
},
{
"code": null,
"e": 27850,
"s": 27676,
"text": "When the browser tries to get the resource homepage.css it will throw it to the server, the server will create a response header, so the browser knows how to parse the file."
},
{
"code": null,
"e": 27917,
"s": 27850,
"text": "The code shown below is written in a third file saved as .js file."
},
{
"code": null,
"e": 27930,
"s": 27919,
"text": "javascript"
},
{
"code": "<script>(function() { // Reading and writing to files in Node.js// working with directories or file systemvar fs = require(\"fs\"); // Responsible for creating HTTPS server// taking options for the server// options like where your certificates // and private key files are located// also take actual request and response server// code for parsing web pages from filesvar https = require(\"https\"); // Helps with mimetypes in creating our response headervar path = require(\"path\"); // \"text/css\" is added in response header // so browser knows how to handle it var mimetypes = { \"css\":\"text/css\", \"html\":\"text/html\"}; // Options is used by the servers// pfx handles the certificate filevar options = { pfx: fs.readFileSync(\"ssl/cert.pfx\"), passphrase: \"encrypted\"}; var server = https.createServer(options, function(request, response) { // If the url is empty if (request.url == \"\" || request.url == \"/\") { request.url = \"homepage.html\"; } // __dirname is the directory where we are getting // these files from __dirname holds the file route // request.url is the index.html we made earlier // function is the callback function that holds two // parameters fs.readFile(__dirname + \"/\" + request.url, function(err, content) { if (err) { console.log(\"Error: \" + err); } else { // 200 is code for OK // content-Type is the object or the content header response.writeHead(200, {'Content-Type':mimetypes[path.extname(request.url).split(\".\")[1]]}); response.write(content); } // This will send our response back to the browser response.end(); });}); server.listen(\"port number\", \"IP Address\", function() { console.log(\"Server has started!\");}); })();</script>",
"e": 29793,
"s": 27930,
"text": null
},
{
"code": null,
"e": 29963,
"s": 29793,
"text": "Output: Whatever the port number and IP Address is given to the server.listen it will execute that only web page whenever requested. And this web page will be an HTTPS. "
},
{
"code": null,
"e": 29975,
"s": 29963,
"text": "kashishsoda"
},
{
"code": null,
"e": 29982,
"s": 29975,
"text": "Picked"
},
{
"code": null,
"e": 29990,
"s": 29982,
"text": "Node.js"
},
{
"code": null,
"e": 30007,
"s": 29990,
"text": "Web Technologies"
},
{
"code": null,
"e": 30105,
"s": 30007,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30175,
"s": 30105,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 30202,
"s": 30175,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 30224,
"s": 30202,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 30249,
"s": 30224,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 30288,
"s": 30249,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 30328,
"s": 30288,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30373,
"s": 30328,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30416,
"s": 30373,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30466,
"s": 30416,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
COUNTIF Function in Excel with Examples - GeeksforGeeks
|
09 May, 2021
COUNTIF function in excel is used to count the number of cells that match a single condition applied. It can include Dates, Numbers, and Texts. It uses various logical operators like <(Less Than), >(Greater Than), >=(Greater Than or Equal to), <=(Less Than or Equal to), =(Equals to), and <>(NOT) for matching the condition. It also uses some wildcard like * and ? for partial matching.
COUNTIF function in excel is used to count the number of cells.
Syntax: COUNTIF ( range, criteria)
Arguments:
1. range:- Here ranges refers to the range of cells for which you want the cell count for
a specific condition.
2. criteria:- Here criteria refers to the condition for which you want the cell count.
Return Value: COUNTIF function in excel returns an integer value of the number of cells
which satisfy the given condition.
Example 1:
Consider the studentβs marks which are given below for and XYZ examination.
Understanding the arguments of the COUNTIF function in Excel
Understanding the argument of the COUNTIF function in Excel
Output:
Note: RED color cells are used for the reference that which cells would satisfy the given criteria. RED color doesnβt come in the output of COUNTIF.
The output of the marks of the students having greater than 80
Example 2:
Examples 3:
Some of the other examples are as follows for the COUNTIF function in excel.
We can find out that how many blank cells are there in the given range and also we can find out which are not blank cells in the given range.
For finding number of Blank cells: = COUNTIF ( D1:D10, ββ )
For finding a number of not Blank cells: = COUNTIF ( D1:D10, β<>β)
We can use the COUNTIF criteria using the value from another cell using concatenation. In the below example it COUNTIF function will return the value which is equal to the cell E5. Here & is used for the concatenation.
= COUNTIF ( D1:D10, "=" & E5)
We can use the COUNTIF function with the DATE function also for finding the dates less than or more than the given DATE. The below example shows how to use the COUNTIF function with the DATE function. It will return some dates that are greater than 1-Jan-2021.
= COUNTIF ( D1:D10, ">" & DATE( 2021, 1, 1) )
COUNTIF is not case sensitive.
COUNTIF will only check one condition at a time.
COUNTIF needs a range for the evaluation.
In COUNTIF the criteria must be enclosed in the double-quotes.
If the criteria are evaluated from a different cell then that cell must not be enclosed in the double-quotes. E.g. β=β & E5
It gives an error if the matching string exceeds 255 characters.
Picked
SQL-Query
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Use Solver in Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Find the Last Used Row and Column in Excel VBA?
How to Sum Values Based on Criteria in Another Column in Excel?
How to Get Length of Array in Excel VBA?
How to Read Data From Text File in Excel VBA?
How to Show Percentages in Stacked Column Chart in Excel?
How to Check if the Number is Prime Number in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
|
[
{
"code": null,
"e": 24884,
"s": 24856,
"text": "\n09 May, 2021"
},
{
"code": null,
"e": 25271,
"s": 24884,
"text": "COUNTIF function in excel is used to count the number of cells that match a single condition applied. It can include Dates, Numbers, and Texts. It uses various logical operators like <(Less Than), >(Greater Than), >=(Greater Than or Equal to), <=(Less Than or Equal to), =(Equals to), and <>(NOT) for matching the condition. It also uses some wildcard like * and ? for partial matching."
},
{
"code": null,
"e": 25335,
"s": 25271,
"text": "COUNTIF function in excel is used to count the number of cells."
},
{
"code": null,
"e": 25731,
"s": 25335,
"text": "Syntax: COUNTIF ( range, criteria)\n\nArguments:\n1. range:- Here ranges refers to the range of cells for which you want the cell count for\n a specific condition.\n2. criteria:- Here criteria refers to the condition for which you want the cell count.\n\nReturn Value: COUNTIF function in excel returns an integer value of the number of cells\n which satisfy the given condition."
},
{
"code": null,
"e": 25742,
"s": 25731,
"text": "Example 1:"
},
{
"code": null,
"e": 25818,
"s": 25742,
"text": "Consider the studentβs marks which are given below for and XYZ examination."
},
{
"code": null,
"e": 25879,
"s": 25818,
"text": "Understanding the arguments of the COUNTIF function in Excel"
},
{
"code": null,
"e": 25939,
"s": 25879,
"text": "Understanding the argument of the COUNTIF function in Excel"
},
{
"code": null,
"e": 25947,
"s": 25939,
"text": "Output:"
},
{
"code": null,
"e": 26096,
"s": 25947,
"text": "Note: RED color cells are used for the reference that which cells would satisfy the given criteria. RED color doesnβt come in the output of COUNTIF."
},
{
"code": null,
"e": 26159,
"s": 26096,
"text": "The output of the marks of the students having greater than 80"
},
{
"code": null,
"e": 26170,
"s": 26159,
"text": "Example 2:"
},
{
"code": null,
"e": 26182,
"s": 26170,
"text": "Examples 3:"
},
{
"code": null,
"e": 26259,
"s": 26182,
"text": "Some of the other examples are as follows for the COUNTIF function in excel."
},
{
"code": null,
"e": 26401,
"s": 26259,
"text": "We can find out that how many blank cells are there in the given range and also we can find out which are not blank cells in the given range."
},
{
"code": null,
"e": 26463,
"s": 26401,
"text": "For finding number of Blank cells: = COUNTIF ( D1:D10, ββ )"
},
{
"code": null,
"e": 26530,
"s": 26463,
"text": "For finding a number of not Blank cells: = COUNTIF ( D1:D10, β<>β)"
},
{
"code": null,
"e": 26749,
"s": 26530,
"text": "We can use the COUNTIF criteria using the value from another cell using concatenation. In the below example it COUNTIF function will return the value which is equal to the cell E5. Here & is used for the concatenation."
},
{
"code": null,
"e": 26779,
"s": 26749,
"text": "= COUNTIF ( D1:D10, \"=\" & E5)"
},
{
"code": null,
"e": 27040,
"s": 26779,
"text": "We can use the COUNTIF function with the DATE function also for finding the dates less than or more than the given DATE. The below example shows how to use the COUNTIF function with the DATE function. It will return some dates that are greater than 1-Jan-2021."
},
{
"code": null,
"e": 27086,
"s": 27040,
"text": "= COUNTIF ( D1:D10, \">\" & DATE( 2021, 1, 1) )"
},
{
"code": null,
"e": 27117,
"s": 27086,
"text": "COUNTIF is not case sensitive."
},
{
"code": null,
"e": 27166,
"s": 27117,
"text": "COUNTIF will only check one condition at a time."
},
{
"code": null,
"e": 27208,
"s": 27166,
"text": "COUNTIF needs a range for the evaluation."
},
{
"code": null,
"e": 27271,
"s": 27208,
"text": "In COUNTIF the criteria must be enclosed in the double-quotes."
},
{
"code": null,
"e": 27395,
"s": 27271,
"text": "If the criteria are evaluated from a different cell then that cell must not be enclosed in the double-quotes. E.g. β=β & E5"
},
{
"code": null,
"e": 27460,
"s": 27395,
"text": "It gives an error if the matching string exceeds 255 characters."
},
{
"code": null,
"e": 27473,
"s": 27466,
"text": "Picked"
},
{
"code": null,
"e": 27483,
"s": 27473,
"text": "SQL-Query"
},
{
"code": null,
"e": 27489,
"s": 27483,
"text": "Excel"
},
{
"code": null,
"e": 27587,
"s": 27489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27596,
"s": 27587,
"text": "Comments"
},
{
"code": null,
"e": 27609,
"s": 27596,
"text": "Old Comments"
},
{
"code": null,
"e": 27637,
"s": 27609,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 27671,
"s": 27637,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 27687,
"s": 27671,
"text": "Macros in Excel"
},
{
"code": null,
"e": 27742,
"s": 27687,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 27806,
"s": 27742,
"text": "How to Sum Values Based on Criteria in Another Column in Excel?"
},
{
"code": null,
"e": 27847,
"s": 27806,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 27893,
"s": 27847,
"text": "How to Read Data From Text File in Excel VBA?"
},
{
"code": null,
"e": 27951,
"s": 27893,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 28004,
"s": 27951,
"text": "How to Check if the Number is Prime Number in Excel?"
}
] |
The Kalman Filter: An algorithm for making sense of fused sensor insight | by Sharath Srinivasan | Towards Data Science
|
Youβre driving your car through a tunnel. The GPS signal is gone. Nevertheless, you might want to get notified that you should take the exit in the tunnel. How should we navigate on a car inside a tunnel, which should know where it is right now given only the last position?
Global Positioning System receivers calculate their locations by analyzing signals that they receive from satellites. These signals donβt pass through solid objects. A GPS in a vehicle may have an external antenna, or it may pick up enough of bounced signal out of the air to operate. If signals in a tunnel are too weak, the GPS may still function, depending on its quality and features.
An approach that merges the vehicle sensors, can calculate the position .
Assume that we were at the tunnel entrance and we were driving at 50km / h, then the navigation can indeed be calculated exactly where (x = position) we would be 1 minute (t = time) later.
Both the sensors have random errors, the transmission path has interference, and the resolution of CAN bus or analog-to-digital converters can cause many inaccuracies in the simple statement βspeedβ.
For example, a speed signal looks like this:
On average, the measured speed has some βnoiseβ added to it which differentiates them from the ground truth. If one calculates a histogram of the determined speeds, one sees that the determined values ββare approximately subject to a normal distribution.
So there is one, and really only one, maximum value (unimodal) and a spread (variance). If this is the case, we can do the calculation very well with a trick nevertheless.
I would like to first explain the idea of ββthe Kalman filter (according to Rudolf Emil Kalman ) with only one dimension . The following explanation is borrowed from the Udacity CS373 course by Prof. Sebastian Thrun.
In order to perform the calculation optimally despite measurement noise, the βhow strongβ parameter must be known. This βhow strongβ is expressed with the variance of the normal distribution. This is determined once for a sensor that is being used and then uses only this βuncertaintyβ for the calculation.
In the following, it is no longer calculated with absolute values ββbut with mean values ββ(ΞΌ) and variances Ο 2 of the normal distribution. The mean of the normal distribution is the value that we would want to calculate. The variance indicates how confidence level. The narrower the normal distribution (low variance), the confident the sensors are with the measurements.
A sensor that measures 100% exactly has a variance of Ο 2= 0 (it does not exist).
Letβs assume that the GPS signal has just been lost and the navigation system is completely unclear where you are. The variance is high, the curve corresponding is really flat. There is an uncertainty.
Normal distribution with variance = 20 and mean = 0
Now comes a speed measurement from the sensor, which is also βinaccurateβ with appropriate variance. These two uncertainties must now be linked together. With the help of Bayes rule, the addition of two Gaussian function is performed . Prof. Thrun explains this very clearly in the Udacity CS373 course.
The two pieces of information (one for the current position and one for the measurement uncertainty of the sensor) actually gives a better result!. The narrower the normal distribution, the confident the result. Movement worsens the estimate.
Of course, the vehicle also moves, which adversely affects the accuracy of the position determination. A sensor, for example, can determine the rotation of the wheel and make the assumption of the radius of the wheel and could have a conclusion on the distance traveled, but this will always remain somewhat inaccurate. This inaccuracy of movement is also described with a normal distribution. Computing with the current estimate runs a little differently this time, because the βmovementβ can also be called βPredictionβ. You can estimate after the calculation, where you will be next (measurement) time.
In our example, ΞΌ is simply v * dt, which is the distance we had traveled in the calculation time.
A simple implementation of this is:
def predict(mean1, var1, mean2, var2): new_mean = mean1 +mean2 new_var = var1 + var2 return [new_mean, new_var]
The Kalman filter simply calculates these two functions over and over again.
The filter cyclically overrides the mean and the variance of the result. The filter will always be confident on where it is, as long as the readings do not deviate too much from the predicted value.
A new measurement improves the estimate
Since the measured values ββ(in update) fit relatively well to the predicted ones (by predict), the filter improves step by step to ensure that it is correct (normal distributions become narrower and higher), even though the values ββare noisy.
def update(mean1, var1, mean2, var2): sum = var1+var2 pr_s = mean1*var2 + mean2*var1 #print(pr_s) new_mean =1/(sum) * pr_s product = var1*var2 new_var = product/sum return [new_mean, new_var]
Without matrices, you can only count in one dimension, which is insufficient for...
I would like to explain the procedure again using the example of a vehicle with navigation device, which enters a tunnel. The last known position is before losing the GPS signal. Afterwards only the speed information of the vehicle (wheel speeds & yaw rate) is available as a normal distributed noisy measured variable. From here, the velocity is calculated.
We now turn to the more complicated part. The procedure mentioned with multiplying or adding the mean values ββand variances thus only works in the one-dimensional case. In the multi-dimensional problem, we would have the mean and the variance inside a matrix on which all the operations are performed.That is, when the state you want to measure can be fully described with just one variable. The example, which was mentioned at the beginning, to determine the position of a vehicle in the tunnel, can no longer be completely described with a variable. Although only interested in the position, but this is already a two dimensional problem in the plane. In addition, only the velocity can be measured, not the position directly. This results in a Kalman filter with the following state variables.
At the beginning we will have to initialize with an initial state. In the one dimensional case the state was a vector.
If nothing is known, you can simply enter zero here. If some boundary conditions are already known, they can be communicated to the filter. The choice of the following covariance matrix controls how fast the filter converges to the correct (measured) values
An uncertainty must be given for the initial state . In the one-dimensional case, the variance was a vector, but now is matrix of uncertainty for all states. Here is an example with for all the four states.
This matrix is ββmost likely to be changed during the filter passes. It is changed in both the predict and correct steps. The Matrices can be initialized on the basis of the sensor accuracy. If the sensor is very accurate, small values ββshould be used here. If the sensor is relatively inaccurate, large values ββshould be used here to allow the filter to converge relatively quickly. If the sensor is very accurate, small values ββshould be used here.
The core of the filter, however, is the following definition, which we should set up with great understanding of the physical context. This is not easy for many real problems. For our simple example (in-plane motion), the physics behind it comes from the smooth motion. For the state matrix shown above, the dynamics in matrix notation is as follows:
This states βwhereβ the state vector moves from one calculation step to the next within. This dynamic model is in our case is βconstant velocityβ model because it assumes that the velocity remains constant during a filterβs calculation step(dt).
This simply reflects physical relationships for the uniform motion. A higher form would be the Constant Acceleration model, which would be a 6-D filter and still includes the accelerations in the state vector. In principle, other dynamics can be specified here.
As the movement of the vehicle (in the sense of a superimposed, normally distributed noise) may also be disturbed, this is where the process noise co-variance matrix is introduced. This matrix tells us about the filter , and how the system state can βjumpβ from one step to the next. Imagine the vehicle that drives autonomously. It can be disturbed by a gust of wind or road bumps, which has a force effect. A speed change by the driver is also an acceleration that acts on the vehicle. If an acceleration now affects the system state , then the physical dependence for it is Q. The matrix is a co-variance matrix containing the following elements:
It is easy to calculate by placing the vector and then multiplying it by the assumed standard deviation for the acceleration.
An external control variables (eg: steering, braking, acceleration, etc.) is possible via the control matrix . The u matrix will contain the robotic input of the system which could be the instantaneous acceleration or the distance traveled by the system from a IMU or a odometer sensor.
The filter must also be told what is measured and how it relates to the state vector. In the example of the vehicle, the car enters a tunnel with only position measured at first point, only the speed is measured! The values ββcan be measured directly with the factor 1.0 (ie the velocity is measured directly in the correct unit), which is why in only 1.0 is set to the appropriate position.
If the sensors measure in a different unit or the size by detours, the relationships in the measuring matrix must be mapped in a formula.
As in the one-dimensional case the variance, a measurement uncertainty must also be stated here.
This measurement uncertainty indicates how much one trusts the measured values ββof the sensors. Since we measure the position and the velocity , this is a 2 Γ 2 matrix. If the sensor is very accurate, small values ββshould be used here. If the sensor is relatively inaccurate, large values ββshould be used here.
Last but not least, a unit matrix is ββnecessary, which would be used to simplify the Kalman equations.
This part of the Kalman filter now dares to predict the state of the system in the future. In addition, under certain conditions, a state can be calculated with it which cannot be measured! Thatβs amazing, but in our case exactly what we need. We cannot measure the position of the vehicle because the GPS of the navigation device has no reception in a tunnel. By initializing the state vector with a position and measuring the velocity, however, the dynamics still be used to make an optimal prediction about the position.
The co-variance must also be recalculated. Uncertainty about the state of the system increases in the predict step, as we have seen in the one dimension case. In the multidimensional case, the measurement uncertainty is added, so the uncertainty becomes larger and larger.
P=Aβ
Pβ
Aβ+Q
Thatβs it. The Kalman filter has made a prediction statement about the expected system state in the future or in the upcoming time-step. The filter will now be measuring / correcting and checking whether the prediction of the system state fits well with the new measurements.
The co-variance chosen to be smaller by the filter illustrates the certainty, if not, then something is wrong, which makes the filter more uncertain.
Note : The following mathematical calculations do not need to be derived.
From the sensors come current measured values, with which an innovation factor (y) is obtained by using the measurements ,the state vector with the measuring matrix .
y=Zβ(Hβ
x)
Then it is looks at with which variance can be further calculated. For this, the uncertainty and the measurement matrix and the measurement uncertainty required.
S=(Hβ
Pβ
Hβ²+R)
This determines the so-called Kalman gain. It states whether the readings or system dynamics should be more familiar.
K= Pβ
HβS
The Kalman Gain will decrease if the readings (measurements) match the predicted system state. If the measured values ββsay otherwise, the elements of matrix K become larger.
This information is now used to update the system state.
x = x + ( Kβ
y )
And also determined a new co-variance for the upcoming predict step.
P= P- ( Kβ
H.P)
which is ,
P= ( I- ( Kβ
H) ) β
P
Now itβs back to the step prediction. Graphically it looks like this:
This filter runs permanently as long as measured values ββcome in. It can also be open loop, so only the prediction step will be executed if no measurements are available. Then the uncertainty gets bigger and bigger.
When we drive into a tunnel , the last known position is recorded which is received from the GPS. The Kalman filter can still predict the position of the vehicle, although it is not being measured at all time.
Now assuming the vehicle speed is available about every 20 m/s via the CAN bus, 6 iterations are only 0.1 s. The filter converges relatively quickly, depending on the choice of initial conditions. For example, after 100 iterations (equivalent to 2s on the vehicle), the variance is already very low, so the filter is confident on its estimated and updates states. My implementation of the linear Kalman filter could be found here . The results are :
def Kalman_Filter() : for n in range(measurements): x = A*x+B*u[n] P = A*P*A.T + Q # Measurement Update (Correction) # =============================== # Compute the Kalman Gain S = H*P*H.T + R K = (P*H.T) * np.linalg.pinv(S)# Update the estimate via z Z = mx[n] y = Z β (H*x) # Innovation or Residual x = x + (K*y) # Update the error covariance P = (I β (K*H))*P
Overall, no matter how large the numerical values are, but rather in what proportion they are. If the values chosen are ten times larger, this will hardly affect the filter. The ratio of values ββis crucial. The correct choice would be directly responsible for the filter performance and form the basic question of filter design.
This either / or question can only be decided on an application-specific basis. In some cases:
We would just want to filter poorly measuring sensors for a relatively constant process. For example, we can implement kalman filter to optimize temperature controller in a furnace in a rocket or in chemical furnace.We would also want to merge several sensors and the dynamics should be preserved. Accordingly, the matrices should be selected. Alternatively, of course, the filter can be designed to adapt automatically during operation.
We would just want to filter poorly measuring sensors for a relatively constant process. For example, we can implement kalman filter to optimize temperature controller in a furnace in a rocket or in chemical furnace.
We would also want to merge several sensors and the dynamics should be preserved. Accordingly, the matrices should be selected. Alternatively, of course, the filter can be designed to adapt automatically during operation.
Kalman Filter works on prediction-correction model used for linear and time-variant or time-invariant systems. Prediction model involves the actual system and the process noise .The update model involves updating the predicated or the estimated value with the observation noise. Kalman gain is calculated based on RLS algorithm in order to reach the optimal value within less amount of time.
Recursive Least Squares is based on weighted least squares in which previous values taken in account for determining the future value. Each weight is exponentially assigned to each previous value of the actual system. The weights are updated recursively based on memory.
Notable Differences:
RLS is faster than Kalman Filter.Accuracy of Kalman Filter is high.Kalman Filter is based on State-Space model where we need to model entire system to achieve optimal value.
RLS is faster than Kalman Filter.
Accuracy of Kalman Filter is high.
Kalman Filter is based on State-Space model where we need to model entire system to achieve optimal value.
Polynomial regression is a method of function approximation. We have a data set and we have to determine the functional relationship, which is often expressed by estimating the probability density p(z|x). Under the assumption that this probability is a Gaussian, we get the least squares solution as a maximum likelihood estimator.
Since Linear dynamic systems are state space models, we assume that the data we observe is generated by the application of a linear transform. The model we come with is the probability of a time series. The process then predicts the next value of a time series.
Polynomial regression does function approximation, Kalman filtering does time series prediction.
The time series prediction is a special case of function approximation. Both the models are modeled from different assumptions on the data they observe.
The Kalman filter is relatively quick and easy to implement and provides an optimal estimate of the condition for normally distributed noisy sensor values ββunder certain conditions. Mr. Kalman was so convinced of his algorithm that he was able to inspire a friendly engineer at NASA. And so this filter helped for the first time in the Apollo Guidance Computer at the moon landings .
The Jupyter Notebook Collection of Roger Labbe.The amazing video series of Michel van BiezenKalman Filters in Pictures .The the blog post of Vivek Yadav .The amazing post by David Silver.
The Jupyter Notebook Collection of Roger Labbe.
The amazing video series of Michel van Biezen
Kalman Filters in Pictures .
The the blog post of Vivek Yadav .
The amazing post by David Silver.
|
[
{
"code": null,
"e": 447,
"s": 172,
"text": "Youβre driving your car through a tunnel. The GPS signal is gone. Nevertheless, you might want to get notified that you should take the exit in the tunnel. How should we navigate on a car inside a tunnel, which should know where it is right now given only the last position?"
},
{
"code": null,
"e": 836,
"s": 447,
"text": "Global Positioning System receivers calculate their locations by analyzing signals that they receive from satellites. These signals donβt pass through solid objects. A GPS in a vehicle may have an external antenna, or it may pick up enough of bounced signal out of the air to operate. If signals in a tunnel are too weak, the GPS may still function, depending on its quality and features."
},
{
"code": null,
"e": 910,
"s": 836,
"text": "An approach that merges the vehicle sensors, can calculate the position ."
},
{
"code": null,
"e": 1099,
"s": 910,
"text": "Assume that we were at the tunnel entrance and we were driving at 50km / h, then the navigation can indeed be calculated exactly where (x = position) we would be 1 minute (t = time) later."
},
{
"code": null,
"e": 1299,
"s": 1099,
"text": "Both the sensors have random errors, the transmission path has interference, and the resolution of CAN bus or analog-to-digital converters can cause many inaccuracies in the simple statement βspeedβ."
},
{
"code": null,
"e": 1344,
"s": 1299,
"text": "For example, a speed signal looks like this:"
},
{
"code": null,
"e": 1599,
"s": 1344,
"text": "On average, the measured speed has some βnoiseβ added to it which differentiates them from the ground truth. If one calculates a histogram of the determined speeds, one sees that the determined values ββare approximately subject to a normal distribution."
},
{
"code": null,
"e": 1771,
"s": 1599,
"text": "So there is one, and really only one, maximum value (unimodal) and a spread (variance). If this is the case, we can do the calculation very well with a trick nevertheless."
},
{
"code": null,
"e": 1988,
"s": 1771,
"text": "I would like to first explain the idea of ββthe Kalman filter (according to Rudolf Emil Kalman ) with only one dimension . The following explanation is borrowed from the Udacity CS373 course by Prof. Sebastian Thrun."
},
{
"code": null,
"e": 2295,
"s": 1988,
"text": "In order to perform the calculation optimally despite measurement noise, the βhow strongβ parameter must be known. This βhow strongβ is expressed with the variance of the normal distribution. This is determined once for a sensor that is being used and then uses only this βuncertaintyβ for the calculation."
},
{
"code": null,
"e": 2669,
"s": 2295,
"text": "In the following, it is no longer calculated with absolute values ββbut with mean values ββ(ΞΌ) and variances Ο 2 of the normal distribution. The mean of the normal distribution is the value that we would want to calculate. The variance indicates how confidence level. The narrower the normal distribution (low variance), the confident the sensors are with the measurements."
},
{
"code": null,
"e": 2751,
"s": 2669,
"text": "A sensor that measures 100% exactly has a variance of Ο 2= 0 (it does not exist)."
},
{
"code": null,
"e": 2953,
"s": 2751,
"text": "Letβs assume that the GPS signal has just been lost and the navigation system is completely unclear where you are. The variance is high, the curve corresponding is really flat. There is an uncertainty."
},
{
"code": null,
"e": 3005,
"s": 2953,
"text": "Normal distribution with variance = 20 and mean = 0"
},
{
"code": null,
"e": 3309,
"s": 3005,
"text": "Now comes a speed measurement from the sensor, which is also βinaccurateβ with appropriate variance. These two uncertainties must now be linked together. With the help of Bayes rule, the addition of two Gaussian function is performed . Prof. Thrun explains this very clearly in the Udacity CS373 course."
},
{
"code": null,
"e": 3552,
"s": 3309,
"text": "The two pieces of information (one for the current position and one for the measurement uncertainty of the sensor) actually gives a better result!. The narrower the normal distribution, the confident the result. Movement worsens the estimate."
},
{
"code": null,
"e": 4158,
"s": 3552,
"text": "Of course, the vehicle also moves, which adversely affects the accuracy of the position determination. A sensor, for example, can determine the rotation of the wheel and make the assumption of the radius of the wheel and could have a conclusion on the distance traveled, but this will always remain somewhat inaccurate. This inaccuracy of movement is also described with a normal distribution. Computing with the current estimate runs a little differently this time, because the βmovementβ can also be called βPredictionβ. You can estimate after the calculation, where you will be next (measurement) time."
},
{
"code": null,
"e": 4257,
"s": 4158,
"text": "In our example, ΞΌ is simply v * dt, which is the distance we had traveled in the calculation time."
},
{
"code": null,
"e": 4293,
"s": 4257,
"text": "A simple implementation of this is:"
},
{
"code": null,
"e": 4405,
"s": 4293,
"text": "def predict(mean1, var1, mean2, var2): new_mean = mean1 +mean2 new_var = var1 + var2 return [new_mean, new_var]"
},
{
"code": null,
"e": 4482,
"s": 4405,
"text": "The Kalman filter simply calculates these two functions over and over again."
},
{
"code": null,
"e": 4681,
"s": 4482,
"text": "The filter cyclically overrides the mean and the variance of the result. The filter will always be confident on where it is, as long as the readings do not deviate too much from the predicted value."
},
{
"code": null,
"e": 4721,
"s": 4681,
"text": "A new measurement improves the estimate"
},
{
"code": null,
"e": 4966,
"s": 4721,
"text": "Since the measured values ββ(in update) fit relatively well to the predicted ones (by predict), the filter improves step by step to ensure that it is correct (normal distributions become narrower and higher), even though the values ββare noisy."
},
{
"code": null,
"e": 5159,
"s": 4966,
"text": "def update(mean1, var1, mean2, var2): sum = var1+var2 pr_s = mean1*var2 + mean2*var1 #print(pr_s) new_mean =1/(sum) * pr_s product = var1*var2 new_var = product/sum return [new_mean, new_var]"
},
{
"code": null,
"e": 5243,
"s": 5159,
"text": "Without matrices, you can only count in one dimension, which is insufficient for..."
},
{
"code": null,
"e": 5602,
"s": 5243,
"text": "I would like to explain the procedure again using the example of a vehicle with navigation device, which enters a tunnel. The last known position is before losing the GPS signal. Afterwards only the speed information of the vehicle (wheel speeds & yaw rate) is available as a normal distributed noisy measured variable. From here, the velocity is calculated."
},
{
"code": null,
"e": 6400,
"s": 5602,
"text": "We now turn to the more complicated part. The procedure mentioned with multiplying or adding the mean values ββand variances thus only works in the one-dimensional case. In the multi-dimensional problem, we would have the mean and the variance inside a matrix on which all the operations are performed.That is, when the state you want to measure can be fully described with just one variable. The example, which was mentioned at the beginning, to determine the position of a vehicle in the tunnel, can no longer be completely described with a variable. Although only interested in the position, but this is already a two dimensional problem in the plane. In addition, only the velocity can be measured, not the position directly. This results in a Kalman filter with the following state variables."
},
{
"code": null,
"e": 6519,
"s": 6400,
"text": "At the beginning we will have to initialize with an initial state. In the one dimensional case the state was a vector."
},
{
"code": null,
"e": 6777,
"s": 6519,
"text": "If nothing is known, you can simply enter zero here. If some boundary conditions are already known, they can be communicated to the filter. The choice of the following covariance matrix controls how fast the filter converges to the correct (measured) values"
},
{
"code": null,
"e": 6984,
"s": 6777,
"text": "An uncertainty must be given for the initial state . In the one-dimensional case, the variance was a vector, but now is matrix of uncertainty for all states. Here is an example with for all the four states."
},
{
"code": null,
"e": 7438,
"s": 6984,
"text": "This matrix is ββmost likely to be changed during the filter passes. It is changed in both the predict and correct steps. The Matrices can be initialized on the basis of the sensor accuracy. If the sensor is very accurate, small values ββshould be used here. If the sensor is relatively inaccurate, large values ββshould be used here to allow the filter to converge relatively quickly. If the sensor is very accurate, small values ββshould be used here."
},
{
"code": null,
"e": 7789,
"s": 7438,
"text": "The core of the filter, however, is the following definition, which we should set up with great understanding of the physical context. This is not easy for many real problems. For our simple example (in-plane motion), the physics behind it comes from the smooth motion. For the state matrix shown above, the dynamics in matrix notation is as follows:"
},
{
"code": null,
"e": 8035,
"s": 7789,
"text": "This states βwhereβ the state vector moves from one calculation step to the next within. This dynamic model is in our case is βconstant velocityβ model because it assumes that the velocity remains constant during a filterβs calculation step(dt)."
},
{
"code": null,
"e": 8297,
"s": 8035,
"text": "This simply reflects physical relationships for the uniform motion. A higher form would be the Constant Acceleration model, which would be a 6-D filter and still includes the accelerations in the state vector. In principle, other dynamics can be specified here."
},
{
"code": null,
"e": 8947,
"s": 8297,
"text": "As the movement of the vehicle (in the sense of a superimposed, normally distributed noise) may also be disturbed, this is where the process noise co-variance matrix is introduced. This matrix tells us about the filter , and how the system state can βjumpβ from one step to the next. Imagine the vehicle that drives autonomously. It can be disturbed by a gust of wind or road bumps, which has a force effect. A speed change by the driver is also an acceleration that acts on the vehicle. If an acceleration now affects the system state , then the physical dependence for it is Q. The matrix is a co-variance matrix containing the following elements:"
},
{
"code": null,
"e": 9073,
"s": 8947,
"text": "It is easy to calculate by placing the vector and then multiplying it by the assumed standard deviation for the acceleration."
},
{
"code": null,
"e": 9360,
"s": 9073,
"text": "An external control variables (eg: steering, braking, acceleration, etc.) is possible via the control matrix . The u matrix will contain the robotic input of the system which could be the instantaneous acceleration or the distance traveled by the system from a IMU or a odometer sensor."
},
{
"code": null,
"e": 9752,
"s": 9360,
"text": "The filter must also be told what is measured and how it relates to the state vector. In the example of the vehicle, the car enters a tunnel with only position measured at first point, only the speed is measured! The values ββcan be measured directly with the factor 1.0 (ie the velocity is measured directly in the correct unit), which is why in only 1.0 is set to the appropriate position."
},
{
"code": null,
"e": 9890,
"s": 9752,
"text": "If the sensors measure in a different unit or the size by detours, the relationships in the measuring matrix must be mapped in a formula."
},
{
"code": null,
"e": 9987,
"s": 9890,
"text": "As in the one-dimensional case the variance, a measurement uncertainty must also be stated here."
},
{
"code": null,
"e": 10301,
"s": 9987,
"text": "This measurement uncertainty indicates how much one trusts the measured values ββof the sensors. Since we measure the position and the velocity , this is a 2 Γ 2 matrix. If the sensor is very accurate, small values ββshould be used here. If the sensor is relatively inaccurate, large values ββshould be used here."
},
{
"code": null,
"e": 10405,
"s": 10301,
"text": "Last but not least, a unit matrix is ββnecessary, which would be used to simplify the Kalman equations."
},
{
"code": null,
"e": 10929,
"s": 10405,
"text": "This part of the Kalman filter now dares to predict the state of the system in the future. In addition, under certain conditions, a state can be calculated with it which cannot be measured! Thatβs amazing, but in our case exactly what we need. We cannot measure the position of the vehicle because the GPS of the navigation device has no reception in a tunnel. By initializing the state vector with a position and measuring the velocity, however, the dynamics still be used to make an optimal prediction about the position."
},
{
"code": null,
"e": 11202,
"s": 10929,
"text": "The co-variance must also be recalculated. Uncertainty about the state of the system increases in the predict step, as we have seen in the one dimension case. In the multidimensional case, the measurement uncertainty is added, so the uncertainty becomes larger and larger."
},
{
"code": null,
"e": 11213,
"s": 11202,
"text": "P=Aβ
Pβ
Aβ+Q"
},
{
"code": null,
"e": 11489,
"s": 11213,
"text": "Thatβs it. The Kalman filter has made a prediction statement about the expected system state in the future or in the upcoming time-step. The filter will now be measuring / correcting and checking whether the prediction of the system state fits well with the new measurements."
},
{
"code": null,
"e": 11639,
"s": 11489,
"text": "The co-variance chosen to be smaller by the filter illustrates the certainty, if not, then something is wrong, which makes the filter more uncertain."
},
{
"code": null,
"e": 11713,
"s": 11639,
"text": "Note : The following mathematical calculations do not need to be derived."
},
{
"code": null,
"e": 11880,
"s": 11713,
"text": "From the sensors come current measured values, with which an innovation factor (y) is obtained by using the measurements ,the state vector with the measuring matrix ."
},
{
"code": null,
"e": 11890,
"s": 11880,
"text": "y=Zβ(Hβ
x)"
},
{
"code": null,
"e": 12052,
"s": 11890,
"text": "Then it is looks at with which variance can be further calculated. For this, the uncertainty and the measurement matrix and the measurement uncertainty required."
},
{
"code": null,
"e": 12065,
"s": 12052,
"text": "S=(Hβ
Pβ
Hβ²+R)"
},
{
"code": null,
"e": 12183,
"s": 12065,
"text": "This determines the so-called Kalman gain. It states whether the readings or system dynamics should be more familiar."
},
{
"code": null,
"e": 12193,
"s": 12183,
"text": "K= Pβ
HβS"
},
{
"code": null,
"e": 12368,
"s": 12193,
"text": "The Kalman Gain will decrease if the readings (measurements) match the predicted system state. If the measured values ββsay otherwise, the elements of matrix K become larger."
},
{
"code": null,
"e": 12425,
"s": 12368,
"text": "This information is now used to update the system state."
},
{
"code": null,
"e": 12442,
"s": 12425,
"text": "x = x + ( Kβ
y )"
},
{
"code": null,
"e": 12511,
"s": 12442,
"text": "And also determined a new co-variance for the upcoming predict step."
},
{
"code": null,
"e": 12527,
"s": 12511,
"text": "P= P- ( Kβ
H.P)"
},
{
"code": null,
"e": 12538,
"s": 12527,
"text": "which is ,"
},
{
"code": null,
"e": 12560,
"s": 12538,
"text": "P= ( I- ( Kβ
H) ) β
P"
},
{
"code": null,
"e": 12630,
"s": 12560,
"text": "Now itβs back to the step prediction. Graphically it looks like this:"
},
{
"code": null,
"e": 12847,
"s": 12630,
"text": "This filter runs permanently as long as measured values ββcome in. It can also be open loop, so only the prediction step will be executed if no measurements are available. Then the uncertainty gets bigger and bigger."
},
{
"code": null,
"e": 13057,
"s": 12847,
"text": "When we drive into a tunnel , the last known position is recorded which is received from the GPS. The Kalman filter can still predict the position of the vehicle, although it is not being measured at all time."
},
{
"code": null,
"e": 13507,
"s": 13057,
"text": "Now assuming the vehicle speed is available about every 20 m/s via the CAN bus, 6 iterations are only 0.1 s. The filter converges relatively quickly, depending on the choice of initial conditions. For example, after 100 iterations (equivalent to 2s on the vehicle), the variance is already very low, so the filter is confident on its estimated and updates states. My implementation of the linear Kalman filter could be found here . The results are :"
},
{
"code": null,
"e": 13899,
"s": 13507,
"text": "def Kalman_Filter() : for n in range(measurements): x = A*x+B*u[n] P = A*P*A.T + Q # Measurement Update (Correction) # =============================== # Compute the Kalman Gain S = H*P*H.T + R K = (P*H.T) * np.linalg.pinv(S)# Update the estimate via z Z = mx[n] y = Z β (H*x) # Innovation or Residual x = x + (K*y) # Update the error covariance P = (I β (K*H))*P"
},
{
"code": null,
"e": 14229,
"s": 13899,
"text": "Overall, no matter how large the numerical values are, but rather in what proportion they are. If the values chosen are ten times larger, this will hardly affect the filter. The ratio of values ββis crucial. The correct choice would be directly responsible for the filter performance and form the basic question of filter design."
},
{
"code": null,
"e": 14324,
"s": 14229,
"text": "This either / or question can only be decided on an application-specific basis. In some cases:"
},
{
"code": null,
"e": 14762,
"s": 14324,
"text": "We would just want to filter poorly measuring sensors for a relatively constant process. For example, we can implement kalman filter to optimize temperature controller in a furnace in a rocket or in chemical furnace.We would also want to merge several sensors and the dynamics should be preserved. Accordingly, the matrices should be selected. Alternatively, of course, the filter can be designed to adapt automatically during operation."
},
{
"code": null,
"e": 14979,
"s": 14762,
"text": "We would just want to filter poorly measuring sensors for a relatively constant process. For example, we can implement kalman filter to optimize temperature controller in a furnace in a rocket or in chemical furnace."
},
{
"code": null,
"e": 15201,
"s": 14979,
"text": "We would also want to merge several sensors and the dynamics should be preserved. Accordingly, the matrices should be selected. Alternatively, of course, the filter can be designed to adapt automatically during operation."
},
{
"code": null,
"e": 15593,
"s": 15201,
"text": "Kalman Filter works on prediction-correction model used for linear and time-variant or time-invariant systems. Prediction model involves the actual system and the process noise .The update model involves updating the predicated or the estimated value with the observation noise. Kalman gain is calculated based on RLS algorithm in order to reach the optimal value within less amount of time."
},
{
"code": null,
"e": 15864,
"s": 15593,
"text": "Recursive Least Squares is based on weighted least squares in which previous values taken in account for determining the future value. Each weight is exponentially assigned to each previous value of the actual system. The weights are updated recursively based on memory."
},
{
"code": null,
"e": 15885,
"s": 15864,
"text": "Notable Differences:"
},
{
"code": null,
"e": 16059,
"s": 15885,
"text": "RLS is faster than Kalman Filter.Accuracy of Kalman Filter is high.Kalman Filter is based on State-Space model where we need to model entire system to achieve optimal value."
},
{
"code": null,
"e": 16093,
"s": 16059,
"text": "RLS is faster than Kalman Filter."
},
{
"code": null,
"e": 16128,
"s": 16093,
"text": "Accuracy of Kalman Filter is high."
},
{
"code": null,
"e": 16235,
"s": 16128,
"text": "Kalman Filter is based on State-Space model where we need to model entire system to achieve optimal value."
},
{
"code": null,
"e": 16567,
"s": 16235,
"text": "Polynomial regression is a method of function approximation. We have a data set and we have to determine the functional relationship, which is often expressed by estimating the probability density p(z|x). Under the assumption that this probability is a Gaussian, we get the least squares solution as a maximum likelihood estimator."
},
{
"code": null,
"e": 16829,
"s": 16567,
"text": "Since Linear dynamic systems are state space models, we assume that the data we observe is generated by the application of a linear transform. The model we come with is the probability of a time series. The process then predicts the next value of a time series."
},
{
"code": null,
"e": 16926,
"s": 16829,
"text": "Polynomial regression does function approximation, Kalman filtering does time series prediction."
},
{
"code": null,
"e": 17079,
"s": 16926,
"text": "The time series prediction is a special case of function approximation. Both the models are modeled from different assumptions on the data they observe."
},
{
"code": null,
"e": 17464,
"s": 17079,
"text": "The Kalman filter is relatively quick and easy to implement and provides an optimal estimate of the condition for normally distributed noisy sensor values ββunder certain conditions. Mr. Kalman was so convinced of his algorithm that he was able to inspire a friendly engineer at NASA. And so this filter helped for the first time in the Apollo Guidance Computer at the moon landings ."
},
{
"code": null,
"e": 17652,
"s": 17464,
"text": "The Jupyter Notebook Collection of Roger Labbe.The amazing video series of Michel van BiezenKalman Filters in Pictures .The the blog post of Vivek Yadav .The amazing post by David Silver."
},
{
"code": null,
"e": 17700,
"s": 17652,
"text": "The Jupyter Notebook Collection of Roger Labbe."
},
{
"code": null,
"e": 17746,
"s": 17700,
"text": "The amazing video series of Michel van Biezen"
},
{
"code": null,
"e": 17775,
"s": 17746,
"text": "Kalman Filters in Pictures ."
},
{
"code": null,
"e": 17810,
"s": 17775,
"text": "The the blog post of Vivek Yadav ."
}
] |
How to predict a variable sinusoid in Python | by Angelica Lo Duca | Towards Data Science
|
This tutorial describes how to predict a variable sinusoid in Python. Firstly, some sinusoidal data are loaded from a CSV file. Then, data are shaped through a sinusoid curve. After that, linear regression is used to model the minimum and maximum peaks. Finally, the modeled lines are used to calculate the next peaks.
The complete code can be downloaded from my Github repository.
Data analyzed: Arrivals at tourist accommodation establishments extracted from https://ec.europa.eu/eurostat/web/tourism/data/database
Firstly, we read the CSV file and we select only data related to Italy (df[df['geo'] == 'IT']), in the form of numbers (df[df['unit'] == 'NR']) and referred to the sum of all data available (internal and external arrivals) (df[df['c_resid'] == 'TOTAL']).
Then we remove not useful columns through the function drop(). Note that we pass the parameter inplace=True to store effects in the original variable df.
import pandas as pddf = pd.read_csv(βdata/eurostat.csvβ)df = df[df[βgeoβ] == βITβ]df = df[df[βunitβ] == βNRβ]df = df[df[βc_residβ] == βTOTALβ]df.drop([βc_residβ, βunitβ, βnace_r2β, β2019M11β, βgeoβ],axis=1, inplace=True)df = df.reset_index()df.drop([βindexβ],axis=1, inplace=True)
Now we can correct some errors in data: some rows contain the character :, which means no data available. Other rows contain the letter b. We change : in 0 and we remove the letter b.
columns = df.columns[::-1]for column in columns: for row in range(1, len(df[column])): if βbβ in df[column][row]: df[column] = df[column][row][:-2] if β:β in df[column][row]: df[column][row] = β0β
Now we calculate the sum over the columns, in order to get the total number of arrivals for each month. We store results in the variable y.
y = []for column in columns: df[column] = df[column].astype(str).astype(int) y.append(df[column].sum())
We plot y to understand the trendline. We build the auxiliary vector X, which contains all the months. Month 0 refers to 1990 Genuary. In order to display x labels in the graph every 5 years, we build two auxiliary variables, x_ticks and x_labels.
import matplotlib.pyplot as pltimport matplotlibimport numpy as npX = np.arange(0, len(columns))step = 5x_ticks = np.arange(0, len(columns)+step, step=12*step)x_labels = []x_labels.append(1990)for i in range(1, len(x_tick)+1): x_labels.append(x_labels[i-1]+step)plt.xticks(x_ticks, x_labels)plt.plot(X, y, color=βredβ, linewidth=1)plt.grid()plt.xlabel(βMonthsβ)plt.ylabel(βNumber of arrivalsβ)plt.show()
We note that over the last 8 years there was an increase of the maximum peaks, with respect to the previous years. Thus we limit our analysis the last 8 years. This means that we should skip the first 22 years. We reset X and y to work only with the last years.
skip = 22*12X = X[skip:]y = y[skip:]
Now we can approximate data with a sinusoid. The equation of a sinusoid is A*np.sin(omega*x+phase) + offset, where:
|A| indicates the amplitude, i.e. half the distance between the maximum and minimum values of the function
omega is the number of cycles between 0 and 2pi. The period T is 2pi/omega
phase is the horizontal shift
offset is the vertical shift, i.e. the sum between the minimum peak and the amplitude. Here are some details about offset: https://www.ck12.org/book/ck-12-precalculus-concepts/section/5.4/
For more details about sinusoids, you can give look at: https://mathbitsnotebook.com/Algebra2/TrigGraphs/TGsinusoidal.html.
def sinusoid(x,A,offset,omega,phase): return A*np.sin(omega*x+phase) + offset
We define also initial values for the sinusoid. We set the period T = 12, i.e. the number of months in a year. If the period is not known, we should calculate it. We could use the Fast Fourier Transform. At these links, you can find more details about this aspect: https://stackoverflow.com/questions/16716302/how-do-i-fit-a-sine-curve-to-my-data-with-pylab-and-numpy, https://www.oreilly.com/library/view/elegant-scipy/9781491922927/ch04.html and https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html.
T = 12def get_p0(x, y): A0 = (max(y[0:T]) β min(y[0:T]))/2 offset0 = y[0] phase0 = 0 omega0 = 2.*np.pi/T return [A0, offset0,omega0, phase0]
Now we are ready to approximate our data with a sinusoid. We use the curve_fit() function provided by scipy. We plot results. For more details about the curve_fit() function, please give a look at https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html.
from scipy.optimize import curve_fitimport mathparam, covariance = curve_fit(sinusoid, X, y, p0=get_p0(X,y))step = 1x_ticks = np.arange(skip, skip+len(X)+step+12, step=12*step)x_labels = []x_labels.append(2012)for i in range(1, len(x_tick)+13): x_labels.append(x_labels[i-1]+step)plt.xticks(x_ticks, x_labels)plt.ylabel(βNumber of arrivalsβ)plt.plot(X, y, color=βredβ, linewidth=1,linestyle=βdashedβ)plt.plot(X, sinusoid(X, *param), color=βblueβ, linewidth=1)plt.show()
We have approximated our data with a sinusoid with a constant value of A. In our case both the amplitude A and the offset are variable. The idea is to calculate all the maximum peaks and minimum peaks in our data. Then we can use their difference to calculate the vector of amplitudes and pass them to the sinusoid() function.
We define the function get_peaks(), which calculates the peaks of an array. We sample the array every T elements and we calculate the peak within each T.
def get_peaks(y, metrics): n = int(math.ceil(len(y)/T)) step = 0 x_peaks = [] y_peaks = [] for i in range(0,n): peak_index = y.index(metrics(y[step:step+T])) x_peaks.append(peak_index + skip) y_peaks.append(y[peak_index]) step = step+T return [x_peaks,y_peaks]
We calculate the maximum and minimum peaks.
min_peaks = get_peaks(y,min)max_peaks = get_peaks(y,max)
Now we can calculate the array of amplitudes and offsets.
A = []offset = []for i in range(0, len(min_peaks[1])): c_a = (max_peaks[1][i] β min_peaks[1][i])/2 c_offset = min_peaks[1][i] + c_a for j in range(0,T): A.append(c_a) offset.append(c_offset)# last two months of 2019 are not availableA = A[:-2]offset = offset[:-2]
Since A and offset are new features, we should add them as variables. Thus we define a new variable features, which defines the new input features of our model. Then we define the function variable_sinusoid(), which takes the features as input.
The only parameters returned by our model are omega and phase thus we modify also the function get_p0() with initial values of omega and phase. The new function is called variable_get_p0().
features = [X, A, offset]def variable_sinusoid(features,omega,phase): x = features[0] A = features[1] offset = features[2] return A*np.sin(omega*x+phase) + offsetdef variable_get_p0(x, y): phase0 = 0 omega0 = 2.*np.pi/T return [omega0, phase0]
We fit the model and plot results.
param, covariance = curve_fit(variable_sinusoid, features, y, p0=variable_get_p0(X,y))plt.xticks(x_ticks, x_labels)plt.ylabel(βNumber of arrivalsβ)plt.plot(X, y, color=βredβ, linewidth=1,linestyle=βdashedβ)plt.plot(X, variable_sinusoid(features, *param), color=βblueβ, linewidth=1)plt.show()
The next step involves the prediction of the next sinusoid, i.e. the sinusoid for the year 2020. In order to do it, we need to calculate the next max and minimum peaks. We can do it by approximating the vector of maximum and minimum peaks with two linear regressions, respectively. Then, we can calculate the maximum peak at instant i (August 2020) as the y value of the maximum linear regression given at instant (i-1) + pi (i-1 represents August 2019). Similarly, we can calculate the minimum peak for year 2020.
Firstly, we reshape the peaks to be passed to the linear model. Then, we build two linear models, one for each predicting line, using the sklearn class LinearRegression(). After that, we fit every model using the fit() function.
from sklearn import linear_model# reshape x_peaksx_min_peaks = list(map(lambda el:[el], min_peaks[0])) x_max_peaks = list(map(lambda el:[el], max_peaks[0]))# min modelmodel_min = linear_model.LinearRegression()model_min.fit(x_min_peaks,min_peaks[1])# max modelmodel_max = linear_model.LinearRegression()model_max.fit(x_max_peaks,max_peaks[1])
We append the next peaks both to x_max_peaks and x_min_peaks and then we predict the maximum and minimum peaks through the predict() function.
x_min_peaks.append([x_min_peaks[len(x_min_peaks) -1][0] + T])x_max_peaks.append([x_max_peaks[len(x_max_peaks) -1][0] + T])y_pred_min = model_min.predict(x_min_peaks)y_pred_max = model_max.predict(x_max_peaks)
We plot the two predicting lines.
plt.xticks(x_ticks, x_labels)plt.plot(X, y, color=βredβ, linewidth=1,linestyle=βdashedβ)plt.scatter(x_min_peaks, y_pred_min, color=βgreenβ, linewidth=1,linestyle=βdashedβ)plt.scatter(x_max_peaks, y_pred_max, color=βgreenβ, linewidth=1,linestyle=βdashedβ)plt.ylabel(βNumber of arrivalsβ)plt.grid()plt.show()
We calculate the sinusoid for all the periods, including 2020. We build a variable X_pred, which contains X and the 12 months of 2020.
X_pred = np.array(X)month = X_pred[len(X_pred)-1]for i in range(0,T): X_pred = np.append(X_pred,month) month = month + 1
Now, we can update the variable features_pred to be passed to the variable_sinusoid() function. Firstly, we update the amplitude A and the offset with new values and then we update the features_pred variable.
index = len(max_peaks[0])-1c_a = (max_peaks[1][index] β min_peaks[1][index])/2c_offset = min_peaks[1][index] + c_afor j in range(0,T): A.append(c_a) offset.append(c_offset)features_pred = [X_pred,A,offset]
Finally, we plot graphs.
plt.xticks(x_ticks, x_labels)plt.plot(X, y, color=βredβ, linewidth=1,linestyle=βdashedβ)plt.plot(X_pred, variable_sinusoid(features_pred, *param), color=βblueβ, linewidth=1)plt.grid()plt.ylabel(βNumber of arrivalsβ)plt.savefig(βdata/sinusoid.pngβ)plt.show()
In this tutorial, I have illustrated a methodology to approximate data having a sinusoidal trend through a variable sinusoid. Then I have described the mechanism to predict the next values of data.
The described methodology can be generalized to all kinds of curves:
load and clean data
plot data to understand the trend line
approximate the trend line with a curve through the curve_fit() function
plot result of approximation and compare with the original data trend line
if needed, improve the approximated trend line
repeat the previous two steps until you get a good approximation
calculate a (linear, polynomial, ...) regression to predict future values
use predicted values to update the approximated trendline.
If you have read this far, for me it is already a lot for today. Thanks! You can read my trending articles at this link.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
The job of the data scientist is very challenging: your knowledge must span from data mining to data analysis up to data visualization. You never stop.
However, what happens when you launch a heavy computation, such as a Machine Learning algorithm on a big dataset? You stop and wait for a result. You may watch your screen for hours, in the hope that your script finishes.
Anyway, this is not the best way to spend your time. You should do something else. You cannot sit down and wait for results.
Continue reading here.
Follow me on Medium
Sign up for my newsletter
Connect on LinkedIn
Follow me on Twitter
Follow me on Facebook
Follow me on Github
|
[
{
"code": null,
"e": 366,
"s": 47,
"text": "This tutorial describes how to predict a variable sinusoid in Python. Firstly, some sinusoidal data are loaded from a CSV file. Then, data are shaped through a sinusoid curve. After that, linear regression is used to model the minimum and maximum peaks. Finally, the modeled lines are used to calculate the next peaks."
},
{
"code": null,
"e": 429,
"s": 366,
"text": "The complete code can be downloaded from my Github repository."
},
{
"code": null,
"e": 564,
"s": 429,
"text": "Data analyzed: Arrivals at tourist accommodation establishments extracted from https://ec.europa.eu/eurostat/web/tourism/data/database"
},
{
"code": null,
"e": 819,
"s": 564,
"text": "Firstly, we read the CSV file and we select only data related to Italy (df[df['geo'] == 'IT']), in the form of numbers (df[df['unit'] == 'NR']) and referred to the sum of all data available (internal and external arrivals) (df[df['c_resid'] == 'TOTAL'])."
},
{
"code": null,
"e": 973,
"s": 819,
"text": "Then we remove not useful columns through the function drop(). Note that we pass the parameter inplace=True to store effects in the original variable df."
},
{
"code": null,
"e": 1254,
"s": 973,
"text": "import pandas as pddf = pd.read_csv(βdata/eurostat.csvβ)df = df[df[βgeoβ] == βITβ]df = df[df[βunitβ] == βNRβ]df = df[df[βc_residβ] == βTOTALβ]df.drop([βc_residβ, βunitβ, βnace_r2β, β2019M11β, βgeoβ],axis=1, inplace=True)df = df.reset_index()df.drop([βindexβ],axis=1, inplace=True)"
},
{
"code": null,
"e": 1438,
"s": 1254,
"text": "Now we can correct some errors in data: some rows contain the character :, which means no data available. Other rows contain the letter b. We change : in 0 and we remove the letter b."
},
{
"code": null,
"e": 1635,
"s": 1438,
"text": "columns = df.columns[::-1]for column in columns: for row in range(1, len(df[column])): if βbβ in df[column][row]: df[column] = df[column][row][:-2] if β:β in df[column][row]: df[column][row] = β0β"
},
{
"code": null,
"e": 1775,
"s": 1635,
"text": "Now we calculate the sum over the columns, in order to get the total number of arrivals for each month. We store results in the variable y."
},
{
"code": null,
"e": 1879,
"s": 1775,
"text": "y = []for column in columns: df[column] = df[column].astype(str).astype(int) y.append(df[column].sum())"
},
{
"code": null,
"e": 2127,
"s": 1879,
"text": "We plot y to understand the trendline. We build the auxiliary vector X, which contains all the months. Month 0 refers to 1990 Genuary. In order to display x labels in the graph every 5 years, we build two auxiliary variables, x_ticks and x_labels."
},
{
"code": null,
"e": 2531,
"s": 2127,
"text": "import matplotlib.pyplot as pltimport matplotlibimport numpy as npX = np.arange(0, len(columns))step = 5x_ticks = np.arange(0, len(columns)+step, step=12*step)x_labels = []x_labels.append(1990)for i in range(1, len(x_tick)+1): x_labels.append(x_labels[i-1]+step)plt.xticks(x_ticks, x_labels)plt.plot(X, y, color=βredβ, linewidth=1)plt.grid()plt.xlabel(βMonthsβ)plt.ylabel(βNumber of arrivalsβ)plt.show()"
},
{
"code": null,
"e": 2793,
"s": 2531,
"text": "We note that over the last 8 years there was an increase of the maximum peaks, with respect to the previous years. Thus we limit our analysis the last 8 years. This means that we should skip the first 22 years. We reset X and y to work only with the last years."
},
{
"code": null,
"e": 2830,
"s": 2793,
"text": "skip = 22*12X = X[skip:]y = y[skip:]"
},
{
"code": null,
"e": 2946,
"s": 2830,
"text": "Now we can approximate data with a sinusoid. The equation of a sinusoid is A*np.sin(omega*x+phase) + offset, where:"
},
{
"code": null,
"e": 3053,
"s": 2946,
"text": "|A| indicates the amplitude, i.e. half the distance between the maximum and minimum values of the function"
},
{
"code": null,
"e": 3128,
"s": 3053,
"text": "omega is the number of cycles between 0 and 2pi. The period T is 2pi/omega"
},
{
"code": null,
"e": 3158,
"s": 3128,
"text": "phase is the horizontal shift"
},
{
"code": null,
"e": 3347,
"s": 3158,
"text": "offset is the vertical shift, i.e. the sum between the minimum peak and the amplitude. Here are some details about offset: https://www.ck12.org/book/ck-12-precalculus-concepts/section/5.4/"
},
{
"code": null,
"e": 3471,
"s": 3347,
"text": "For more details about sinusoids, you can give look at: https://mathbitsnotebook.com/Algebra2/TrigGraphs/TGsinusoidal.html."
},
{
"code": null,
"e": 3549,
"s": 3471,
"text": "def sinusoid(x,A,offset,omega,phase): return A*np.sin(omega*x+phase) + offset"
},
{
"code": null,
"e": 4070,
"s": 3549,
"text": "We define also initial values for the sinusoid. We set the period T = 12, i.e. the number of months in a year. If the period is not known, we should calculate it. We could use the Fast Fourier Transform. At these links, you can find more details about this aspect: https://stackoverflow.com/questions/16716302/how-do-i-fit-a-sine-curve-to-my-data-with-pylab-and-numpy, https://www.oreilly.com/library/view/elegant-scipy/9781491922927/ch04.html and https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html."
},
{
"code": null,
"e": 4212,
"s": 4070,
"text": "T = 12def get_p0(x, y): A0 = (max(y[0:T]) β min(y[0:T]))/2 offset0 = y[0] phase0 = 0 omega0 = 2.*np.pi/T return [A0, offset0,omega0, phase0]"
},
{
"code": null,
"e": 4493,
"s": 4212,
"text": "Now we are ready to approximate our data with a sinusoid. We use the curve_fit() function provided by scipy. We plot results. For more details about the curve_fit() function, please give a look at https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html."
},
{
"code": null,
"e": 4963,
"s": 4493,
"text": "from scipy.optimize import curve_fitimport mathparam, covariance = curve_fit(sinusoid, X, y, p0=get_p0(X,y))step = 1x_ticks = np.arange(skip, skip+len(X)+step+12, step=12*step)x_labels = []x_labels.append(2012)for i in range(1, len(x_tick)+13): x_labels.append(x_labels[i-1]+step)plt.xticks(x_ticks, x_labels)plt.ylabel(βNumber of arrivalsβ)plt.plot(X, y, color=βredβ, linewidth=1,linestyle=βdashedβ)plt.plot(X, sinusoid(X, *param), color=βblueβ, linewidth=1)plt.show()"
},
{
"code": null,
"e": 5290,
"s": 4963,
"text": "We have approximated our data with a sinusoid with a constant value of A. In our case both the amplitude A and the offset are variable. The idea is to calculate all the maximum peaks and minimum peaks in our data. Then we can use their difference to calculate the vector of amplitudes and pass them to the sinusoid() function."
},
{
"code": null,
"e": 5444,
"s": 5290,
"text": "We define the function get_peaks(), which calculates the peaks of an array. We sample the array every T elements and we calculate the peak within each T."
},
{
"code": null,
"e": 5705,
"s": 5444,
"text": "def get_peaks(y, metrics): n = int(math.ceil(len(y)/T)) step = 0 x_peaks = [] y_peaks = [] for i in range(0,n): peak_index = y.index(metrics(y[step:step+T])) x_peaks.append(peak_index + skip) y_peaks.append(y[peak_index]) step = step+T return [x_peaks,y_peaks]"
},
{
"code": null,
"e": 5749,
"s": 5705,
"text": "We calculate the maximum and minimum peaks."
},
{
"code": null,
"e": 5806,
"s": 5749,
"text": "min_peaks = get_peaks(y,min)max_peaks = get_peaks(y,max)"
},
{
"code": null,
"e": 5864,
"s": 5806,
"text": "Now we can calculate the array of amplitudes and offsets."
},
{
"code": null,
"e": 6128,
"s": 5864,
"text": "A = []offset = []for i in range(0, len(min_peaks[1])): c_a = (max_peaks[1][i] β min_peaks[1][i])/2 c_offset = min_peaks[1][i] + c_a for j in range(0,T): A.append(c_a) offset.append(c_offset)# last two months of 2019 are not availableA = A[:-2]offset = offset[:-2]"
},
{
"code": null,
"e": 6373,
"s": 6128,
"text": "Since A and offset are new features, we should add them as variables. Thus we define a new variable features, which defines the new input features of our model. Then we define the function variable_sinusoid(), which takes the features as input."
},
{
"code": null,
"e": 6563,
"s": 6373,
"text": "The only parameters returned by our model are omega and phase thus we modify also the function get_p0() with initial values of omega and phase. The new function is called variable_get_p0()."
},
{
"code": null,
"e": 6808,
"s": 6563,
"text": "features = [X, A, offset]def variable_sinusoid(features,omega,phase): x = features[0] A = features[1] offset = features[2] return A*np.sin(omega*x+phase) + offsetdef variable_get_p0(x, y): phase0 = 0 omega0 = 2.*np.pi/T return [omega0, phase0]"
},
{
"code": null,
"e": 6843,
"s": 6808,
"text": "We fit the model and plot results."
},
{
"code": null,
"e": 7135,
"s": 6843,
"text": "param, covariance = curve_fit(variable_sinusoid, features, y, p0=variable_get_p0(X,y))plt.xticks(x_ticks, x_labels)plt.ylabel(βNumber of arrivalsβ)plt.plot(X, y, color=βredβ, linewidth=1,linestyle=βdashedβ)plt.plot(X, variable_sinusoid(features, *param), color=βblueβ, linewidth=1)plt.show()"
},
{
"code": null,
"e": 7650,
"s": 7135,
"text": "The next step involves the prediction of the next sinusoid, i.e. the sinusoid for the year 2020. In order to do it, we need to calculate the next max and minimum peaks. We can do it by approximating the vector of maximum and minimum peaks with two linear regressions, respectively. Then, we can calculate the maximum peak at instant i (August 2020) as the y value of the maximum linear regression given at instant (i-1) + pi (i-1 represents August 2019). Similarly, we can calculate the minimum peak for year 2020."
},
{
"code": null,
"e": 7879,
"s": 7650,
"text": "Firstly, we reshape the peaks to be passed to the linear model. Then, we build two linear models, one for each predicting line, using the sklearn class LinearRegression(). After that, we fit every model using the fit() function."
},
{
"code": null,
"e": 8222,
"s": 7879,
"text": "from sklearn import linear_model# reshape x_peaksx_min_peaks = list(map(lambda el:[el], min_peaks[0])) x_max_peaks = list(map(lambda el:[el], max_peaks[0]))# min modelmodel_min = linear_model.LinearRegression()model_min.fit(x_min_peaks,min_peaks[1])# max modelmodel_max = linear_model.LinearRegression()model_max.fit(x_max_peaks,max_peaks[1])"
},
{
"code": null,
"e": 8365,
"s": 8222,
"text": "We append the next peaks both to x_max_peaks and x_min_peaks and then we predict the maximum and minimum peaks through the predict() function."
},
{
"code": null,
"e": 8574,
"s": 8365,
"text": "x_min_peaks.append([x_min_peaks[len(x_min_peaks) -1][0] + T])x_max_peaks.append([x_max_peaks[len(x_max_peaks) -1][0] + T])y_pred_min = model_min.predict(x_min_peaks)y_pred_max = model_max.predict(x_max_peaks)"
},
{
"code": null,
"e": 8608,
"s": 8574,
"text": "We plot the two predicting lines."
},
{
"code": null,
"e": 8915,
"s": 8608,
"text": "plt.xticks(x_ticks, x_labels)plt.plot(X, y, color=βredβ, linewidth=1,linestyle=βdashedβ)plt.scatter(x_min_peaks, y_pred_min, color=βgreenβ, linewidth=1,linestyle=βdashedβ)plt.scatter(x_max_peaks, y_pred_max, color=βgreenβ, linewidth=1,linestyle=βdashedβ)plt.ylabel(βNumber of arrivalsβ)plt.grid()plt.show()"
},
{
"code": null,
"e": 9050,
"s": 8915,
"text": "We calculate the sinusoid for all the periods, including 2020. We build a variable X_pred, which contains X and the 12 months of 2020."
},
{
"code": null,
"e": 9171,
"s": 9050,
"text": "X_pred = np.array(X)month = X_pred[len(X_pred)-1]for i in range(0,T): X_pred = np.append(X_pred,month) month = month + 1"
},
{
"code": null,
"e": 9380,
"s": 9171,
"text": "Now, we can update the variable features_pred to be passed to the variable_sinusoid() function. Firstly, we update the amplitude A and the offset with new values and then we update the features_pred variable."
},
{
"code": null,
"e": 9586,
"s": 9380,
"text": "index = len(max_peaks[0])-1c_a = (max_peaks[1][index] β min_peaks[1][index])/2c_offset = min_peaks[1][index] + c_afor j in range(0,T): A.append(c_a) offset.append(c_offset)features_pred = [X_pred,A,offset]"
},
{
"code": null,
"e": 9611,
"s": 9586,
"text": "Finally, we plot graphs."
},
{
"code": null,
"e": 9869,
"s": 9611,
"text": "plt.xticks(x_ticks, x_labels)plt.plot(X, y, color=βredβ, linewidth=1,linestyle=βdashedβ)plt.plot(X_pred, variable_sinusoid(features_pred, *param), color=βblueβ, linewidth=1)plt.grid()plt.ylabel(βNumber of arrivalsβ)plt.savefig(βdata/sinusoid.pngβ)plt.show()"
},
{
"code": null,
"e": 10067,
"s": 9869,
"text": "In this tutorial, I have illustrated a methodology to approximate data having a sinusoidal trend through a variable sinusoid. Then I have described the mechanism to predict the next values of data."
},
{
"code": null,
"e": 10136,
"s": 10067,
"text": "The described methodology can be generalized to all kinds of curves:"
},
{
"code": null,
"e": 10156,
"s": 10136,
"text": "load and clean data"
},
{
"code": null,
"e": 10195,
"s": 10156,
"text": "plot data to understand the trend line"
},
{
"code": null,
"e": 10268,
"s": 10195,
"text": "approximate the trend line with a curve through the curve_fit() function"
},
{
"code": null,
"e": 10343,
"s": 10268,
"text": "plot result of approximation and compare with the original data trend line"
},
{
"code": null,
"e": 10390,
"s": 10343,
"text": "if needed, improve the approximated trend line"
},
{
"code": null,
"e": 10455,
"s": 10390,
"text": "repeat the previous two steps until you get a good approximation"
},
{
"code": null,
"e": 10529,
"s": 10455,
"text": "calculate a (linear, polynomial, ...) regression to predict future values"
},
{
"code": null,
"e": 10588,
"s": 10529,
"text": "use predicted values to update the approximated trendline."
},
{
"code": null,
"e": 10709,
"s": 10588,
"text": "If you have read this far, for me it is already a lot for today. Thanks! You can read my trending articles at this link."
},
{
"code": null,
"e": 10732,
"s": 10709,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10755,
"s": 10732,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10778,
"s": 10755,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10930,
"s": 10778,
"text": "The job of the data scientist is very challenging: your knowledge must span from data mining to data analysis up to data visualization. You never stop."
},
{
"code": null,
"e": 11152,
"s": 10930,
"text": "However, what happens when you launch a heavy computation, such as a Machine Learning algorithm on a big dataset? You stop and wait for a result. You may watch your screen for hours, in the hope that your script finishes."
},
{
"code": null,
"e": 11277,
"s": 11152,
"text": "Anyway, this is not the best way to spend your time. You should do something else. You cannot sit down and wait for results."
},
{
"code": null,
"e": 11300,
"s": 11277,
"text": "Continue reading here."
},
{
"code": null,
"e": 11320,
"s": 11300,
"text": "Follow me on Medium"
},
{
"code": null,
"e": 11346,
"s": 11320,
"text": "Sign up for my newsletter"
},
{
"code": null,
"e": 11366,
"s": 11346,
"text": "Connect on LinkedIn"
},
{
"code": null,
"e": 11387,
"s": 11366,
"text": "Follow me on Twitter"
},
{
"code": null,
"e": 11409,
"s": 11387,
"text": "Follow me on Facebook"
}
] |
Expressing numbers in expanded form - JavaScript
|
Suppose we are given a number 124 and are required to write a function that takes this number as input and returns its expanded form as a string.
The expanded form of 124 is β
'100+20+4'
Following is the code β
const num = 125;
const expandedForm = num => {
const numStr = String(num);
let res = '';
for(let i = 0; i < numStr.length; i++){
const placeValue = +(numStr[i]) * Math.pow(10, (numStr.length - 1 - i));
if(numStr.length - i > 1){
res += `${placeValue}+`
}else{
res += placeValue;
};
};
return res;
};
console.log(expandedForm(num));
Following is the output in the console β
100+20+5
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "Suppose we are given a number 124 and are required to write a function that takes this number as input and returns its expanded form as a string."
},
{
"code": null,
"e": 1238,
"s": 1208,
"text": "The expanded form of 124 is β"
},
{
"code": null,
"e": 1249,
"s": 1238,
"text": "'100+20+4'"
},
{
"code": null,
"e": 1273,
"s": 1249,
"text": "Following is the code β"
},
{
"code": null,
"e": 1662,
"s": 1273,
"text": "const num = 125;\nconst expandedForm = num => {\n const numStr = String(num);\n let res = '';\n for(let i = 0; i < numStr.length; i++){\n const placeValue = +(numStr[i]) * Math.pow(10, (numStr.length - 1 - i));\n if(numStr.length - i > 1){\n res += `${placeValue}+`\n }else{\n res += placeValue;\n };\n };\n return res;\n};\nconsole.log(expandedForm(num));"
},
{
"code": null,
"e": 1703,
"s": 1662,
"text": "Following is the output in the console β"
},
{
"code": null,
"e": 1712,
"s": 1703,
"text": "100+20+5"
}
] |
DAX Time Intelligence - DATESQTD function
|
Returns a table that contains a column of the dates for the quarter to date, in the current context.
DATESQTD (<dates>)
dates
A column that contains dates.
A table containing a single column of date values.
The dates parameter can be any of the following β
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions β
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
= CALCULATE (
SUM (Sales [Sales Amount]), DATESQTD (Sales [Date])
)
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2102,
"s": 2001,
"text": "Returns a table that contains a column of the dates for the quarter to date, in the current context."
},
{
"code": null,
"e": 2123,
"s": 2102,
"text": "DATESQTD (<dates>) \n"
},
{
"code": null,
"e": 2129,
"s": 2123,
"text": "dates"
},
{
"code": null,
"e": 2159,
"s": 2129,
"text": "A column that contains dates."
},
{
"code": null,
"e": 2210,
"s": 2159,
"text": "A table containing a single column of date values."
},
{
"code": null,
"e": 2260,
"s": 2210,
"text": "The dates parameter can be any of the following β"
},
{
"code": null,
"e": 2295,
"s": 2260,
"text": "A reference to a date/time column."
},
{
"code": null,
"e": 2330,
"s": 2295,
"text": "A reference to a date/time column."
},
{
"code": null,
"e": 2399,
"s": 2330,
"text": "A table expression that returns a single column of date/time values."
},
{
"code": null,
"e": 2468,
"s": 2399,
"text": "A table expression that returns a single column of date/time values."
},
{
"code": null,
"e": 2545,
"s": 2468,
"text": "A Boolean expression that defines a single-column table of date/time values."
},
{
"code": null,
"e": 2622,
"s": 2545,
"text": "A Boolean expression that defines a single-column table of date/time values."
},
{
"code": null,
"e": 2659,
"s": 2622,
"text": "Constraints on Boolean expressions β"
},
{
"code": null,
"e": 2711,
"s": 2659,
"text": "The expression cannot reference a calculated field."
},
{
"code": null,
"e": 2763,
"s": 2711,
"text": "The expression cannot reference a calculated field."
},
{
"code": null,
"e": 2809,
"s": 2763,
"text": "The expression cannot use CALCULATE function."
},
{
"code": null,
"e": 2855,
"s": 2809,
"text": "The expression cannot use CALCULATE function."
},
{
"code": null,
"e": 2966,
"s": 2855,
"text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3077,
"s": 2966,
"text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3193,
"s": 3077,
"text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value."
},
{
"code": null,
"e": 3266,
"s": 3193,
"text": "= CALCULATE ( \n SUM (Sales [Sales Amount]), DATESQTD (Sales [Date])\n) "
},
{
"code": null,
"e": 3301,
"s": 3266,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3315,
"s": 3301,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3348,
"s": 3315,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3362,
"s": 3348,
"text": " Randy Minder"
},
{
"code": null,
"e": 3397,
"s": 3362,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3411,
"s": 3397,
"text": " Randy Minder"
},
{
"code": null,
"e": 3418,
"s": 3411,
"text": " Print"
},
{
"code": null,
"e": 3429,
"s": 3418,
"text": " Add Notes"
}
] |
Scala Collections - Array with Range
|
Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1.
Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18.
Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, ..., and 19.
The following example program shows how to create an array with ranges.
import Array._
object Demo {
def main(args: Array[String]) {
var myList1 = range(10, 20, 2)
var myList2 = range(10,20)
// Print all the array elements
for ( x <- myList1 ) {
print( " " + x )
}
println()
for ( x <- myList2 ) {
print( " " + x )
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
10 12 14 16 18
10 11 12 13 14 15 16 17 18 19
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3114,
"s": 2882,
"text": "Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1."
},
{
"code": null,
"e": 3313,
"s": 3114,
"text": "Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18."
},
{
"code": null,
"e": 3555,
"s": 3313,
"text": "Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, ..., and 19."
},
{
"code": null,
"e": 3627,
"s": 3555,
"text": "The following example program shows how to create an array with ranges."
},
{
"code": null,
"e": 3948,
"s": 3627,
"text": "import Array._\nobject Demo {\n def main(args: Array[String]) {\n var myList1 = range(10, 20, 2)\n var myList2 = range(10,20)\n // Print all the array elements\n for ( x <- myList1 ) {\n print( \" \" + x )\n }\n println()\n for ( x <- myList2 ) {\n print( \" \" + x )\n }\n }\n}"
},
{
"code": null,
"e": 4055,
"s": 3948,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 4089,
"s": 4055,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 4135,
"s": 4089,
"text": "10 12 14 16 18\n10 11 12 13 14 15 16 17 18 19\n"
},
{
"code": null,
"e": 4168,
"s": 4135,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4187,
"s": 4168,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4222,
"s": 4187,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4243,
"s": 4222,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 4278,
"s": 4243,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4296,
"s": 4278,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4331,
"s": 4296,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4349,
"s": 4331,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4384,
"s": 4349,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4402,
"s": 4384,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4437,
"s": 4402,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4460,
"s": 4437,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4467,
"s": 4460,
"text": " Print"
},
{
"code": null,
"e": 4478,
"s": 4467,
"text": " Add Notes"
}
] |
HTML <noscript> Tag - GeeksforGeeks
|
17 Mar, 2022
The <noscript> tag in HTML is used to display the text for those browsers which does not support script tag or the browsers disable the script by the user. This tag is used in both <head> and <body> tag.
Note: This tag is used in those browsers only which does not support scripts.
Syntax:
<noscript> Contents... </noscript>
Below example illustrates the <noscript> tag in HTML:
Example:
HTML
<html> <body> <h1>GeeksforGeeks</h1> <h2>HTML noscript Tag</h2> <script> document.write("GeeksforGeeks!") </script> <!-- noscript tag starts --> <noscript>A computer science portal</noscript> <!-- noscript tag ends --> </body> </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Vishal_Khoda
arorakashish0911
ghoshsuman0129
HTML-Tags
Technical Scripter 2018
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 23149,
"s": 23121,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 23353,
"s": 23149,
"text": "The <noscript> tag in HTML is used to display the text for those browsers which does not support script tag or the browsers disable the script by the user. This tag is used in both <head> and <body> tag."
},
{
"code": null,
"e": 23431,
"s": 23353,
"text": "Note: This tag is used in those browsers only which does not support scripts."
},
{
"code": null,
"e": 23441,
"s": 23431,
"text": "Syntax: "
},
{
"code": null,
"e": 23476,
"s": 23441,
"text": "<noscript> Contents... </noscript>"
},
{
"code": null,
"e": 23530,
"s": 23476,
"text": "Below example illustrates the <noscript> tag in HTML:"
},
{
"code": null,
"e": 23540,
"s": 23530,
"text": "Example: "
},
{
"code": null,
"e": 23545,
"s": 23540,
"text": "HTML"
},
{
"code": "<html> <body> <h1>GeeksforGeeks</h1> <h2>HTML noscript Tag</h2> <script> document.write(\"GeeksforGeeks!\") </script> <!-- noscript tag starts --> <noscript>A computer science portal</noscript> <!-- noscript tag ends --> </body> </html>",
"e": 23808,
"s": 23545,
"text": null
},
{
"code": null,
"e": 23817,
"s": 23808,
"text": "Output: "
},
{
"code": null,
"e": 23838,
"s": 23817,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 23852,
"s": 23838,
"text": "Google Chrome"
},
{
"code": null,
"e": 23870,
"s": 23852,
"text": "Internet Explorer"
},
{
"code": null,
"e": 23878,
"s": 23870,
"text": "Firefox"
},
{
"code": null,
"e": 23884,
"s": 23878,
"text": "Opera"
},
{
"code": null,
"e": 23891,
"s": 23884,
"text": "Safari"
},
{
"code": null,
"e": 24028,
"s": 23891,
"text": "Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 24041,
"s": 24028,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 24058,
"s": 24041,
"text": "arorakashish0911"
},
{
"code": null,
"e": 24073,
"s": 24058,
"text": "ghoshsuman0129"
},
{
"code": null,
"e": 24083,
"s": 24073,
"text": "HTML-Tags"
},
{
"code": null,
"e": 24107,
"s": 24083,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 24112,
"s": 24107,
"text": "HTML"
},
{
"code": null,
"e": 24117,
"s": 24112,
"text": "HTML"
},
{
"code": null,
"e": 24215,
"s": 24117,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24277,
"s": 24215,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 24327,
"s": 24277,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 24387,
"s": 24327,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 24435,
"s": 24387,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 24496,
"s": 24435,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 24549,
"s": 24496,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 24599,
"s": 24549,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 24623,
"s": 24599,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 24673,
"s": 24623,
"text": "CSS to put icon inside an input element in a form"
}
] |
How to remove a directory recursively using Python?
|
If you want to delete a folder containing all files and folders you want to remove, you can remove the folder(or tree) as follows:
>>> import shutil
>>> shutil.rmtree('my_folder')
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "If you want to delete a folder containing all files and folders you want to remove, you can remove the folder(or tree) as follows:"
},
{
"code": null,
"e": 1242,
"s": 1193,
"text": ">>> import shutil\n>>> shutil.rmtree('my_folder')"
}
] |
M-Coloring Problem | Practice | GeeksforGeeks
|
Given an undirected graph and an integer M. The task is to determine if the graph can be colored with at most M colors such that no two adjacent vertices of the graph are colored with the same color. Here coloring of a graph means the assignment of colors to all vertices. Print 1 if it is possible to colour vertices and 0 otherwise.
Example 1:
Input:
N = 4
M = 3
E = 5
Edges[] = {(0,1),(1,2),(2,3),(3,0),(0,2)}
Output: 1
Explanation: It is possible to colour the
given graph using 3 colours.
Example 2:
Input:
N = 3
M = 2
E = 3
Edges[] = {(0,1),(1,2),(0,2)}
Output: 0
Your Task:
Your task is to complete the function graphColoring() which takes the 2d-array graph[], the number of colours and the number of nodes as inputs and returns true if answer exists otherwise false. 1 is printed if the returned value is true, 0 otherwise. The printing is done by the driver's code.
Note: In Example there are Edges not the graph.Graph will be like, if there is an edge between vertex X and vertex Y graph[] will contain 1 at graph[X-1][Y-1], else 0. In 2d-array graph[ ], nodes are 0-based indexed, i.e. from 0 to N-1.Function will be contain 2-D graph not the edges.
Expected Time Complexity: O(MN).
Expected Auxiliary Space: O(N).
Constraints:
1 β€ N β€ 20
1 β€ E β€ (N*(N-1))/2
1 β€ M β€ N
0
ydahanh
This comment was deleted.
0
milindprajapatmst194 days ago
Total Time Taken: 0.04/1.06
Idea: dfs
const int N = 20;
int color[N];
bool check(int u, int n, int c, bool graph[101][101]) {
for (int v = 0; v < n; v++) {
if (u != v && graph[u][v] && color[v] == c)
return true;
}
return false;
}
bool help(int u, int n, int m, bool graph[101][101]) {
if (u == n)
return true;
for (int c = 0; c < m; c++) {
if (check(u, n, c, graph))
continue;
color[u] = c;
if (help(u + 1, n, m, graph))
return true;
color[u] = -1;
}
return false;
}
bool graphColoring(bool graph[101][101], int m, int n) {
memset(color, -1, sizeof(color));
return help(0, n, m, graph);
}
+1
akshu199bhardwaj2 weeks ago
Can anyone tell why all tcs are not passing with this code?
int colour[101]={0};bool isvalid(int c, int n,bool graph[101][101], int m, int v){ for(int j=0; j<v; j++) { if(j!=n && graph[j][n]==1 && colour[j]==c) return false; } return true;}bool helper(int n, bool graph[101][101], int m, int v){ if(n==v) return 1; for(int i=1; i<=m; i++){ if(isvalid(i,n,graph,m,v)) { colour[n]=i; if(helper(n+1,graph,m,v)) return true; colour[n]=0; } }return false; }
bool graphColoring(bool graph[101][101], int m, int v){ if(helper(0,graph,m,v)) return true; return 0;}
0
gaurav_1k32 weeks ago
//working code
bool isPossibleToColor(int node,int color[],bool graph[101][101],int V,int col){
for(int i=0;i<V;i++){
if(i!=node and graph[node][i]==1 and color[i]==col)
return false;
}
return true;
}
bool solve(int node ,bool graph[101][101],int m, int V,int color[]){
if(node==V) return true;
for(int i=1;i<=m;i++){
if(isPossibleToColor(node,color,graph,V,i)){
color[node] = i;
if(solve(node+1,graph,m,V,color)) return true;
color[node] = 0;
}
}
return false;
}
bool graphColoring(bool graph[101][101], int m, int V)
{
// your code here
int color[V] = {0};
if(solve(0,graph,m,V,color)==true) return true;
return false;
}
0
khanarshad26002 weeks ago
Easy Java Solution _________
public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m){ if(i == G.length) return true; for(int c=1; c<=m; c++){ if(isSafe(G, color, i, c)){ color[i] = c; if(graphColoring(G, color, i+1, m)) return true; color[i] = 0; } } return false; } public static boolean isSafe(List<Integer>[] G, int[] color, int i, int c){ for(int adj : G[i]){ if(color[adj] == c) return false; } return true; }
0
sunboykenneth2 weeks ago
bool graphColoringImpl (bool graph[101][101], int M, int V, int curVertice, vector<int>& verticeColors)
{
if (curVertice == V) {
return true;
}
vector<bool> colorAvailable = vector<bool>(M, true);
for (int i = 0; i < curVertice; i++) {
if (graph[curVertice][i] == 0) {
continue;
}
colorAvailable[verticeColors[i]] = false;
}
// Use available colors for current vertice
for (int i = 0 ; i < M; i++) {
if (colorAvailable[i] == false) {
continue;
}
verticeColors[curVertice] = i;
if( graphColoringImpl(graph, M, V, curVertice + 1, verticeColors) == true) {
return true;
}
verticeColors[curVertice] = -1;
}
return false;
}
bool graphColoring(bool graph[101][101], int M, int V)
{
if (M == 0) {
return V == 0;
}
if (V <= M) {
return true;
}
vector<int> verticeColors = vector<int>(V, -1);
return graphColoringImpl(graph, M, V, 0, verticeColors);
}
-1
amateur_973 weeks ago
How is the site still popular beats me.
For the Java problem, atleast tell what the parameters are?!
0
devashishbakare3 weeks ago
JAVA Solution with comments
public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m)
{
return solve(G, color, i, m);
}
public static boolean solve(List<Integer>[] graph, int color[], int ind, int total_clr)
{
//base case
if(ind == graph.length)
return true;
//explore all the color
for(int i = 1 ; i <= total_clr ; i++ )
{
//check whether a color is assign to adjacent or not
if(check(ind, graph, color, i))
{
//its safe to add this color so we need to add this color
color[ind] = i;
//call to its adjacent to check next color on there index
if(solve(graph, color, ind+1, total_clr) == true) return true;
//if not possible this color remove that color
color[ind] = 0;
}
}
//by exploring all the option we still not return result then return false;
return false;
}
public static boolean check(int ind, List<Integer> []graph, int color[], int col)
{
//we have a color then we have to check the adjacent have same color or not
for(int i :graph[ind])
{
if(color[i] == col)
//if yes return false saying this color your pass not possible
return false;
}
//if adjacent not have the same color then return a true
return true;
}
0
avinashdhn19043 weeks ago
// C++ solution
bool isSafe(int node,bool graph[101][101],int color[],int n,int col){
for(int i=0;i<n;i++){
if((i!=node)&&graph[node][i]&&color[i]==col)return false;
}
return true;
}
bool solve(int node,bool graph[101][101],int color[],int n,int m){
if(node==n)return true;
for(int i=1;i<=m;i++){
if(isSafe(node,graph,color,n,i)){
color[node]=i;
if(solve(node+1,graph,color,n,m))return true;
color[node]=0;
}
}
return false;
}
bool graphColoring(bool graph[101][101], int m, int V)
{
int n=V;
int color[n];
memset(color,0,sizeof(color));
return solve(0,graph,color,n,m);
}
0
asissrmakumar6661 month ago
JAVA | BackTracking
class solve {
public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m) {
return check(i,G.length,G,color,m);
}
public static boolean check(int node,int n,List<Integer> []G,int []color,int m){
if(node==n) return true;
for(int i=1;i<=m;i++){
if(isPossible(i,G,node,color)){
color[node]=i;
if(check(node+1,n,G,color,m)) return true;
color[node]=0;
}
}
return false;
}
public static boolean isPossible(int clr,List<Integer> []G,int node,int []color){
for(int k:G[node]){
if(color[k]==clr) return false;
}
return true;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 561,
"s": 226,
"text": "Given an undirected graph and an integer M. The task is to determine if the graph can be colored with at most M colors such that no two adjacent vertices of the graph are colored with the same color. Here coloring of a graph means the assignment of colors to all vertices. Print 1 if it is possible to colour vertices and 0 otherwise."
},
{
"code": null,
"e": 572,
"s": 561,
"text": "Example 1:"
},
{
"code": null,
"e": 721,
"s": 572,
"text": "Input:\nN = 4\nM = 3\nE = 5\nEdges[] = {(0,1),(1,2),(2,3),(3,0),(0,2)}\nOutput: 1\nExplanation: It is possible to colour the\ngiven graph using 3 colours.\n"
},
{
"code": null,
"e": 732,
"s": 721,
"text": "Example 2:"
},
{
"code": null,
"e": 797,
"s": 732,
"text": "Input:\nN = 3\nM = 2\nE = 3\nEdges[] = {(0,1),(1,2),(0,2)}\nOutput: 0"
},
{
"code": null,
"e": 1455,
"s": 797,
"text": "Your Task:\nYour task is to complete the function graphColoring() which takes the 2d-array graph[], the number of colours and the number of nodes as inputs and returns true if answer exists otherwise false. 1 is printed if the returned value is true, 0 otherwise. The printing is done by the driver's code.\nNote: In Example there are Edges not the graph.Graph will be like, if there is an edge between vertex X and vertex Y graph[] will contain 1 at graph[X-1][Y-1], else 0. In 2d-array graph[ ], nodes are 0-based indexed, i.e. from 0 to N-1.Function will be contain 2-D graph not the edges.\n\nExpected Time Complexity: O(MN).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 1509,
"s": 1455,
"text": "Constraints:\n1 β€ N β€ 20\n1 β€ E β€ (N*(N-1))/2\n1 β€ M β€ N"
},
{
"code": null,
"e": 1511,
"s": 1509,
"text": "0"
},
{
"code": null,
"e": 1519,
"s": 1511,
"text": "ydahanh"
},
{
"code": null,
"e": 1545,
"s": 1519,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1547,
"s": 1545,
"text": "0"
},
{
"code": null,
"e": 1577,
"s": 1547,
"text": "milindprajapatmst194 days ago"
},
{
"code": null,
"e": 1605,
"s": 1577,
"text": "Total Time Taken: 0.04/1.06"
},
{
"code": null,
"e": 1615,
"s": 1605,
"text": "Idea: dfs"
},
{
"code": null,
"e": 2292,
"s": 1617,
"text": "const int N = 20;\nint color[N];\n\nbool check(int u, int n, int c, bool graph[101][101]) {\n for (int v = 0; v < n; v++) {\n if (u != v && graph[u][v] && color[v] == c)\n return true;\n }\n return false;\n}\n\nbool help(int u, int n, int m, bool graph[101][101]) {\n if (u == n)\n return true;\n for (int c = 0; c < m; c++) {\n if (check(u, n, c, graph))\n continue;\n color[u] = c;\n if (help(u + 1, n, m, graph))\n return true;\n color[u] = -1;\n }\n return false;\n}\n\nbool graphColoring(bool graph[101][101], int m, int n) {\n memset(color, -1, sizeof(color));\n return help(0, n, m, graph);\n}"
},
{
"code": null,
"e": 2295,
"s": 2292,
"text": "+1"
},
{
"code": null,
"e": 2323,
"s": 2295,
"text": "akshu199bhardwaj2 weeks ago"
},
{
"code": null,
"e": 2383,
"s": 2323,
"text": "Can anyone tell why all tcs are not passing with this code?"
},
{
"code": null,
"e": 2869,
"s": 2385,
"text": "int colour[101]={0};bool isvalid(int c, int n,bool graph[101][101], int m, int v){ for(int j=0; j<v; j++) { if(j!=n && graph[j][n]==1 && colour[j]==c) return false; } return true;}bool helper(int n, bool graph[101][101], int m, int v){ if(n==v) return 1; for(int i=1; i<=m; i++){ if(isvalid(i,n,graph,m,v)) { colour[n]=i; if(helper(n+1,graph,m,v)) return true; colour[n]=0; } }return false; }"
},
{
"code": null,
"e": 2975,
"s": 2869,
"text": "bool graphColoring(bool graph[101][101], int m, int v){ if(helper(0,graph,m,v)) return true; return 0;}"
},
{
"code": null,
"e": 2977,
"s": 2975,
"text": "0"
},
{
"code": null,
"e": 2999,
"s": 2977,
"text": "gaurav_1k32 weeks ago"
},
{
"code": null,
"e": 3231,
"s": 2999,
"text": "//working code\nbool isPossibleToColor(int node,int color[],bool graph[101][101],int V,int col){\n \n for(int i=0;i<V;i++){\n if(i!=node and graph[node][i]==1 and color[i]==col)\n return false;\n }\n return true;\n}"
},
{
"code": null,
"e": 3557,
"s": 3231,
"text": "bool solve(int node ,bool graph[101][101],int m, int V,int color[]){\n if(node==V) return true;\n \n for(int i=1;i<=m;i++){\n if(isPossibleToColor(node,color,graph,V,i)){\n color[node] = i;\n if(solve(node+1,graph,m,V,color)) return true;\n color[node] = 0;\n }\n }\n return false;\n}"
},
{
"code": null,
"e": 3729,
"s": 3557,
"text": "\nbool graphColoring(bool graph[101][101], int m, int V)\n{\n // your code here\n int color[V] = {0};\n if(solve(0,graph,m,V,color)==true) return true;\n return false;\n}"
},
{
"code": null,
"e": 3731,
"s": 3729,
"text": "0"
},
{
"code": null,
"e": 3757,
"s": 3731,
"text": "khanarshad26002 weeks ago"
},
{
"code": null,
"e": 3786,
"s": 3757,
"text": "Easy Java Solution _________"
},
{
"code": null,
"e": 4335,
"s": 3786,
"text": "public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m){ if(i == G.length) return true; for(int c=1; c<=m; c++){ if(isSafe(G, color, i, c)){ color[i] = c; if(graphColoring(G, color, i+1, m)) return true; color[i] = 0; } } return false; } public static boolean isSafe(List<Integer>[] G, int[] color, int i, int c){ for(int adj : G[i]){ if(color[adj] == c) return false; } return true; }"
},
{
"code": null,
"e": 4337,
"s": 4335,
"text": "0"
},
{
"code": null,
"e": 4362,
"s": 4337,
"text": "sunboykenneth2 weeks ago"
},
{
"code": null,
"e": 5442,
"s": 4362,
"text": "bool graphColoringImpl (bool graph[101][101], int M, int V, int curVertice, vector<int>& verticeColors)\n{\n if (curVertice == V) {\n return true;\n }\n \n vector<bool> colorAvailable = vector<bool>(M, true);\n for (int i = 0; i < curVertice; i++) {\n if (graph[curVertice][i] == 0) {\n continue;\n }\n \n colorAvailable[verticeColors[i]] = false;\n }\n \n // Use available colors for current vertice\n for (int i = 0 ; i < M; i++) {\n if (colorAvailable[i] == false) {\n continue;\n }\n \n verticeColors[curVertice] = i;\n if( graphColoringImpl(graph, M, V, curVertice + 1, verticeColors) == true) {\n return true;\n }\n verticeColors[curVertice] = -1;\n }\n \n return false;\n}\n\n\nbool graphColoring(bool graph[101][101], int M, int V)\n{\n if (M == 0) {\n return V == 0;\n }\n \n if (V <= M) {\n return true;\n }\n \n vector<int> verticeColors = vector<int>(V, -1);\n return graphColoringImpl(graph, M, V, 0, verticeColors);\n}"
},
{
"code": null,
"e": 5445,
"s": 5442,
"text": "-1"
},
{
"code": null,
"e": 5467,
"s": 5445,
"text": "amateur_973 weeks ago"
},
{
"code": null,
"e": 5507,
"s": 5467,
"text": "How is the site still popular beats me."
},
{
"code": null,
"e": 5568,
"s": 5507,
"text": "For the Java problem, atleast tell what the parameters are?!"
},
{
"code": null,
"e": 5570,
"s": 5568,
"text": "0"
},
{
"code": null,
"e": 5597,
"s": 5570,
"text": "devashishbakare3 weeks ago"
},
{
"code": null,
"e": 5625,
"s": 5597,
"text": "JAVA Solution with comments"
},
{
"code": null,
"e": 7118,
"s": 5627,
"text": "public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m) \n {\n return solve(G, color, i, m);\n }\n \n \n public static boolean solve(List<Integer>[] graph, int color[], int ind, int total_clr)\n {\n //base case\n if(ind == graph.length)\n return true;\n \n //explore all the color\n for(int i = 1 ; i <= total_clr ; i++ )\n {\n //check whether a color is assign to adjacent or not\n if(check(ind, graph, color, i))\n {\n //its safe to add this color so we need to add this color\n color[ind] = i;\n //call to its adjacent to check next color on there index\n if(solve(graph, color, ind+1, total_clr) == true) return true;\n //if not possible this color remove that color\n color[ind] = 0;\n }\n }\n \n //by exploring all the option we still not return result then return false;\n return false;\n }\n \n public static boolean check(int ind, List<Integer> []graph, int color[], int col)\n {\n //we have a color then we have to check the adjacent have same color or not\n for(int i :graph[ind])\n {\n if(color[i] == col)\n //if yes return false saying this color your pass not possible\n return false;\n }\n //if adjacent not have the same color then return a true\n return true;\n }"
},
{
"code": null,
"e": 7120,
"s": 7118,
"text": "0"
},
{
"code": null,
"e": 7146,
"s": 7120,
"text": "avinashdhn19043 weeks ago"
},
{
"code": null,
"e": 7836,
"s": 7146,
"text": "// C++ solution\n\nbool isSafe(int node,bool graph[101][101],int color[],int n,int col){\n \n for(int i=0;i<n;i++){\n if((i!=node)&&graph[node][i]&&color[i]==col)return false;\n }\n return true;\n}\nbool solve(int node,bool graph[101][101],int color[],int n,int m){\n if(node==n)return true;\n for(int i=1;i<=m;i++){\n if(isSafe(node,graph,color,n,i)){\n color[node]=i;\n if(solve(node+1,graph,color,n,m))return true;\n color[node]=0;\n }\n }\n return false;\n \n}\nbool graphColoring(bool graph[101][101], int m, int V)\n{\n int n=V;\n int color[n];\n memset(color,0,sizeof(color));\n return solve(0,graph,color,n,m);\n}"
},
{
"code": null,
"e": 7838,
"s": 7836,
"text": "0"
},
{
"code": null,
"e": 7866,
"s": 7838,
"text": "asissrmakumar6661 month ago"
},
{
"code": null,
"e": 7887,
"s": 7866,
"text": "JAVA | BackTracking "
},
{
"code": null,
"e": 8603,
"s": 7887,
"text": "class solve {\n public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m) {\n return check(i,G.length,G,color,m);\n }\n public static boolean check(int node,int n,List<Integer> []G,int []color,int m){\n if(node==n) return true;\n for(int i=1;i<=m;i++){\n if(isPossible(i,G,node,color)){\n color[node]=i;\n if(check(node+1,n,G,color,m)) return true;\n color[node]=0;\n }\n }\n return false;\n } \n public static boolean isPossible(int clr,List<Integer> []G,int node,int []color){\n for(int k:G[node]){\n if(color[k]==clr) return false;\n }\n return true;\n }\n}"
},
{
"code": null,
"e": 8749,
"s": 8603,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 8785,
"s": 8749,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8795,
"s": 8785,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8805,
"s": 8795,
"text": "\nContest\n"
},
{
"code": null,
"e": 8868,
"s": 8805,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9016,
"s": 8868,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9224,
"s": 9016,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 9330,
"s": 9224,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
10 tricks for a better Google Colab experience | by Cyprien NIELLY | Towards Data Science
|
Colab is a great tool for coding. I use it very often, for a large set of tasks, from traditional Machine Learning to Deep Learning applications using PyTorch, TensorFlow or OpenCV. With Google Colab, creating and sharing notebooks is intuitive and simple π
Here are 10 tips and tricks I gathered over time that will help you to get the most out of Google Colab.
Table of content:
Save time with keyboard shortcutsMount your Google Drive to ColabRun bash commandsUpload / download filesActivate GPU and TPULink Colab to GitHubStop Colab from disconnectingDisplay dataframes as interactive tablesUse TensorBoard with ColabChange display mode
Save time with keyboard shortcuts
Mount your Google Drive to Colab
Run bash commands
Upload / download files
Activate GPU and TPU
Link Colab to GitHub
Stop Colab from disconnecting
Display dataframes as interactive tables
Use TensorBoard with Colab
Change display mode
You can access all the shortcuts selecting βToolsβ β βKeyboard Shortcutsβ.
But here is a selection of my top 5:
Undo last action (inside a cell): ctrl + m + z
Find and replace: ctrl + m + h
Insert code cell above: ctrl + m + a
Insert code cell below: ctrl + m + b
Delete cell: ctrl + m + d
Be sure to check out other shortcuts and customize your favourite ones!
This feature is useful to get access to files that are stored on your Google Drive. It is also the perfect way to save your models and data. To do so, just enter the following code snippet:
from google.colab import drivedrive.mount('/content/gdrive')
The cell will return the following:
Click on the link, give Google Colab access to your Drive, and retrieve the authorization code. Paste it, and youβre done!
You are now able to access your Google Drive files under: /content/gdrive/My Drive/Use the batch comand !cd or the βFilesβ panel on the left.
Bash commands can be run by prefixing the command with β!β.Example:
Download dataset from the web with !wget <ENTER URL>
Install libraries with !pip install <LIBRARY>or !apt-get install <LIBRARY>
Run an existing .py script with !python script.py
Clone a git repository with !git clone <REPOSITORY URL>
To upload a file (or several) from your computer, run:
from google.colab import filesfiles.upload()
To download a file, run:
from google.colab import filesfiles.download('path/to/your/file')
Another way to do this is to use the file explorer on the left panel, with drags & drops.
β οΈ Be aware the files will disapear as soon as you leave Google Colab.
The default hardware of Google Colab is CPU. However you can enable GPU (and even TPU) support for more computationally demanding tasks like Deep Learning.
Click on: βRuntimeβ β βChange runtime typeβ β βHardware acceleratorβ. Then select the desired hardware.
You can easily check if the GPU is enabled by executing the following code:
import tensorflow as tftf.test.gpu_device_name()
To open a notebook hosted on GitHub, there are 3 options:
Go to https://colab.research.google.com switch to the GitHub tab and enter the URL of the notebook
The notebook carries an βOpen in Colabβ badge, which allows you to open it directly on Google Colab. The markdown code to insert into the README.md file is:
[](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
Use βOpen in Colabβ Chrome extension. After installation, whenever you find a Jupyter notebook in GitHub, click the icon of the plugin and it will open in Colab.
Follow: βFileβ β βSave a copy in GitHubβ. Once that is clicked it will ask for the authorization of your git account. Finally, you will be able to save the collaboratory notebook into the repository of your choice.
This is a big drawback of Google Colab, and Iβm sure a lot of you encountered this issue at least once. You decide to take a break, but when youβre back your notebook is disconnected!
Actually, Google Colab automatically disconnects the notebook if we leave it idle for more than 30 minutes. π
Open your Chrome DevTools by pressing F12 or ctrl+shift+i on Linux and enter the following JavaScript snippet in your console:
function KeepClicking(){console.log("Clicking");document.querySelector("colab-connect-button").click()}setInterval(KeepClicking,60000)
This function makes a click on the connect-button every 60 seconds. Thus, Colab thinks that the notebook is not idle and you donβt have to worry about being disconnected!
First, be aware that when you connect to a GPU, you are given a maximum of 12 hours at a time on the Cloud Machine.
Sometimes it happens that youβre being disconnected, even within this 12-hour time lapse. As explained in Colabβs FAQ: βColaboratory is intended for interactive use. Long-running background computations, particularly on GPUs, may be stopped.β π
Colab includes an extension that renders pandas dataframes into interactive tables that can be filtered, sorted, and explored dynamically.
Enable this extension with %load_ext google.colab.data_table and disable it with %unload_ext google.colab.data_table
TensorBoard is a tool for providing the measurements and visualizations needed during a Deep Learning workflow. It can be used directly within Colab. π π
Start by loading the TensorBoard notebook extension:
%load_ext tensorboard
Once your model is created, start TensorBoard within the notebook using:
%tensorboard --logdir logs
For more details, please check the Tensorflow tutorial on that topic.
Dark mode: a lot of people prefer this mode because is more relaxing for their eyes. You can activate it following βToolsβ β βSettingsβ β βThemeβ.
For cats & dogs lovers: yes, there is a Kitty and a Corgi mode. Go to βToolsβ β βSettingsβ β βMiscellaneousβ. Here, you can select the mode, and you will see your cats and dogs strolling on your screen! πΉ πΆ
I hope this article has been helpful and that you will keep using this wonderful and free tool. Please share your extra tips in the comments below. Happy coding!
For further reading, you can have a look at this very exhaustive blog post:
|
[
{
"code": null,
"e": 429,
"s": 171,
"text": "Colab is a great tool for coding. I use it very often, for a large set of tasks, from traditional Machine Learning to Deep Learning applications using PyTorch, TensorFlow or OpenCV. With Google Colab, creating and sharing notebooks is intuitive and simple π"
},
{
"code": null,
"e": 534,
"s": 429,
"text": "Here are 10 tips and tricks I gathered over time that will help you to get the most out of Google Colab."
},
{
"code": null,
"e": 552,
"s": 534,
"text": "Table of content:"
},
{
"code": null,
"e": 812,
"s": 552,
"text": "Save time with keyboard shortcutsMount your Google Drive to ColabRun bash commandsUpload / download filesActivate GPU and TPULink Colab to GitHubStop Colab from disconnectingDisplay dataframes as interactive tablesUse TensorBoard with ColabChange display mode"
},
{
"code": null,
"e": 846,
"s": 812,
"text": "Save time with keyboard shortcuts"
},
{
"code": null,
"e": 879,
"s": 846,
"text": "Mount your Google Drive to Colab"
},
{
"code": null,
"e": 897,
"s": 879,
"text": "Run bash commands"
},
{
"code": null,
"e": 921,
"s": 897,
"text": "Upload / download files"
},
{
"code": null,
"e": 942,
"s": 921,
"text": "Activate GPU and TPU"
},
{
"code": null,
"e": 963,
"s": 942,
"text": "Link Colab to GitHub"
},
{
"code": null,
"e": 993,
"s": 963,
"text": "Stop Colab from disconnecting"
},
{
"code": null,
"e": 1034,
"s": 993,
"text": "Display dataframes as interactive tables"
},
{
"code": null,
"e": 1061,
"s": 1034,
"text": "Use TensorBoard with Colab"
},
{
"code": null,
"e": 1081,
"s": 1061,
"text": "Change display mode"
},
{
"code": null,
"e": 1156,
"s": 1081,
"text": "You can access all the shortcuts selecting βToolsβ β βKeyboard Shortcutsβ."
},
{
"code": null,
"e": 1193,
"s": 1156,
"text": "But here is a selection of my top 5:"
},
{
"code": null,
"e": 1240,
"s": 1193,
"text": "Undo last action (inside a cell): ctrl + m + z"
},
{
"code": null,
"e": 1271,
"s": 1240,
"text": "Find and replace: ctrl + m + h"
},
{
"code": null,
"e": 1308,
"s": 1271,
"text": "Insert code cell above: ctrl + m + a"
},
{
"code": null,
"e": 1345,
"s": 1308,
"text": "Insert code cell below: ctrl + m + b"
},
{
"code": null,
"e": 1371,
"s": 1345,
"text": "Delete cell: ctrl + m + d"
},
{
"code": null,
"e": 1443,
"s": 1371,
"text": "Be sure to check out other shortcuts and customize your favourite ones!"
},
{
"code": null,
"e": 1633,
"s": 1443,
"text": "This feature is useful to get access to files that are stored on your Google Drive. It is also the perfect way to save your models and data. To do so, just enter the following code snippet:"
},
{
"code": null,
"e": 1694,
"s": 1633,
"text": "from google.colab import drivedrive.mount('/content/gdrive')"
},
{
"code": null,
"e": 1730,
"s": 1694,
"text": "The cell will return the following:"
},
{
"code": null,
"e": 1853,
"s": 1730,
"text": "Click on the link, give Google Colab access to your Drive, and retrieve the authorization code. Paste it, and youβre done!"
},
{
"code": null,
"e": 1995,
"s": 1853,
"text": "You are now able to access your Google Drive files under: /content/gdrive/My Drive/Use the batch comand !cd or the βFilesβ panel on the left."
},
{
"code": null,
"e": 2063,
"s": 1995,
"text": "Bash commands can be run by prefixing the command with β!β.Example:"
},
{
"code": null,
"e": 2116,
"s": 2063,
"text": "Download dataset from the web with !wget <ENTER URL>"
},
{
"code": null,
"e": 2191,
"s": 2116,
"text": "Install libraries with !pip install <LIBRARY>or !apt-get install <LIBRARY>"
},
{
"code": null,
"e": 2241,
"s": 2191,
"text": "Run an existing .py script with !python script.py"
},
{
"code": null,
"e": 2297,
"s": 2241,
"text": "Clone a git repository with !git clone <REPOSITORY URL>"
},
{
"code": null,
"e": 2352,
"s": 2297,
"text": "To upload a file (or several) from your computer, run:"
},
{
"code": null,
"e": 2397,
"s": 2352,
"text": "from google.colab import filesfiles.upload()"
},
{
"code": null,
"e": 2422,
"s": 2397,
"text": "To download a file, run:"
},
{
"code": null,
"e": 2488,
"s": 2422,
"text": "from google.colab import filesfiles.download('path/to/your/file')"
},
{
"code": null,
"e": 2578,
"s": 2488,
"text": "Another way to do this is to use the file explorer on the left panel, with drags & drops."
},
{
"code": null,
"e": 2649,
"s": 2578,
"text": "β οΈ Be aware the files will disapear as soon as you leave Google Colab."
},
{
"code": null,
"e": 2805,
"s": 2649,
"text": "The default hardware of Google Colab is CPU. However you can enable GPU (and even TPU) support for more computationally demanding tasks like Deep Learning."
},
{
"code": null,
"e": 2909,
"s": 2805,
"text": "Click on: βRuntimeβ β βChange runtime typeβ β βHardware acceleratorβ. Then select the desired hardware."
},
{
"code": null,
"e": 2985,
"s": 2909,
"text": "You can easily check if the GPU is enabled by executing the following code:"
},
{
"code": null,
"e": 3034,
"s": 2985,
"text": "import tensorflow as tftf.test.gpu_device_name()"
},
{
"code": null,
"e": 3092,
"s": 3034,
"text": "To open a notebook hosted on GitHub, there are 3 options:"
},
{
"code": null,
"e": 3191,
"s": 3092,
"text": "Go to https://colab.research.google.com switch to the GitHub tab and enter the URL of the notebook"
},
{
"code": null,
"e": 3348,
"s": 3191,
"text": "The notebook carries an βOpen in Colabβ badge, which allows you to open it directly on Google Colab. The markdown code to insert into the README.md file is:"
},
{
"code": null,
"e": 3536,
"s": 3348,
"text": "[](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)"
},
{
"code": null,
"e": 3698,
"s": 3536,
"text": "Use βOpen in Colabβ Chrome extension. After installation, whenever you find a Jupyter notebook in GitHub, click the icon of the plugin and it will open in Colab."
},
{
"code": null,
"e": 3913,
"s": 3698,
"text": "Follow: βFileβ β βSave a copy in GitHubβ. Once that is clicked it will ask for the authorization of your git account. Finally, you will be able to save the collaboratory notebook into the repository of your choice."
},
{
"code": null,
"e": 4097,
"s": 3913,
"text": "This is a big drawback of Google Colab, and Iβm sure a lot of you encountered this issue at least once. You decide to take a break, but when youβre back your notebook is disconnected!"
},
{
"code": null,
"e": 4207,
"s": 4097,
"text": "Actually, Google Colab automatically disconnects the notebook if we leave it idle for more than 30 minutes. π"
},
{
"code": null,
"e": 4334,
"s": 4207,
"text": "Open your Chrome DevTools by pressing F12 or ctrl+shift+i on Linux and enter the following JavaScript snippet in your console:"
},
{
"code": null,
"e": 4469,
"s": 4334,
"text": "function KeepClicking(){console.log(\"Clicking\");document.querySelector(\"colab-connect-button\").click()}setInterval(KeepClicking,60000)"
},
{
"code": null,
"e": 4640,
"s": 4469,
"text": "This function makes a click on the connect-button every 60 seconds. Thus, Colab thinks that the notebook is not idle and you donβt have to worry about being disconnected!"
},
{
"code": null,
"e": 4756,
"s": 4640,
"text": "First, be aware that when you connect to a GPU, you are given a maximum of 12 hours at a time on the Cloud Machine."
},
{
"code": null,
"e": 5001,
"s": 4756,
"text": "Sometimes it happens that youβre being disconnected, even within this 12-hour time lapse. As explained in Colabβs FAQ: βColaboratory is intended for interactive use. Long-running background computations, particularly on GPUs, may be stopped.β π"
},
{
"code": null,
"e": 5140,
"s": 5001,
"text": "Colab includes an extension that renders pandas dataframes into interactive tables that can be filtered, sorted, and explored dynamically."
},
{
"code": null,
"e": 5257,
"s": 5140,
"text": "Enable this extension with %load_ext google.colab.data_table and disable it with %unload_ext google.colab.data_table"
},
{
"code": null,
"e": 5411,
"s": 5257,
"text": "TensorBoard is a tool for providing the measurements and visualizations needed during a Deep Learning workflow. It can be used directly within Colab. π π"
},
{
"code": null,
"e": 5464,
"s": 5411,
"text": "Start by loading the TensorBoard notebook extension:"
},
{
"code": null,
"e": 5486,
"s": 5464,
"text": "%load_ext tensorboard"
},
{
"code": null,
"e": 5559,
"s": 5486,
"text": "Once your model is created, start TensorBoard within the notebook using:"
},
{
"code": null,
"e": 5586,
"s": 5559,
"text": "%tensorboard --logdir logs"
},
{
"code": null,
"e": 5656,
"s": 5586,
"text": "For more details, please check the Tensorflow tutorial on that topic."
},
{
"code": null,
"e": 5803,
"s": 5656,
"text": "Dark mode: a lot of people prefer this mode because is more relaxing for their eyes. You can activate it following βToolsβ β βSettingsβ β βThemeβ."
},
{
"code": null,
"e": 6010,
"s": 5803,
"text": "For cats & dogs lovers: yes, there is a Kitty and a Corgi mode. Go to βToolsβ β βSettingsβ β βMiscellaneousβ. Here, you can select the mode, and you will see your cats and dogs strolling on your screen! πΉ πΆ"
},
{
"code": null,
"e": 6172,
"s": 6010,
"text": "I hope this article has been helpful and that you will keep using this wonderful and free tool. Please share your extra tips in the comments below. Happy coding!"
}
] |
Understanding time complexity with Python examples | by Kelvin Salton do Prado | Towards Data Science
|
Nowadays, with all these data we consume and generate every single day, algorithms must be good enough to handle operations in large volumes of data.
In this post, we will understand a little more about time complexity, Big-O notation and why we need to be concerned about it when developing algorithms.
The examples shown in this story were developed in Python, so it will be easier to understand if you have at least the basic knowledge of Python, but this is not a prerequisite.
Letβs start understanding what is computational complexity.
Computational complexity is a field from computer science which analyzes algorithms based on the amount resources required for running it. The amount of required resources varies based on the input size, so the complexity is generally expressed as a function of n, where n is the size of the input.
It is important to note that when analyzing an algorithm we can consider the time complexity and space complexity. The space complexity is basically the amount of memory space required to solve a problem in relation to the input size. Even though the space complexity is important when analyzing an algorithm, in this story we will focus only on the time complexity.
As youβre reading this story right now, you may have an idea about what is time complexity, but to make sure weβre all on the same page, letβs start understanding what time complexity means with a short description from Wikipedia.
In computer science, the time complexity is the computational complexity that describes the amount of time it takes to run an algorithm. Time complexity is commonly estimated by counting the number of elementary operations performed by the algorithm, supposing that each elementary operation takes a fixed amount of time to perform.
When analyzing the time complexity of an algorithm we may find three cases: best-case, average-case and worst-case. Letβs understand what it means.
Suppose we have the following unsorted list [1, 5, 3, 9, 2, 4, 6, 7, 8] and we need to find the index of a value in this list using linear search.
best-case: this is the complexity of solving the problem for the best input. In our example, the best case would be to search for the value 1. Since this is the first value of the list, it would be found in the first iteration.
average-case: this is the average complexity of solving the problem. This complexity is defined with respect to the distribution of the values in the input data. Maybe this is not the best example but, based on our sample, we could say that the average-case would be when weβre searching for some value in the βmiddleβ of the list, for example, the value 2.
worst-case: this is the complexity of solving the problem for the worst input of size n. In our example, the worst-case would be to search for the value 8, which is the last element from the list.
Usually, when describing the time complexity of an algorithm, we are talking about the worst-case.
Ok, but how we describe the time complexity of an algorithm?
We use a mathematical notation called Big-O.
Big-O notation, sometimes called βasymptotic notationβ, is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity.
In computer science, Big-O notation is used to classify algorithms according to how their running time or space requirements grow as the input size (n) grows. This notation characterizes functions according to their growth rates: different functions with the same growth rate may be represented using the same O notation.
Letβs see some common time complexities described in the Big-O notation.
These are the most common time complexities expressed using the Big-O notation:
ββββββββββββββββββββ¦βββββββββββββββββββ Name β Time Complexity ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Constant Time β O(1) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Logarithmic Time β O(log n) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Linear Time β O(n) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Quasilinear Time β O(n log n) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Quadratic Time β O(n^2) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Exponential Time β O(2^n) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Factorial Time β O(n!) βββββββββββββββββββββ©ββββββββββββββββββ
Note that we will focus our study in these common time complexities but there are some other time complexities out there which you can study later.
As already said, we generally use the Big-O notation to describe the time complexity of algorithms. Thereβs a lot of math involved in the formal definition of the notation, but informally we can assume that the Big-O notation gives us the algorithmβs approximate run time in the worst case. When using the Big-O notation, we describe the algorithmβs efficiency based on the increasing size of the input data (n). For example, if the input is a string, the n will be the length of the string. If it is a list, the n will be the length of the list and so on.
Now, letβs go through each one of these common time complexities and see some examples of algorithms. Note that I tried to follow the following approach: present a little description, show a simple and understandable example and show a more complex example (usually from a real-world problem).
An algorithm is said to have a constant time when it is not dependent on the input data (n). No matter the size of the input data, the running time will always be the same. For example:
if a > b: return Trueelse: return False
Now, letβs take a look at the function get_first which returns the first element of a list:
def get_first(data): return data[0] if __name__ == '__main__': data = [1, 2, 9, 8, 3, 4, 7, 6, 5] print(get_first(data))
Independently of the input data size, it will always have the same running time since it only gets the first value from the list.
An algorithm with constant time complexity is excellent since we donβt need to worry about the input size.
An algorithm is said to have a logarithmic time complexity when it reduces the size of the input data in each step (it donβt need to look at all values of the input data), for example:
for index in range(0, len(data), 3): print(data[index])
Algorithms with logarithmic time complexity are commonly found in operations on binary trees or when using binary search. Letβs take a look at the example of a binary search, where we need to find the position of an element in a sorted list:
def binary_search(data, value): n = len(data) left = 0 right = n - 1 while left <= right: middle = (left + right) // 2 if value < data[middle]: right = middle - 1 elif value > data[middle]: left = middle + 1 else: return middle raise ValueError('Value is not in the list') if __name__ == '__main__': data = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(binary_search(data, 8))
Steps of the binary search:
Calculate the middle of the list.
If the searched value is lower than the value in the middle of the list, set a new right bounder.
If the searched value is higher than the value in the middle of the list, set a new left bounder.
If the search value is equal to the value in the middle of the list, return the middle (the index).
Repeat the steps above until the value is found or the left bounder is equal or higher the right bounder.
It is important to understand that an algorithm that must access all elements of its input data cannot take logarithmic time, as the time taken for reading input of size n is of the order of n.
An algorithm is said to have a linear time complexity when the running time increases at most linearly with the size of the input data. This is the best possible time complexity when the algorithm must examine all values in the input data. For example:
for value in data: print(value)
Letβs take a look at the example of a linear search, where we need to find the position of an element in an unsorted list:
def linear_search(data, value): for index in range(len(data)): if value == data[index]: return index raise ValueError('Value not found in the list') if __name__ == '__main__': data = [1, 2, 9, 8, 3, 4, 7, 6, 5] print(linear_search(data, 7))
Note that in this example, we need to look at all values in the list to find the value we are looking for.
An algorithm is said to have a quasilinear time complexity when each operation in the input data have a logarithm time complexity. It is commonly seen in sorting algorithms (e.g. mergesort, timsort, heapsort).
For example: for each value in the data1 (O(n)) use the binary search (O(log n)) to search the same value in data2.
for value in data1: result.append(binary_search(data2, value))
Another, more complex example, can be found in the Mergesort algorithm. Mergesort is an efficient, general-purpose, comparison-based sorting algorithm which has quasilinear time complexity, letβs see an example:
def merge_sort(data): if len(data) <= 1: return mid = len(data) // 2 left_data = data[:mid] right_data = data[mid:] merge_sort(left_data) merge_sort(right_data) left_index = 0 right_index = 0 data_index = 0 while left_index < len(left_data) and right_index < len(right_data): if left_data[left_index] < right_data[right_index]: data[data_index] = left_data[left_index] left_index += 1 else: data[data_index] = right_data[right_index] right_index += 1 data_index += 1 if left_index < len(left_data): del data[data_index:] data += left_data[left_index:] elif right_index < len(right_data): del data[data_index:] data += right_data[right_index:] if __name__ == '__main__': data = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] merge_sort(data) print(data)
The following image exemplifies the steps taken by the mergesort algorithm.
Note that in this example the sorting is being performed in-place.
An algorithm is said to have a quadratic time complexity when it needs to perform a linear time operation for each value in the input data, for example:
for x in data: for y in data: print(x, y)
Bubble sort is a great example of quadratic time complexity since for each value it needs to compare to all other values in the list, letβs see an example:
def bubble_sort(data): swapped = True while swapped: swapped = False for i in range(len(data)-1): if data[i] > data[i+1]: data[i], data[i+1] = data[i+1], data[i] swapped = True if __name__ == '__main__': data = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] bubble_sort(data) print(data)
An algorithm is said to have an exponential time complexity when the growth doubles with each addition to the input data set. This kind of time complexity is usually seen in brute-force algorithms.
As exemplified by Vicky Lai:
In cryptography, a brute-force attack may systematically check all possible elements of a password by iterating through subsets. Using an exponential algorithm to do this, it becomes incredibly resource-expensive to brute-force crack a long password versus a shorter one. This is one reason that a long password is considered more secure than a shorter one.
Another example of an exponential time algorithm is the recursive calculation of Fibonacci numbers:
def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2)
If you donβt know what a recursive function is, letβs clarify it quickly: a recursive function may be described as a function that calls itself in specific conditions. As you may have noticed, the time complexity of recursive functions is a little harder to define since it depends on how many times the function is called and the time complexity of a single function call.
It makes more sense when we look at the recursion tree. The following recursion tree was generated by the Fibonacci algorithm using n = 4:
Note that it will call itself until it reaches the leaves. When reaching the leaves it returns the value itself.
Now, look how the recursion tree grows just increasing the n to 6:
You can find a more complete explanation about the time complexity of the recursive Fibonacci algorithm here on StackOverflow.
An algorithm is said to have a factorial time complexity when it grows in a factorial way based on the size of the input data, for example:
2! = 2 x 1 = 23! = 3 x 2 x 1 = 64! = 4 x 3 x 2 x 1 = 245! = 5 x 4 x 3 x 2 x 1 = 1206! = 6 x 5 x 4 x 3 x 2 x 1 = 7207! = 7 x 6 x 5 x 4 x 3 x 2 x 1 = 5.0408! = 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 40.320
As you may see it grows very fast, even for a small size input.
A great example of an algorithm which has a factorial time complexity is the Heapβs algorithm, which is used for generating all possible permutations of n objects.
According to Wikipedia:
Heap found a systematic method for choosing at each step a pair of elements to switch, in order to produce every possible permutation of these elements exactly once.
Letβs take a look at the example:
def heap_permutation(data, n): if n == 1: print(data) return for i in range(n): heap_permutation(data, n - 1) if n % 2 == 0: data[i], data[n-1] = data[n-1], data[i] else: data[0], data[n-1] = data[n-1], data[0] if __name__ == '__main__': data = [1, 2, 3] heap_permutation(data, len(data))
The result will be:
[1, 2, 3][2, 1, 3][3, 1, 2][1, 3, 2][2, 3, 1][3, 2, 1]
Note that it will grow in a factorial way, based on the size of the input data, so we can say the algorithm has factorial time complexity O(n!).
Another great example is the Travelling Salesman Problem.
It is important to note that when analyzing the time complexity of an algorithm with several operations we need to describe the algorithm based on the largest complexity among all operations. For example:
def my_function(data): first_element = data[0] for value in data: print(value) for x in data: for y in data: print(x, y)
Even that the operations in βmy_functionβ donβt make sense we can see that it has multiple time complexities: O(1) + O(n) + O(n2). So, when increasing the size of the input data, the bottleneck of this algorithm will be the operation that takes O(n2). Based on this, we can describe the time complexity of this algorithm as O(n2).
To make your life easier, here you can find a sheet with the time complexity of the operations in the most common data structures.
Here is another sheet with the time complexity of the most common sorting algorithms.
If after reading all this story you still have some doubts about the importance of knowing time complexity and the Big-O notation, letβs clarify some points.
Even when working with modern languages, like Python, which provides built-in functions, like sorting algorithms, someday you will probably need to implement an algorithm to perform some kind of operation in a certain amount of data. By studying time complexity you will understand the important concept of efficiency and will be able to find bottlenecks in your code which should be improved, mainly when working with huge data sets.
Besides that, if you plan to apply to a software engineer position in a big company like Google, Facebook, Twitter, and Amazon you will need to be prepared to answer questions about time complexity using the Big-O notation.
Thanks for reading this story. I hope you have learned a little more about time complexity and the Big-O notation. If you enjoyed it, please give it a clap and share it. If you have any doubt or suggestion feel free to comment or send me an email. Also, feel free to follow me on Twitter, Linkedin, and Github.
Computational complexity: https://en.wikipedia.org/wiki/Computational_complexity
Big-O notation: https://en.wikipedia.org/wiki/Big_O_notation
Time complexity: https://en.wikipedia.org/wiki/Time_complexity
Big-O Cheat Sheet: http://bigocheatsheet.com/
A coffee-break introduction to time complexity of algorithms: https://vickylai.com/verbose/a-coffee-break-introduction-to-time-complexity-of-algorithms/
|
[
{
"code": null,
"e": 321,
"s": 171,
"text": "Nowadays, with all these data we consume and generate every single day, algorithms must be good enough to handle operations in large volumes of data."
},
{
"code": null,
"e": 475,
"s": 321,
"text": "In this post, we will understand a little more about time complexity, Big-O notation and why we need to be concerned about it when developing algorithms."
},
{
"code": null,
"e": 653,
"s": 475,
"text": "The examples shown in this story were developed in Python, so it will be easier to understand if you have at least the basic knowledge of Python, but this is not a prerequisite."
},
{
"code": null,
"e": 713,
"s": 653,
"text": "Letβs start understanding what is computational complexity."
},
{
"code": null,
"e": 1012,
"s": 713,
"text": "Computational complexity is a field from computer science which analyzes algorithms based on the amount resources required for running it. The amount of required resources varies based on the input size, so the complexity is generally expressed as a function of n, where n is the size of the input."
},
{
"code": null,
"e": 1379,
"s": 1012,
"text": "It is important to note that when analyzing an algorithm we can consider the time complexity and space complexity. The space complexity is basically the amount of memory space required to solve a problem in relation to the input size. Even though the space complexity is important when analyzing an algorithm, in this story we will focus only on the time complexity."
},
{
"code": null,
"e": 1610,
"s": 1379,
"text": "As youβre reading this story right now, you may have an idea about what is time complexity, but to make sure weβre all on the same page, letβs start understanding what time complexity means with a short description from Wikipedia."
},
{
"code": null,
"e": 1943,
"s": 1610,
"text": "In computer science, the time complexity is the computational complexity that describes the amount of time it takes to run an algorithm. Time complexity is commonly estimated by counting the number of elementary operations performed by the algorithm, supposing that each elementary operation takes a fixed amount of time to perform."
},
{
"code": null,
"e": 2091,
"s": 1943,
"text": "When analyzing the time complexity of an algorithm we may find three cases: best-case, average-case and worst-case. Letβs understand what it means."
},
{
"code": null,
"e": 2238,
"s": 2091,
"text": "Suppose we have the following unsorted list [1, 5, 3, 9, 2, 4, 6, 7, 8] and we need to find the index of a value in this list using linear search."
},
{
"code": null,
"e": 2466,
"s": 2238,
"text": "best-case: this is the complexity of solving the problem for the best input. In our example, the best case would be to search for the value 1. Since this is the first value of the list, it would be found in the first iteration."
},
{
"code": null,
"e": 2824,
"s": 2466,
"text": "average-case: this is the average complexity of solving the problem. This complexity is defined with respect to the distribution of the values in the input data. Maybe this is not the best example but, based on our sample, we could say that the average-case would be when weβre searching for some value in the βmiddleβ of the list, for example, the value 2."
},
{
"code": null,
"e": 3021,
"s": 2824,
"text": "worst-case: this is the complexity of solving the problem for the worst input of size n. In our example, the worst-case would be to search for the value 8, which is the last element from the list."
},
{
"code": null,
"e": 3120,
"s": 3021,
"text": "Usually, when describing the time complexity of an algorithm, we are talking about the worst-case."
},
{
"code": null,
"e": 3181,
"s": 3120,
"text": "Ok, but how we describe the time complexity of an algorithm?"
},
{
"code": null,
"e": 3226,
"s": 3181,
"text": "We use a mathematical notation called Big-O."
},
{
"code": null,
"e": 3424,
"s": 3226,
"text": "Big-O notation, sometimes called βasymptotic notationβ, is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity."
},
{
"code": null,
"e": 3746,
"s": 3424,
"text": "In computer science, Big-O notation is used to classify algorithms according to how their running time or space requirements grow as the input size (n) grows. This notation characterizes functions according to their growth rates: different functions with the same growth rate may be represented using the same O notation."
},
{
"code": null,
"e": 3819,
"s": 3746,
"text": "Letβs see some common time complexities described in the Big-O notation."
},
{
"code": null,
"e": 3899,
"s": 3819,
"text": "These are the most common time complexities expressed using the Big-O notation:"
},
{
"code": null,
"e": 4546,
"s": 3899,
"text": "ββββββββββββββββββββ¦βββββββββββββββββββ Name β Time Complexity ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Constant Time β O(1) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Logarithmic Time β O(log n) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Linear Time β O(n) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Quasilinear Time β O(n log n) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Quadratic Time β O(n^2) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Exponential Time β O(2^n) ββ βββββββββββββββββββ¬ββββββββββββββββββ£β Factorial Time β O(n!) βββββββββββββββββββββ©ββββββββββββββββββ"
},
{
"code": null,
"e": 4694,
"s": 4546,
"text": "Note that we will focus our study in these common time complexities but there are some other time complexities out there which you can study later."
},
{
"code": null,
"e": 5251,
"s": 4694,
"text": "As already said, we generally use the Big-O notation to describe the time complexity of algorithms. Thereβs a lot of math involved in the formal definition of the notation, but informally we can assume that the Big-O notation gives us the algorithmβs approximate run time in the worst case. When using the Big-O notation, we describe the algorithmβs efficiency based on the increasing size of the input data (n). For example, if the input is a string, the n will be the length of the string. If it is a list, the n will be the length of the list and so on."
},
{
"code": null,
"e": 5545,
"s": 5251,
"text": "Now, letβs go through each one of these common time complexities and see some examples of algorithms. Note that I tried to follow the following approach: present a little description, show a simple and understandable example and show a more complex example (usually from a real-world problem)."
},
{
"code": null,
"e": 5731,
"s": 5545,
"text": "An algorithm is said to have a constant time when it is not dependent on the input data (n). No matter the size of the input data, the running time will always be the same. For example:"
},
{
"code": null,
"e": 5777,
"s": 5731,
"text": "if a > b: return Trueelse: return False"
},
{
"code": null,
"e": 5869,
"s": 5777,
"text": "Now, letβs take a look at the function get_first which returns the first element of a list:"
},
{
"code": null,
"e": 6002,
"s": 5869,
"text": "def get_first(data): return data[0] if __name__ == '__main__': data = [1, 2, 9, 8, 3, 4, 7, 6, 5] print(get_first(data))"
},
{
"code": null,
"e": 6132,
"s": 6002,
"text": "Independently of the input data size, it will always have the same running time since it only gets the first value from the list."
},
{
"code": null,
"e": 6239,
"s": 6132,
"text": "An algorithm with constant time complexity is excellent since we donβt need to worry about the input size."
},
{
"code": null,
"e": 6424,
"s": 6239,
"text": "An algorithm is said to have a logarithmic time complexity when it reduces the size of the input data in each step (it donβt need to look at all values of the input data), for example:"
},
{
"code": null,
"e": 6483,
"s": 6424,
"text": "for index in range(0, len(data), 3): print(data[index])"
},
{
"code": null,
"e": 6725,
"s": 6483,
"text": "Algorithms with logarithmic time complexity are commonly found in operations on binary trees or when using binary search. Letβs take a look at the example of a binary search, where we need to find the position of an element in a sorted list:"
},
{
"code": null,
"e": 7175,
"s": 6725,
"text": "def binary_search(data, value): n = len(data) left = 0 right = n - 1 while left <= right: middle = (left + right) // 2 if value < data[middle]: right = middle - 1 elif value > data[middle]: left = middle + 1 else: return middle raise ValueError('Value is not in the list') if __name__ == '__main__': data = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(binary_search(data, 8))"
},
{
"code": null,
"e": 7203,
"s": 7175,
"text": "Steps of the binary search:"
},
{
"code": null,
"e": 7237,
"s": 7203,
"text": "Calculate the middle of the list."
},
{
"code": null,
"e": 7335,
"s": 7237,
"text": "If the searched value is lower than the value in the middle of the list, set a new right bounder."
},
{
"code": null,
"e": 7433,
"s": 7335,
"text": "If the searched value is higher than the value in the middle of the list, set a new left bounder."
},
{
"code": null,
"e": 7533,
"s": 7433,
"text": "If the search value is equal to the value in the middle of the list, return the middle (the index)."
},
{
"code": null,
"e": 7639,
"s": 7533,
"text": "Repeat the steps above until the value is found or the left bounder is equal or higher the right bounder."
},
{
"code": null,
"e": 7833,
"s": 7639,
"text": "It is important to understand that an algorithm that must access all elements of its input data cannot take logarithmic time, as the time taken for reading input of size n is of the order of n."
},
{
"code": null,
"e": 8086,
"s": 7833,
"text": "An algorithm is said to have a linear time complexity when the running time increases at most linearly with the size of the input data. This is the best possible time complexity when the algorithm must examine all values in the input data. For example:"
},
{
"code": null,
"e": 8121,
"s": 8086,
"text": "for value in data: print(value)"
},
{
"code": null,
"e": 8244,
"s": 8121,
"text": "Letβs take a look at the example of a linear search, where we need to find the position of an element in an unsorted list:"
},
{
"code": null,
"e": 8518,
"s": 8244,
"text": "def linear_search(data, value): for index in range(len(data)): if value == data[index]: return index raise ValueError('Value not found in the list') if __name__ == '__main__': data = [1, 2, 9, 8, 3, 4, 7, 6, 5] print(linear_search(data, 7))"
},
{
"code": null,
"e": 8625,
"s": 8518,
"text": "Note that in this example, we need to look at all values in the list to find the value we are looking for."
},
{
"code": null,
"e": 8835,
"s": 8625,
"text": "An algorithm is said to have a quasilinear time complexity when each operation in the input data have a logarithm time complexity. It is commonly seen in sorting algorithms (e.g. mergesort, timsort, heapsort)."
},
{
"code": null,
"e": 8951,
"s": 8835,
"text": "For example: for each value in the data1 (O(n)) use the binary search (O(log n)) to search the same value in data2."
},
{
"code": null,
"e": 9017,
"s": 8951,
"text": "for value in data1: result.append(binary_search(data2, value))"
},
{
"code": null,
"e": 9229,
"s": 9017,
"text": "Another, more complex example, can be found in the Mergesort algorithm. Mergesort is an efficient, general-purpose, comparison-based sorting algorithm which has quasilinear time complexity, letβs see an example:"
},
{
"code": null,
"e": 10134,
"s": 9229,
"text": "def merge_sort(data): if len(data) <= 1: return mid = len(data) // 2 left_data = data[:mid] right_data = data[mid:] merge_sort(left_data) merge_sort(right_data) left_index = 0 right_index = 0 data_index = 0 while left_index < len(left_data) and right_index < len(right_data): if left_data[left_index] < right_data[right_index]: data[data_index] = left_data[left_index] left_index += 1 else: data[data_index] = right_data[right_index] right_index += 1 data_index += 1 if left_index < len(left_data): del data[data_index:] data += left_data[left_index:] elif right_index < len(right_data): del data[data_index:] data += right_data[right_index:] if __name__ == '__main__': data = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] merge_sort(data) print(data)"
},
{
"code": null,
"e": 10210,
"s": 10134,
"text": "The following image exemplifies the steps taken by the mergesort algorithm."
},
{
"code": null,
"e": 10277,
"s": 10210,
"text": "Note that in this example the sorting is being performed in-place."
},
{
"code": null,
"e": 10430,
"s": 10277,
"text": "An algorithm is said to have a quadratic time complexity when it needs to perform a linear time operation for each value in the input data, for example:"
},
{
"code": null,
"e": 10482,
"s": 10430,
"text": "for x in data: for y in data: print(x, y)"
},
{
"code": null,
"e": 10638,
"s": 10482,
"text": "Bubble sort is a great example of quadratic time complexity since for each value it needs to compare to all other values in the list, letβs see an example:"
},
{
"code": null,
"e": 10983,
"s": 10638,
"text": "def bubble_sort(data): swapped = True while swapped: swapped = False for i in range(len(data)-1): if data[i] > data[i+1]: data[i], data[i+1] = data[i+1], data[i] swapped = True if __name__ == '__main__': data = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] bubble_sort(data) print(data)"
},
{
"code": null,
"e": 11181,
"s": 10983,
"text": "An algorithm is said to have an exponential time complexity when the growth doubles with each addition to the input data set. This kind of time complexity is usually seen in brute-force algorithms."
},
{
"code": null,
"e": 11210,
"s": 11181,
"text": "As exemplified by Vicky Lai:"
},
{
"code": null,
"e": 11568,
"s": 11210,
"text": "In cryptography, a brute-force attack may systematically check all possible elements of a password by iterating through subsets. Using an exponential algorithm to do this, it becomes incredibly resource-expensive to brute-force crack a long password versus a shorter one. This is one reason that a long password is considered more secure than a shorter one."
},
{
"code": null,
"e": 11668,
"s": 11568,
"text": "Another example of an exponential time algorithm is the recursive calculation of Fibonacci numbers:"
},
{
"code": null,
"e": 11758,
"s": 11668,
"text": "def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2)"
},
{
"code": null,
"e": 12132,
"s": 11758,
"text": "If you donβt know what a recursive function is, letβs clarify it quickly: a recursive function may be described as a function that calls itself in specific conditions. As you may have noticed, the time complexity of recursive functions is a little harder to define since it depends on how many times the function is called and the time complexity of a single function call."
},
{
"code": null,
"e": 12271,
"s": 12132,
"text": "It makes more sense when we look at the recursion tree. The following recursion tree was generated by the Fibonacci algorithm using n = 4:"
},
{
"code": null,
"e": 12384,
"s": 12271,
"text": "Note that it will call itself until it reaches the leaves. When reaching the leaves it returns the value itself."
},
{
"code": null,
"e": 12451,
"s": 12384,
"text": "Now, look how the recursion tree grows just increasing the n to 6:"
},
{
"code": null,
"e": 12578,
"s": 12451,
"text": "You can find a more complete explanation about the time complexity of the recursive Fibonacci algorithm here on StackOverflow."
},
{
"code": null,
"e": 12718,
"s": 12578,
"text": "An algorithm is said to have a factorial time complexity when it grows in a factorial way based on the size of the input data, for example:"
},
{
"code": null,
"e": 12915,
"s": 12718,
"text": "2! = 2 x 1 = 23! = 3 x 2 x 1 = 64! = 4 x 3 x 2 x 1 = 245! = 5 x 4 x 3 x 2 x 1 = 1206! = 6 x 5 x 4 x 3 x 2 x 1 = 7207! = 7 x 6 x 5 x 4 x 3 x 2 x 1 = 5.0408! = 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 40.320"
},
{
"code": null,
"e": 12979,
"s": 12915,
"text": "As you may see it grows very fast, even for a small size input."
},
{
"code": null,
"e": 13143,
"s": 12979,
"text": "A great example of an algorithm which has a factorial time complexity is the Heapβs algorithm, which is used for generating all possible permutations of n objects."
},
{
"code": null,
"e": 13167,
"s": 13143,
"text": "According to Wikipedia:"
},
{
"code": null,
"e": 13333,
"s": 13167,
"text": "Heap found a systematic method for choosing at each step a pair of elements to switch, in order to produce every possible permutation of these elements exactly once."
},
{
"code": null,
"e": 13367,
"s": 13333,
"text": "Letβs take a look at the example:"
},
{
"code": null,
"e": 13732,
"s": 13367,
"text": "def heap_permutation(data, n): if n == 1: print(data) return for i in range(n): heap_permutation(data, n - 1) if n % 2 == 0: data[i], data[n-1] = data[n-1], data[i] else: data[0], data[n-1] = data[n-1], data[0] if __name__ == '__main__': data = [1, 2, 3] heap_permutation(data, len(data))"
},
{
"code": null,
"e": 13752,
"s": 13732,
"text": "The result will be:"
},
{
"code": null,
"e": 13807,
"s": 13752,
"text": "[1, 2, 3][2, 1, 3][3, 1, 2][1, 3, 2][2, 3, 1][3, 2, 1]"
},
{
"code": null,
"e": 13952,
"s": 13807,
"text": "Note that it will grow in a factorial way, based on the size of the input data, so we can say the algorithm has factorial time complexity O(n!)."
},
{
"code": null,
"e": 14010,
"s": 13952,
"text": "Another great example is the Travelling Salesman Problem."
},
{
"code": null,
"e": 14215,
"s": 14010,
"text": "It is important to note that when analyzing the time complexity of an algorithm with several operations we need to describe the algorithm based on the largest complexity among all operations. For example:"
},
{
"code": null,
"e": 14378,
"s": 14215,
"text": "def my_function(data): first_element = data[0] for value in data: print(value) for x in data: for y in data: print(x, y)"
},
{
"code": null,
"e": 14709,
"s": 14378,
"text": "Even that the operations in βmy_functionβ donβt make sense we can see that it has multiple time complexities: O(1) + O(n) + O(n2). So, when increasing the size of the input data, the bottleneck of this algorithm will be the operation that takes O(n2). Based on this, we can describe the time complexity of this algorithm as O(n2)."
},
{
"code": null,
"e": 14840,
"s": 14709,
"text": "To make your life easier, here you can find a sheet with the time complexity of the operations in the most common data structures."
},
{
"code": null,
"e": 14926,
"s": 14840,
"text": "Here is another sheet with the time complexity of the most common sorting algorithms."
},
{
"code": null,
"e": 15084,
"s": 14926,
"text": "If after reading all this story you still have some doubts about the importance of knowing time complexity and the Big-O notation, letβs clarify some points."
},
{
"code": null,
"e": 15519,
"s": 15084,
"text": "Even when working with modern languages, like Python, which provides built-in functions, like sorting algorithms, someday you will probably need to implement an algorithm to perform some kind of operation in a certain amount of data. By studying time complexity you will understand the important concept of efficiency and will be able to find bottlenecks in your code which should be improved, mainly when working with huge data sets."
},
{
"code": null,
"e": 15743,
"s": 15519,
"text": "Besides that, if you plan to apply to a software engineer position in a big company like Google, Facebook, Twitter, and Amazon you will need to be prepared to answer questions about time complexity using the Big-O notation."
},
{
"code": null,
"e": 16054,
"s": 15743,
"text": "Thanks for reading this story. I hope you have learned a little more about time complexity and the Big-O notation. If you enjoyed it, please give it a clap and share it. If you have any doubt or suggestion feel free to comment or send me an email. Also, feel free to follow me on Twitter, Linkedin, and Github."
},
{
"code": null,
"e": 16135,
"s": 16054,
"text": "Computational complexity: https://en.wikipedia.org/wiki/Computational_complexity"
},
{
"code": null,
"e": 16196,
"s": 16135,
"text": "Big-O notation: https://en.wikipedia.org/wiki/Big_O_notation"
},
{
"code": null,
"e": 16259,
"s": 16196,
"text": "Time complexity: https://en.wikipedia.org/wiki/Time_complexity"
},
{
"code": null,
"e": 16305,
"s": 16259,
"text": "Big-O Cheat Sheet: http://bigocheatsheet.com/"
}
] |
MySQL - SHOW EVENTS Statement
|
A MySQL Event is nothing but a task that execute at a particular schedule. An event can contain one or more MySQL statements these statements are stored in the databases and gets executed at the specified schedule.
The SHOW EVENTS statement lists (information about) the events in the specified schema.
Following is the syntax of the MySQL SHOW EVENTS statement β
SHOW EVENTS
[{FROM | IN} schema_name]
[LIKE 'pattern' | WHERE expr]
Assume we have created a table with name data and create an event which inserts records into it.
mysql> CREATE TABLE Data (Name VARCHAR(255), age INT);
mysql> CREATE EVENT sample_event ON SCHEDULE EVERY 1 MONTH DO TRUNCATE TABLE data;
Following query lists the events in the current database β
mysql> SHOW EVENTS;
+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | Originator | character_set_client | collation_connection | Database Collation |
+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
| test | sample_event | root@localhost | SYSTEM | RECURRING | NULL | 1 | MONTH | 2021-03-20 10:47:00 | NULL | ENABLED | 1 | cp850 | cp850_general_ci | utf8mb4_0900_ai_ci |
+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
1 row in set (0.10 sec)
You can retrieve the description of events from a specific database using the FROM clause.
Assume we have created a database named demo using the CREATE DATABASE statement β
mysql> CREATE DATABASE demo;
Query OK, 1 row affected (0.18 sec)
Now, let us create a table in it, using the CREATE TABLE statement β
mysql> CREATE TABLE demo.Data (Name VARCHAR(255), age INT);
Query OK, 0 rows affected (0.51 sec)
Let us create two events with names example_event1 and example_event2 it inserts a record in the above created table one minute after the execution β
mysql> CREATE EVENT demo.example_event ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 Hour DO INSERT INTO new.Data VALUES('Rahman', 25);
Query OK, 0 rows affected (0.13 sec)
mysql> CREATE EVENT demo.event_hourly ON SCHEDULE EVERY 1 MONTH DO TRUNCATE TABLE data;
Query OK, 0 rows affected (0.21 sec)
Following query lists out all the (upcoming) events in the database named demo β
mysql> SHOW EVENTS FROM demo\G;
*************************** 1. row ***************************
Db: demo
Name: event_hourly
Definer: root@localhost
Time zone: SYSTEM
Type: RECURRING
Execute at: NULL
Interval value: 1
Interval field: MONTH
Starts: 2021-05-12 22:13:53
Ends: NULL
Status: ENABLED
Originator: 1
character_set_client: utf8mb4
collation_connection: utf8mb4_0900_ai_ci
Database Collation: utf8mb4_0900_ai_ci
*************************** 2. row ***************************
Db: demo
Name: example_event
Definer: root@localhost
Time zone: SYSTEM
Type: ONE TIME
Execute at: 2021-05-12 23:13:10
Interval value: NULL
Interval field: NULL
Starts: NULL
Ends: NULL
Status: ENABLED
Originator: 1
character_set_client: utf8mb4
collation_connection: utf8mb4_0900_ai_ci
Database Collation: utf8mb4_0900_ai_ci
2 rows in set (0.26 sec)
You can also use the IN clause instead of FROM as β
mysql> SHOW EVENTS IN demo;
+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | Originator | character_set_client | collation_connection | Database Collation |
+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
| demo | event_hourly | root@localhost | SYSTEM | RECURRING | NULL | 1 | MONTH | 2021-05-12 22:13:53 | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |
| demo | example_event | root@localhost | SYSTEM | ONE TIME | 2021-05-12 23:13:10 | NULL | NULL | NULL | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |
+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
2 rows in set (0.00 sec)
Using the LIKE clause, you can specify a pattern to retrieve specific tables. Following query retrieves the information about the events whose name starts with the letter "e".
mysql> SHOW EVENTS LIKE 'e%';
+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | Originator | character_set_client | collation_connection | Database Collation |
+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
| demo | event_hourly | root@localhost | SYSTEM | RECURRING | NULL | 1 | MONTH | 2021-05-12 22:13:53 | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |
| demo | example_event | root@localhost | SYSTEM | ONE TIME | 2021-05-13 17:24:46 | NULL | NULL | NULL | NULL | ENABLED | 1 | cp850 | cp850_general_ci | utf8mb4_0900_ai_ci |
+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
2 rows in set (0.07 sec)
You can use the WHERE clause of the SHOW EVENTS statements to retrieve names of the tables which match the specified condition.
Following query lists out event which is of type recurring from the database named demo. Here we are using the SHOW EVENTS statement with WHERE clause.
mysql> SHOW EVENTS FROM demo WHERE Type = 'RECURRING';
+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | Originator | character_set_client | collation_connection | Database Collation |
+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
| demo | event_hourly | root@localhost | SYSTEM | RECURRING | NULL | 1 | MONTH | 2021-05-12 22:13:53 | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |
+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2548,
"s": 2333,
"text": "A MySQL Event is nothing but a task that execute at a particular schedule. An event can contain one or more MySQL statements these statements are stored in the databases and gets executed at the specified schedule."
},
{
"code": null,
"e": 2636,
"s": 2548,
"text": "The SHOW EVENTS statement lists (information about) the events in the specified schema."
},
{
"code": null,
"e": 2697,
"s": 2636,
"text": "Following is the syntax of the MySQL SHOW EVENTS statement β"
},
{
"code": null,
"e": 2772,
"s": 2697,
"text": "SHOW EVENTS\n [{FROM | IN} schema_name]\n [LIKE 'pattern' | WHERE expr]\n"
},
{
"code": null,
"e": 2869,
"s": 2772,
"text": "Assume we have created a table with name data and create an event which inserts records into it."
},
{
"code": null,
"e": 3007,
"s": 2869,
"text": "mysql> CREATE TABLE Data (Name VARCHAR(255), age INT);\nmysql> CREATE EVENT sample_event ON SCHEDULE EVERY 1 MONTH DO TRUNCATE TABLE data;"
},
{
"code": null,
"e": 3066,
"s": 3007,
"text": "Following query lists the events in the current database β"
},
{
"code": null,
"e": 4265,
"s": 3066,
"text": "mysql> SHOW EVENTS;\n+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | Originator | character_set_client | collation_connection | Database Collation |\n+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n| test | sample_event | root@localhost | SYSTEM | RECURRING | NULL | 1 | MONTH | 2021-03-20 10:47:00 | NULL | ENABLED | 1 | cp850 | cp850_general_ci | utf8mb4_0900_ai_ci |\n+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n1 row in set (0.10 sec)"
},
{
"code": null,
"e": 4356,
"s": 4265,
"text": "You can retrieve the description of events from a specific database using the FROM clause."
},
{
"code": null,
"e": 4439,
"s": 4356,
"text": "Assume we have created a database named demo using the CREATE DATABASE statement β"
},
{
"code": null,
"e": 4504,
"s": 4439,
"text": "mysql> CREATE DATABASE demo;\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 4573,
"s": 4504,
"text": "Now, let us create a table in it, using the CREATE TABLE statement β"
},
{
"code": null,
"e": 4670,
"s": 4573,
"text": "mysql> CREATE TABLE demo.Data (Name VARCHAR(255), age INT);\nQuery OK, 0 rows affected (0.51 sec)"
},
{
"code": null,
"e": 4820,
"s": 4670,
"text": "Let us create two events with names example_event1 and example_event2 it inserts a record in the above created table one minute after the execution β"
},
{
"code": null,
"e": 5119,
"s": 4820,
"text": "mysql> CREATE EVENT demo.example_event ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 Hour DO INSERT INTO new.Data VALUES('Rahman', 25);\nQuery OK, 0 rows affected (0.13 sec)\n\nmysql> CREATE EVENT demo.event_hourly ON SCHEDULE EVERY 1 MONTH DO TRUNCATE TABLE data;\nQuery OK, 0 rows affected (0.21 sec)"
},
{
"code": null,
"e": 5200,
"s": 5119,
"text": "Following query lists out all the (upcoming) events in the database named demo β"
},
{
"code": null,
"e": 6333,
"s": 5200,
"text": "mysql> SHOW EVENTS FROM demo\\G;\n*************************** 1. row ***************************\n Db: demo\n Name: event_hourly\n Definer: root@localhost\n Time zone: SYSTEM\n Type: RECURRING\n Execute at: NULL\n Interval value: 1\n Interval field: MONTH\n Starts: 2021-05-12 22:13:53\n Ends: NULL\n Status: ENABLED\n Originator: 1\ncharacter_set_client: utf8mb4\ncollation_connection: utf8mb4_0900_ai_ci\n Database Collation: utf8mb4_0900_ai_ci\n*************************** 2. row ***************************\n Db: demo\n Name: example_event\n Definer: root@localhost\n Time zone: SYSTEM\n Type: ONE TIME\n Execute at: 2021-05-12 23:13:10\n Interval value: NULL\n Interval field: NULL\n Starts: NULL\n Ends: NULL\n Status: ENABLED\n Originator: 1\ncharacter_set_client: utf8mb4\ncollation_connection: utf8mb4_0900_ai_ci\n Database Collation: utf8mb4_0900_ai_ci\n2 rows in set (0.26 sec)"
},
{
"code": null,
"e": 6385,
"s": 6333,
"text": "You can also use the IN clause instead of FROM as β"
},
{
"code": null,
"e": 7884,
"s": 6385,
"text": "mysql> SHOW EVENTS IN demo;\n+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | Originator | character_set_client | collation_connection | Database Collation |\n+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n| demo | event_hourly | root@localhost | SYSTEM | RECURRING | NULL | 1 | MONTH | 2021-05-12 22:13:53 | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |\n| demo | example_event | root@localhost | SYSTEM | ONE TIME | 2021-05-12 23:13:10 | NULL | NULL | NULL | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |\n+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 8060,
"s": 7884,
"text": "Using the LIKE clause, you can specify a pattern to retrieve specific tables. Following query retrieves the information about the events whose name starts with the letter \"e\"."
},
{
"code": null,
"e": 9561,
"s": 8060,
"text": "mysql> SHOW EVENTS LIKE 'e%';\n+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | Originator | character_set_client | collation_connection | Database Collation |\n+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n| demo | event_hourly | root@localhost | SYSTEM | RECURRING | NULL | 1 | MONTH | 2021-05-12 22:13:53 | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |\n| demo | example_event | root@localhost | SYSTEM | ONE TIME | 2021-05-13 17:24:46 | NULL | NULL | NULL | NULL | ENABLED | 1 | cp850 | cp850_general_ci | utf8mb4_0900_ai_ci |\n+------+---------------+----------------+-----------+-----------+---------------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n2 rows in set (0.07 sec)"
},
{
"code": null,
"e": 9689,
"s": 9561,
"text": "You can use the WHERE clause of the SHOW EVENTS statements to retrieve names of the tables which match the specified condition."
},
{
"code": null,
"e": 9841,
"s": 9689,
"text": "Following query lists out event which is of type recurring from the database named demo. Here we are using the SHOW EVENTS statement with WHERE clause."
},
{
"code": null,
"e": 11075,
"s": 9841,
"text": "mysql> SHOW EVENTS FROM demo WHERE Type = 'RECURRING';\n+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | Originator | character_set_client | collation_connection | Database Collation |\n+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n| demo | event_hourly | root@localhost | SYSTEM | RECURRING | NULL | 1 | MONTH | 2021-05-12 22:13:53 | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |\n+------+--------------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+------------+----------------------+----------------------+--------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 11108,
"s": 11075,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 11136,
"s": 11108,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11171,
"s": 11136,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 11188,
"s": 11171,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11222,
"s": 11188,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 11257,
"s": 11222,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 11291,
"s": 11257,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 11319,
"s": 11291,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 11352,
"s": 11319,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11372,
"s": 11352,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 11405,
"s": 11372,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11423,
"s": 11405,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 11430,
"s": 11423,
"text": " Print"
},
{
"code": null,
"e": 11441,
"s": 11430,
"text": " Add Notes"
}
] |
Concatenate strings from two fields into a third field in MongoDB?
|
To concatenate strings from two fields into a third field, you can use the following syntax
db.yourCollectionName.aggregate(
[
{ $project: { "yourNewFieldName": { $concat: [ "$yourFieldName1", " yourDellimiterValue ", "$yourFieldName2" ] } } }
]
);
Let us first create a collection with documents
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb7362d66697741252444")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb7402d66697741252445")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb74c2d66697741252446")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb7752d66697741252447")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"James","StudentLastName":"Williams"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb7862d66697741252448")
}
Following is the query to display all documents from a collection with the help of find() method
> db.concatenateStringsDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c9bb7362d66697741252444"),
"StudentFirstName" : "John",
"StudentLastName" : "Doe"
}
{
"_id" : ObjectId("5c9bb7402d66697741252445"),
"StudentFirstName" : "John",
"StudentLastName" : "Smith"
}
{
"_id" : ObjectId("5c9bb74c2d66697741252446"),
"StudentFirstName" : "Carol",
"StudentLastName" : "Taylor"
}
{
"_id" : ObjectId("5c9bb7752d66697741252447"),
"StudentFirstName" : "David",
"StudentLastName" : "Miller"
}
{
"_id" : ObjectId("5c9bb7862d66697741252448"),
"StudentFirstName" : "James",
"StudentLastName" : "Williams"
}
Following is the query to concatenate strings from two fields into a third field. We are concatenating the fields βStudentFirstNameβ and βStudentLastNameβ here into a third field
> db.concatenateStringsDemo.aggregate(
... [
... { $project: { "StudentFullName": { $concat: [ "$StudentFirstName", " / ", "$StudentLastName" ] } } }
... ]
... );
This will produce the following output
{ "_id" : ObjectId("5c9bb7362d66697741252444"), "StudentFullName" : "John / Doe" }
{ "_id" : ObjectId("5c9bb7402d66697741252445"), "StudentFullName" : "John / Smith" }
{ "_id" : ObjectId("5c9bb74c2d66697741252446"), "StudentFullName" : "Carol / Taylor" }
{ "_id" : ObjectId("5c9bb7752d66697741252447"), "StudentFullName" : "David / Miller" }
{ "_id" : ObjectId("5c9bb7862d66697741252448"), "StudentFullName" : "James / Williams" }
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To concatenate strings from two fields into a third field, you can use the following syntax"
},
{
"code": null,
"e": 1323,
"s": 1154,
"text": "db.yourCollectionName.aggregate(\n [\n { $project: { \"yourNewFieldName\": { $concat: [ \"$yourFieldName1\", \" yourDellimiterValue \", \"$yourFieldName2\" ] } } }\n ]\n);"
},
{
"code": null,
"e": 1371,
"s": 1323,
"text": "Let us first create a collection with documents"
},
{
"code": null,
"e": 2267,
"s": 1371,
"text": ">db.concatenateStringsDemo.insertOne({\"StudentFirstName\":\"John\",\"StudentLastName\":\"Doe\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9bb7362d66697741252444\")\n}\n>db.concatenateStringsDemo.insertOne({\"StudentFirstName\":\"John\",\"StudentLastName\":\"Smith\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9bb7402d66697741252445\")\n}\n>db.concatenateStringsDemo.insertOne({\"StudentFirstName\":\"Carol\",\"StudentLastName\":\"Taylor\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9bb74c2d66697741252446\")\n}\n>db.concatenateStringsDemo.insertOne({\"StudentFirstName\":\"David\",\"StudentLastName\":\"Miller\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9bb7752d66697741252447\")\n}\n>db.concatenateStringsDemo.insertOne({\"StudentFirstName\":\"James\",\"StudentLastName\":\"Williams\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9bb7862d66697741252448\")\n}"
},
{
"code": null,
"e": 2364,
"s": 2267,
"text": "Following is the query to display all documents from a collection with the help of find() method"
},
{
"code": null,
"e": 2409,
"s": 2364,
"text": "> db.concatenateStringsDemo.find().pretty();"
},
{
"code": null,
"e": 2448,
"s": 2409,
"text": "This will produce the following output"
},
{
"code": null,
"e": 3034,
"s": 2448,
"text": "{\n \"_id\" : ObjectId(\"5c9bb7362d66697741252444\"),\n \"StudentFirstName\" : \"John\",\n \"StudentLastName\" : \"Doe\"\n}\n{\n \"_id\" : ObjectId(\"5c9bb7402d66697741252445\"),\n \"StudentFirstName\" : \"John\",\n \"StudentLastName\" : \"Smith\"\n}\n{\n \"_id\" : ObjectId(\"5c9bb74c2d66697741252446\"),\n \"StudentFirstName\" : \"Carol\",\n \"StudentLastName\" : \"Taylor\"\n}\n{\n \"_id\" : ObjectId(\"5c9bb7752d66697741252447\"),\n \"StudentFirstName\" : \"David\",\n \"StudentLastName\" : \"Miller\"\n}\n{\n \"_id\" : ObjectId(\"5c9bb7862d66697741252448\"),\n \"StudentFirstName\" : \"James\",\n \"StudentLastName\" : \"Williams\"\n}"
},
{
"code": null,
"e": 3213,
"s": 3034,
"text": "Following is the query to concatenate strings from two fields into a third field. We are concatenating the fields βStudentFirstNameβ and βStudentLastNameβ here into a third field"
},
{
"code": null,
"e": 3376,
"s": 3213,
"text": "> db.concatenateStringsDemo.aggregate(\n... [\n... { $project: { \"StudentFullName\": { $concat: [ \"$StudentFirstName\", \" / \", \"$StudentLastName\" ] } } }\n... ]\n... );"
},
{
"code": null,
"e": 3415,
"s": 3376,
"text": "This will produce the following output"
},
{
"code": null,
"e": 3846,
"s": 3415,
"text": "{ \"_id\" : ObjectId(\"5c9bb7362d66697741252444\"), \"StudentFullName\" : \"John / Doe\" }\n{ \"_id\" : ObjectId(\"5c9bb7402d66697741252445\"), \"StudentFullName\" : \"John / Smith\" }\n{ \"_id\" : ObjectId(\"5c9bb74c2d66697741252446\"), \"StudentFullName\" : \"Carol / Taylor\" }\n{ \"_id\" : ObjectId(\"5c9bb7752d66697741252447\"), \"StudentFullName\" : \"David / Miller\" }\n{ \"_id\" : ObjectId(\"5c9bb7862d66697741252448\"), \"StudentFullName\" : \"James / Williams\" }"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.