title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Programming 8051 using Keil Software
|
In this section we will see how to write and execute programs for 8051 microcontroller using the Keil Software.
Here is the download link of Keil. You can download it and install it very easily. We are using C51 version for 8051 devices.
https://www.keil.com/download/product/
Start the Keil software. Go to the Project > New Project then choose a location to store your program, and give a name and Save.
Start the Keil software. Go to the Project > New Project then choose a location to store your program, and give a name and Save.
Now in the next window select the device from different manufacturers. We are selecting Microchip, and then by expanding we are selecting AT89C51 device and click ok.
Now in the next window select the device from different manufacturers. We are selecting Microchip, and then by expanding we are selecting AT89C51 device and click ok.
Now go to the New in the menu and select New. It will open a new editor to write code.
Now go to the New in the menu and select New. It will open a new editor to write code.
Go to the save option and save the program file with .c extension.
Go to the save option and save the program file with .c extension.
Write the code for 8051 Microcontroller. (Here we are using a code for blinking LED in 500 ms)
Write the code for 8051 Microcontroller. (Here we are using a code for blinking LED in 500 ms)
Now from the left panel, select Source Group 1, and Add Existing Files to Group ‘Source Group 1’. Then select the program (c file) then add and close.
Now from the left panel, select Source Group 1, and Add Existing Files to Group ‘Source Group 1’. Then select the program (c file) then add and close.
Now go to the Project > Build Target to build the project. If there is some error the building will be failed, after correcting the errors it can be build.
Now go to the Project > Build Target to build the project. If there is some error the building will be failed, after correcting the errors it can be build.
Now click on the Target1 from the left panel and select Options for Target ‘Target1’. Then set the xtal (MHz) value to 11.0592. Check mark on the Use On Chip ROM. Then go to the output tab. In this tab check Create Hex File, and click OK. Then build it again.
Now click on the Target1 from the left panel and select Options for Target ‘Target1’. Then set the xtal (MHz) value to 11.0592. Check mark on the Use On Chip ROM. Then go to the output tab. In this tab check Create Hex File, and click OK. Then build it again.
By uploading this hex file into the 8051 microcontroller the program can be loaded into it. And it will work.
Here we have used the following code −
#include<reg51.h>
sbit LED_pin = P2^0; //set the LED pin as P2.0
void delay(int ms){
unsigned int i, j;
for(i = 0; i< ms; i++){
// Outer for loop for given milliseconds value
for(j = 0; j < 1275; j++){
//execute in each milliseconds;
}
}
}
void main(){
while(1){
//infinite loop for LED blinking
LED_pin = 0;
delay(500); //wait for 500 milliseconds
LED_pin = 1;
delay(500); //wait for 500 milliseconds
}
}
The connection is like below
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "In this section we will see how to write and execute programs for 8051 microcontroller using the Keil Software."
},
{
"code": null,
"e": 1300,
"s": 1174,
"text": "Here is the download link of Keil. You can download it and install it very easily. We are using C51 version for 8051 devices."
},
{
"code": null,
"e": 1339,
"s": 1300,
"text": "https://www.keil.com/download/product/"
},
{
"code": null,
"e": 1468,
"s": 1339,
"text": "Start the Keil software. Go to the Project > New Project then choose a location to store your program, and give a name and Save."
},
{
"code": null,
"e": 1597,
"s": 1468,
"text": "Start the Keil software. Go to the Project > New Project then choose a location to store your program, and give a name and Save."
},
{
"code": null,
"e": 1764,
"s": 1597,
"text": "Now in the next window select the device from different manufacturers. We are selecting Microchip, and then by expanding we are selecting AT89C51 device and click ok."
},
{
"code": null,
"e": 1931,
"s": 1764,
"text": "Now in the next window select the device from different manufacturers. We are selecting Microchip, and then by expanding we are selecting AT89C51 device and click ok."
},
{
"code": null,
"e": 2018,
"s": 1931,
"text": "Now go to the New in the menu and select New. It will open a new editor to write code."
},
{
"code": null,
"e": 2105,
"s": 2018,
"text": "Now go to the New in the menu and select New. It will open a new editor to write code."
},
{
"code": null,
"e": 2172,
"s": 2105,
"text": "Go to the save option and save the program file with .c extension."
},
{
"code": null,
"e": 2239,
"s": 2172,
"text": "Go to the save option and save the program file with .c extension."
},
{
"code": null,
"e": 2334,
"s": 2239,
"text": "Write the code for 8051 Microcontroller. (Here we are using a code for blinking LED in 500 ms)"
},
{
"code": null,
"e": 2429,
"s": 2334,
"text": "Write the code for 8051 Microcontroller. (Here we are using a code for blinking LED in 500 ms)"
},
{
"code": null,
"e": 2580,
"s": 2429,
"text": "Now from the left panel, select Source Group 1, and Add Existing Files to Group ‘Source Group 1’. Then select the program (c file) then add and close."
},
{
"code": null,
"e": 2731,
"s": 2580,
"text": "Now from the left panel, select Source Group 1, and Add Existing Files to Group ‘Source Group 1’. Then select the program (c file) then add and close."
},
{
"code": null,
"e": 2887,
"s": 2731,
"text": "Now go to the Project > Build Target to build the project. If there is some error the building will be failed, after correcting the errors it can be build."
},
{
"code": null,
"e": 3043,
"s": 2887,
"text": "Now go to the Project > Build Target to build the project. If there is some error the building will be failed, after correcting the errors it can be build."
},
{
"code": null,
"e": 3303,
"s": 3043,
"text": "Now click on the Target1 from the left panel and select Options for Target ‘Target1’. Then set the xtal (MHz) value to 11.0592. Check mark on the Use On Chip ROM. Then go to the output tab. In this tab check Create Hex File, and click OK. Then build it again."
},
{
"code": null,
"e": 3563,
"s": 3303,
"text": "Now click on the Target1 from the left panel and select Options for Target ‘Target1’. Then set the xtal (MHz) value to 11.0592. Check mark on the Use On Chip ROM. Then go to the output tab. In this tab check Create Hex File, and click OK. Then build it again."
},
{
"code": null,
"e": 3673,
"s": 3563,
"text": "By uploading this hex file into the 8051 microcontroller the program can be loaded into it. And it will work."
},
{
"code": null,
"e": 3712,
"s": 3673,
"text": "Here we have used the following code −"
},
{
"code": null,
"e": 4190,
"s": 3712,
"text": "#include<reg51.h>\nsbit LED_pin = P2^0; //set the LED pin as P2.0\nvoid delay(int ms){\n unsigned int i, j;\n for(i = 0; i< ms; i++){\n // Outer for loop for given milliseconds value\n for(j = 0; j < 1275; j++){\n //execute in each milliseconds;\n }\n }\n}\nvoid main(){\n while(1){\n //infinite loop for LED blinking\n LED_pin = 0;\n delay(500); //wait for 500 milliseconds\n LED_pin = 1;\n delay(500); //wait for 500 milliseconds\n }\n}"
},
{
"code": null,
"e": 4219,
"s": 4190,
"text": "The connection is like below"
}
] |
shuffle vs random_shuffle in C++ - GeeksforGeeks
|
09 Oct, 2019
random_shuffle
It randomly rearrange elements in range [first, last).The function swaps the value of each element with some other randomly picked element. When provided, the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified source of randomness.
// CPP program Illustrating the// use of random_shuffle#include <bits/stdc++.h>using namespace std; // random generator functionint randomfunc(int j){ return rand() % j;} int main(){ srand(unsigned(time(0))); vector<int> arr; // set some values: for (int j = 1; j < 10; ++j) // 1 2 3 4 5 6 7 8 9 arr.push_back(j); // using built-in random generator random_shuffle(arr.begin(), arr.end()); // using randomfunc random_shuffle(arr.begin(), arr.end(), randomfunc); // print out content: cout << "arr contains:"; for (auto i = arr.begin(); i != arr.end(); ++i) cout << ' ' << *i; cout << endl; return 0;}
Output:
arr contains: 5 8 1 7 9 6 4 3 2
shuffle
Rearranges the elements in the range [first, last) randomly, using g as uniform random number generator.The function swaps the value of each element with that of some other randomly picked element. The function determines the element picked by calling g().
// CPP program Illustrating// the use of shuffle#include <bits/stdc++.h>using namespace std; // Driver Programint main(){ array<int, 5> s{ 1, 2, 3, 4, 5 }; // To obtain a time-based seed unsigned seed = 0; // Use of shuffle shuffle(s.begin(), s.end(), default_random_engine(seed)); cout << "shuffled elements are:"; for (int& i : s) cout << ' ' << i; cout << endl; return 0;}
Output:
shuffled elements are: 3 1 5 4 2
What is the difference between shuffle and random_shuffle c++?
The only difference is that random_shuffle uses rand() function to randomize the items, while the shuffle uses urng which is a better random generator, though with the particular overload of random_shuffle, we can get the same behavior (as with the shuffle).shuffle is an improvement over random_shuffle, and we should prefer using the formerfor better results.Example of Swapping Variables using bothrandom shuffle:template (class RandomIt, class RandomFunc)
void random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r)
{
typename iterator_traits::difference_type i, n;
n = last - first;
for (i = n-1; i > 0; --i) {
using std::swap;
swap(first[i], first[r(i+1)]);
}
}
Shuffle:template void shuffle(RandomIt first, RandomIt last,
UniformRandomBitGenerator&& g)
{
typedef typename iterator_traits::difference_type diff_t;
typedef uniform_int_distribution distr_t;
typedef typename distr_t::param_type param_t;
distr_t D;
diff_t n = last - first;
for (diff_t i = n-1; i > 0; --i) {
using swap;
swap(first[i], first[D(g, param_t(0, i))]);
}
}
The only difference is that random_shuffle uses rand() function to randomize the items, while the shuffle uses urng which is a better random generator, though with the particular overload of random_shuffle, we can get the same behavior (as with the shuffle).
shuffle is an improvement over random_shuffle, and we should prefer using the formerfor better results.
Example of Swapping Variables using bothrandom shuffle:template (class RandomIt, class RandomFunc)
void random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r)
{
typename iterator_traits::difference_type i, n;
n = last - first;
for (i = n-1; i > 0; --i) {
using std::swap;
swap(first[i], first[r(i+1)]);
}
}
Shuffle:template void shuffle(RandomIt first, RandomIt last,
UniformRandomBitGenerator&& g)
{
typedef typename iterator_traits::difference_type diff_t;
typedef uniform_int_distribution distr_t;
typedef typename distr_t::param_type param_t;
distr_t D;
diff_t n = last - first;
for (diff_t i = n-1; i > 0; --i) {
using swap;
swap(first[i], first[D(g, param_t(0, i))]);
}
}
template (class RandomIt, class RandomFunc)
void random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r)
{
typename iterator_traits::difference_type i, n;
n = last - first;
for (i = n-1; i > 0; --i) {
using std::swap;
swap(first[i], first[r(i+1)]);
}
}
Shuffle:
template void shuffle(RandomIt first, RandomIt last,
UniformRandomBitGenerator&& g)
{
typedef typename iterator_traits::difference_type diff_t;
typedef uniform_int_distribution distr_t;
typedef typename distr_t::param_type param_t;
distr_t D;
diff_t n = last - first;
for (diff_t i = n-1; i > 0; --i) {
using swap;
swap(first[i], first[D(g, param_t(0, i))]);
}
}
This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
saurabhgajjar
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
Copy Constructor in C++
|
[
{
"code": null,
"e": 24652,
"s": 24624,
"text": "\n09 Oct, 2019"
},
{
"code": null,
"e": 24667,
"s": 24652,
"text": "random_shuffle"
},
{
"code": null,
"e": 24957,
"s": 24667,
"text": "It randomly rearrange elements in range [first, last).The function swaps the value of each element with some other randomly picked element. When provided, the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified source of randomness."
},
{
"code": "// CPP program Illustrating the// use of random_shuffle#include <bits/stdc++.h>using namespace std; // random generator functionint randomfunc(int j){ return rand() % j;} int main(){ srand(unsigned(time(0))); vector<int> arr; // set some values: for (int j = 1; j < 10; ++j) // 1 2 3 4 5 6 7 8 9 arr.push_back(j); // using built-in random generator random_shuffle(arr.begin(), arr.end()); // using randomfunc random_shuffle(arr.begin(), arr.end(), randomfunc); // print out content: cout << \"arr contains:\"; for (auto i = arr.begin(); i != arr.end(); ++i) cout << ' ' << *i; cout << endl; return 0;}",
"e": 25636,
"s": 24957,
"text": null
},
{
"code": null,
"e": 25644,
"s": 25636,
"text": "Output:"
},
{
"code": null,
"e": 25677,
"s": 25644,
"text": "arr contains: 5 8 1 7 9 6 4 3 2\n"
},
{
"code": null,
"e": 25685,
"s": 25677,
"text": "shuffle"
},
{
"code": null,
"e": 25942,
"s": 25685,
"text": "Rearranges the elements in the range [first, last) randomly, using g as uniform random number generator.The function swaps the value of each element with that of some other randomly picked element. The function determines the element picked by calling g()."
},
{
"code": "// CPP program Illustrating// the use of shuffle#include <bits/stdc++.h>using namespace std; // Driver Programint main(){ array<int, 5> s{ 1, 2, 3, 4, 5 }; // To obtain a time-based seed unsigned seed = 0; // Use of shuffle shuffle(s.begin(), s.end(), default_random_engine(seed)); cout << \"shuffled elements are:\"; for (int& i : s) cout << ' ' << i; cout << endl; return 0;}",
"e": 26361,
"s": 25942,
"text": null
},
{
"code": null,
"e": 26369,
"s": 26361,
"text": "Output:"
},
{
"code": null,
"e": 26405,
"s": 26369,
"text": " \nshuffled elements are: 3 1 5 4 2\n"
},
{
"code": null,
"e": 26468,
"s": 26405,
"text": "What is the difference between shuffle and random_shuffle c++?"
},
{
"code": null,
"e": 27606,
"s": 26468,
"text": "The only difference is that random_shuffle uses rand() function to randomize the items, while the shuffle uses urng which is a better random generator, though with the particular overload of random_shuffle, we can get the same behavior (as with the shuffle).shuffle is an improvement over random_shuffle, and we should prefer using the formerfor better results.Example of Swapping Variables using bothrandom shuffle:template (class RandomIt, class RandomFunc)\nvoid random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r)\n{\n typename iterator_traits::difference_type i, n;\n n = last - first;\n for (i = n-1; i > 0; --i) {\n using std::swap;\n swap(first[i], first[r(i+1)]);\n }\n}\nShuffle:template void shuffle(RandomIt first, RandomIt last, \n UniformRandomBitGenerator&& g)\n{\n typedef typename iterator_traits::difference_type diff_t;\n typedef uniform_int_distribution distr_t;\n typedef typename distr_t::param_type param_t;\n \n distr_t D;\n diff_t n = last - first;\n for (diff_t i = n-1; i > 0; --i) {\n using swap;\n swap(first[i], first[D(g, param_t(0, i))]);\n }\n}"
},
{
"code": null,
"e": 27865,
"s": 27606,
"text": "The only difference is that random_shuffle uses rand() function to randomize the items, while the shuffle uses urng which is a better random generator, though with the particular overload of random_shuffle, we can get the same behavior (as with the shuffle)."
},
{
"code": null,
"e": 27969,
"s": 27865,
"text": "shuffle is an improvement over random_shuffle, and we should prefer using the formerfor better results."
},
{
"code": null,
"e": 28746,
"s": 27969,
"text": "Example of Swapping Variables using bothrandom shuffle:template (class RandomIt, class RandomFunc)\nvoid random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r)\n{\n typename iterator_traits::difference_type i, n;\n n = last - first;\n for (i = n-1; i > 0; --i) {\n using std::swap;\n swap(first[i], first[r(i+1)]);\n }\n}\nShuffle:template void shuffle(RandomIt first, RandomIt last, \n UniformRandomBitGenerator&& g)\n{\n typedef typename iterator_traits::difference_type diff_t;\n typedef uniform_int_distribution distr_t;\n typedef typename distr_t::param_type param_t;\n \n distr_t D;\n diff_t n = last - first;\n for (diff_t i = n-1; i > 0; --i) {\n using swap;\n swap(first[i], first[D(g, param_t(0, i))]);\n }\n}"
},
{
"code": null,
"e": 29038,
"s": 28746,
"text": "template (class RandomIt, class RandomFunc)\nvoid random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r)\n{\n typename iterator_traits::difference_type i, n;\n n = last - first;\n for (i = n-1; i > 0; --i) {\n using std::swap;\n swap(first[i], first[r(i+1)]);\n }\n}\n"
},
{
"code": null,
"e": 29047,
"s": 29038,
"text": "Shuffle:"
},
{
"code": null,
"e": 29470,
"s": 29047,
"text": "template void shuffle(RandomIt first, RandomIt last, \n UniformRandomBitGenerator&& g)\n{\n typedef typename iterator_traits::difference_type diff_t;\n typedef uniform_int_distribution distr_t;\n typedef typename distr_t::param_type param_t;\n \n distr_t D;\n diff_t n = last - first;\n for (diff_t i = n-1; i > 0; --i) {\n using swap;\n swap(first[i], first[D(g, param_t(0, i))]);\n }\n}"
},
{
"code": null,
"e": 29773,
"s": 29470,
"text": "This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29898,
"s": 29773,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29912,
"s": 29898,
"text": "saurabhgajjar"
},
{
"code": null,
"e": 29934,
"s": 29912,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 29938,
"s": 29934,
"text": "STL"
},
{
"code": null,
"e": 29942,
"s": 29938,
"text": "C++"
},
{
"code": null,
"e": 29946,
"s": 29942,
"text": "STL"
},
{
"code": null,
"e": 29950,
"s": 29946,
"text": "CPP"
},
{
"code": null,
"e": 30048,
"s": 29950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30067,
"s": 30048,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30091,
"s": 30067,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 30119,
"s": 30091,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30147,
"s": 30119,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 30174,
"s": 30147,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 30209,
"s": 30174,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 30233,
"s": 30209,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 30253,
"s": 30233,
"text": "Constructors in C++"
},
{
"code": null,
"e": 30284,
"s": 30253,
"text": "Templates in C++ with Examples"
}
] |
Tryit Editor v3.7
|
Tryit: Different border color for each side
|
[] |
Program to rotate square matrix by 90 degrees counterclockwise in Python
|
Suppose we have a square matrix, we have to rotate it 90 degrees counter-clockwise.
then the output will be
To solve this, we will follow these steps −
if matrix is empty, thenreturn a blank list
if matrix is empty, then
return a blank list
return a blank list
n := row count of matrix
n := row count of matrix
for each row in matrix, doreverse the row
for each row in matrix, do
reverse the row
reverse the row
for i in range 0 to n−1, dofor j in range 0 to i−1, doswap matrix[i, j] and matrix[j, i]
for i in range 0 to n−1, do
for j in range 0 to i−1, doswap matrix[i, j] and matrix[j, i]
for j in range 0 to i−1, do
swap matrix[i, j] and matrix[j, i]
swap matrix[i, j] and matrix[j, i]
return matrix
return matrix
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, matrix):
if not matrix or not matrix[0]:
return []
n = len(matrix)
for row in matrix:
row.reverse()
for i in range(n):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i],
matrix[i][j]
return matrix
ob = Solution()
matrix = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]
print(ob.solve(matrix))
[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9] ]
[
[7, 8, 9],
[4, 5, 6],
[1, 2, 3]]
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "Suppose we have a square matrix, we have to rotate it 90 degrees counter-clockwise."
},
{
"code": null,
"e": 1170,
"s": 1146,
"text": "then the output will be"
},
{
"code": null,
"e": 1214,
"s": 1170,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1258,
"s": 1214,
"text": "if matrix is empty, thenreturn a blank list"
},
{
"code": null,
"e": 1283,
"s": 1258,
"text": "if matrix is empty, then"
},
{
"code": null,
"e": 1303,
"s": 1283,
"text": "return a blank list"
},
{
"code": null,
"e": 1323,
"s": 1303,
"text": "return a blank list"
},
{
"code": null,
"e": 1348,
"s": 1323,
"text": "n := row count of matrix"
},
{
"code": null,
"e": 1373,
"s": 1348,
"text": "n := row count of matrix"
},
{
"code": null,
"e": 1415,
"s": 1373,
"text": "for each row in matrix, doreverse the row"
},
{
"code": null,
"e": 1442,
"s": 1415,
"text": "for each row in matrix, do"
},
{
"code": null,
"e": 1458,
"s": 1442,
"text": "reverse the row"
},
{
"code": null,
"e": 1474,
"s": 1458,
"text": "reverse the row"
},
{
"code": null,
"e": 1563,
"s": 1474,
"text": "for i in range 0 to n−1, dofor j in range 0 to i−1, doswap matrix[i, j] and matrix[j, i]"
},
{
"code": null,
"e": 1591,
"s": 1563,
"text": "for i in range 0 to n−1, do"
},
{
"code": null,
"e": 1653,
"s": 1591,
"text": "for j in range 0 to i−1, doswap matrix[i, j] and matrix[j, i]"
},
{
"code": null,
"e": 1681,
"s": 1653,
"text": "for j in range 0 to i−1, do"
},
{
"code": null,
"e": 1716,
"s": 1681,
"text": "swap matrix[i, j] and matrix[j, i]"
},
{
"code": null,
"e": 1751,
"s": 1716,
"text": "swap matrix[i, j] and matrix[j, i]"
},
{
"code": null,
"e": 1765,
"s": 1751,
"text": "return matrix"
},
{
"code": null,
"e": 1779,
"s": 1765,
"text": "return matrix"
},
{
"code": null,
"e": 1849,
"s": 1779,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1860,
"s": 1849,
"text": " Live Demo"
},
{
"code": null,
"e": 2269,
"s": 1860,
"text": "class Solution:\n def solve(self, matrix):\n if not matrix or not matrix[0]:\n return []\n n = len(matrix)\n for row in matrix:\n row.reverse()\n for i in range(n):\n for j in range(i):\n matrix[i][j], matrix[j][i] = matrix[j][i],\n matrix[i][j]\n return matrix\nob = Solution()\nmatrix = [\n[1, 4, 7],\n[2, 5, 8],\n[3, 6, 9]\n]\nprint(ob.solve(matrix))"
},
{
"code": null,
"e": 2305,
"s": 2269,
"text": "[\n[1, 4, 7],\n[2, 5, 8],\n[3, 6, 9] ]"
},
{
"code": null,
"e": 2340,
"s": 2305,
"text": "[\n[7, 8, 9],\n[4, 5, 6],\n[1, 2, 3]]"
}
] |
What is the scope of local variables in Java?
|
Scope of a variable denotes span of a variable.
The scope of a local variable is within that method i.e. when we create a variable with in a method, it cannot be accessed outside that method.
If you observe the following example here, we have created a variable named num in the main method and, trying to access it in another method (demo).
public class SampleTest {
String str = "sampleString";
public static void main(String args[]){
int num = 334;
}
public void demo(){
System.out.println(num);
}
}
Since we cannot access a local variable (variable of a method) outside it, the compiler generates an error as −
C:\Sample>javac SampleTest.java
SampleTest.java:7: error: cannot find symbol
System.out.println(num);
^
symbol: variable num
location: class SampleTest
1 error
|
[
{
"code": null,
"e": 1110,
"s": 1062,
"text": "Scope of a variable denotes span of a variable."
},
{
"code": null,
"e": 1254,
"s": 1110,
"text": "The scope of a local variable is within that method i.e. when we create a variable with in a method, it cannot be accessed outside that method."
},
{
"code": null,
"e": 1404,
"s": 1254,
"text": "If you observe the following example here, we have created a variable named num in the main method and, trying to access it in another method (demo)."
},
{
"code": null,
"e": 1596,
"s": 1404,
"text": "public class SampleTest {\n String str = \"sampleString\";\n \n public static void main(String args[]){\n int num = 334;\n }\n public void demo(){\n System.out.println(num);\n }\n}"
},
{
"code": null,
"e": 1708,
"s": 1596,
"text": "Since we cannot access a local variable (variable of a method) outside it, the compiler generates an error as −"
},
{
"code": null,
"e": 1888,
"s": 1708,
"text": "C:\\Sample>javac SampleTest.java\nSampleTest.java:7: error: cannot find symbol\nSystem.out.println(num);\n ^\nsymbol: variable num\nlocation: class SampleTest\n1 error\n"
}
] |
Integrating Trino and Apache Ranger | by Aakash Nand | Towards Data Science
|
As demand for data grows day by day, the requirement for data security in an enterprise setup is increasing as well. In the Hadoop ecosystem, Apache Ranger has been a promising framework for data security with extensive plugins such as HDFS, Solr, Yarn, Kafka, Hive and many more. Apache Ranger added a plugin for prestosql in version 2.1.0 but recently PrestoSQL was rebranded as Trino and that broke the working prestosql plugin for Apache Ranger.
I have submitted a patch for this issue and there is already an open JIRA issue here but that will not stop us from integrating Trino with Apache Ranger. For this tutorial, I have built the Apache Ranger 2.1.0 with the Trino plugin. If you want to build the Apache Ranger from source code including the trino plugin you can refer to this GitHub repository on the branch ranger-2.1.0-trino and for this tutorial purpose, we will this Github repository.
Apache Ranger has three key components ranger-admin , ranger-usersync and ranger-audit . Let us get introduced to these components.
Note: Configuring ranger-usersync is out of scope for this tutorial and we will not use any usersync component for this tutorial.
Ranger Admin component is a UI component using which we can create policies for the different access levels. Ranger Admin requires a backend database, in our case we are using Postgres as the backend database for Ranger Admin UI.
Ranger Audit component collects and shows logs for each access event of the resource. Ranger supports two audit methods, solr and elasticsearch . We will use elasticsearch to store ranger audit logs which will be then displayed in the Ranger Audit UI as well.
Trino is a fast distributed query engine. It can connect to several data sources such as hive , postgres , oracle and so on. You can read more about Trino and Trino connectors in the official documentation here. For this tutorial, we will use the default catalog tpch which comes with dummy data.
Apache Ranger supports many plugins such as HDFS, Hive, Yarn, Trino etc. Each of these plugins needs to be configured on the host which is running that process. Trino-Ranger-Plugin is one component that will communicate with Ranger Admin to check and download the access policies which will be then synced with Trino Server. The downloaded policies are stored as JSON files on the Trino server and can be found under the path /etc/ranger/<service-name>/policycache so in this case the policy path is /etc/ranger/trino/policycache
The communication between the above components is explained in the following diagram.
The docker-compose file connects all of the above components.
Important points about docker-compose.yml
We have used named-docker-volumes ex: ranger-es-data , ranger-pg-datato persist data of the services such as elasticsearch and postgres even after a container restartThe pre-built tar files of Ranger-Admin and Ranger-Trino Plugin are available as release assets on this demo repository here.The ranger-Admin process requires a minimum of 1.5 GB of memory. The Ranger-Admin tar file contains install.properties and setup.sh . The setup.sh the script reads the configuration from install.properties . The following patch file describes configuration changes made to install.properties compared to the default version of install.propertiesfor Ranger-Admin component.
We have used named-docker-volumes ex: ranger-es-data , ranger-pg-datato persist data of the services such as elasticsearch and postgres even after a container restart
The pre-built tar files of Ranger-Admin and Ranger-Trino Plugin are available as release assets on this demo repository here.
The ranger-Admin process requires a minimum of 1.5 GB of memory. The Ranger-Admin tar file contains install.properties and setup.sh . The setup.sh the script reads the configuration from install.properties . The following patch file describes configuration changes made to install.properties compared to the default version of install.propertiesfor Ranger-Admin component.
4. Ranger-Trino-Plugin tar file also contains install.properties and enable-trino-plugin.sh script. One important point to note about the trino docker environment is that the configuration files and plugin directory are configured to different directory locations. The configuration is read from /etc/trino whereas plugins are loaded from /usr/lib/trino/plugins These two directories are important when configuring install.properties for Trino-Ranger-Plugin and hence some extra customization is required to the default script enable-trino-plugin.sh that comes with the Trino-Ranger-Plugin tar file to make it work with dockerized Trino. These changes are highlighted in the following patch file. Basically, these changes introduce two new custom variables INSTALL_ENV and COMPONENT_PLUGIN_DIR_NAME which can be configured in install.properties
5. install.properties file for Trino Ranger Plugin needs to be configured as shown in the following patch file. Please note that we are using two newly introduced custom variables to inform enable-plugin-script that Trino is deployed in the docker environment.
6. Finally, putting it all together in the docker-compose.yml as shown below. This file is also available in Github Repository here.
In this part, we will deploy docker-compose services and confirm the status of each component.
git clone https://github.com/aakashnand/trino-ranger-demo.git
$ cd trino-ranger-demo$ docker-compose up -d
Once we deploy services using docker-compose, we should be able to see four running services. We can confirm this by docker-compose ps
Let’s confirm that Trino and Ranger-Admin services are accessible on the following URLs
Ranger Admin: http://localhost:6080
Trino: http://localhost:8080
Elasticsearch: http://localhost:9200
Let's access Ranger-Admin UI and log in as admin user. We configured our admin user password rangeradmin1 in the above ranger-admin-install.properties file. As we can see in the following screenshot, by default, there is no trinoservice. Therefore, let's create a service with the name trino . The service name should match with the name defined in install.properties for Ranger-Admin
Please note the hostname in the JDBC string. From ranger-admin container trino is reachable at my-localhost-trino hence hostname is configured as my-localhost-trino
If we click on Test Connection we will get a Connection Failed error as shown below. This is because the Ranger-Admin process is already running and is still looking for a service with the nametrino which we have not created yet. It will be created once we click Add .
So let's add trino service and then click Test Connection again
Now Ranger-Admin is successfully connected to Trino 🎉
To check audit logs, navigate to audit from the top navigation bar and click Audit . We can see that audit logs are displayed 🎉 . Ranger-Admin and Elasticsearch are working correctly.
Now that we have finished the setup, it is time to create actual access policies and see it in action
When creating the trino service we used ranger-admin as username in the connection information. This creates default policies with this username and thus the ranger-adminuser will have super privileges
To understand the access scenario and create an access policy we need to create a test user. The Ranger usersync service syncs users, groups, and group memberships from various sources, such as Unix, File, or AD/LDAP into Ranger. Ranger usersync provides a set of rich and flexible configuration properties to sync users, groups, and group memberships from AD/LDAP supporting a wide variety of use cases. In this tutorial, we will manually create a test user from Ranger-Admin UI.
To create a user, let’s navigate to Settings → Users/Groups/Roles → Add New User
When creating a user we can choose different roles.
user role is the normal user
Admin role can create and manage policies from Ranger Admin UI.
Auditor role is read-only user role.
For the time being, let’s create a user with Admin role.
Let's confirm access for the user ranger-admin
As we can see ranger-admin user can access all the tables under schema tpch.sf10
Since we have not configured any policy for test-user if we try to access any catalog or execute any query, we should see an access denied message. Let's confirm this by executing queries from Trino CLI
Let’s create a policy that allows test-user access to tpch.sf10 to all tables.
We can also assign specific permissions on each policy, but for the time being let's create a policy with all permissions. After creating this policy, we have the following active policies.
Now let’s confirm the access again.
We are still getting access denied message. This is because Trino ranger policies need to be configured for each object level. For example, catalog level policy, catalog+schema level policy, catalog+schema+table level policy and information_schema policy. Let's add policy for the catalog level.
Let's confirm again with Trino CLI
We are still getting the error but the error message is different. Let's navigate to Ranger Audit Section to understand more about this.
We can see an entry that denied permission to a resource called tpch.information_schema.tables.table_schema . In Trino, information_schema is the schema which contains metadata about table and table columns. So it is necessary to add policy for information_schema as well. Access to information_schema is required for any user to execute the query in Trino, therefore, we can use the {USER} variable in Ranger policy that gives access to all users.
Let us confirm the access from Trino CLI again.
We still get access denied if we try to execute any SQL function. In the default policies section, all-functionspolicy (ID:3) is the policy that allows access to execute any SQL function. Since executing SQL function is a requirement for all users, Let’s edit the all-functionspolicy (ID:3) and add all users using the {USER}variable to give access to functions
So to summarize, to give access to test-user to ALL tables under sf10 we added three new policies and edited the default all-function policy.
Now we can access and execute queries for all tables for sf10 schema.
In the next step, let’s understand how to give access to test-user for a specific table under schema sf10
In the previous step, we configured policies to give access to ALL tables under sf10 schema and therefore, schema-level the policy was not necessary. To give access to a specific schema we need to add schema-level policy and then we can configure table-level the policy. So let us add schema-level a policy for tpch.sf10
Now let us edit sf10-all-tables-policy from all tables to specific table. We will configure a policy that will allow access to onlynation table
So finally we have the following active policies
Now let's execute queries from Trino CLI again for test-user.
test-user can now access the onlynation table from tpch.sf10 schema as desired.
If you have followed all the steps and reached this end, Congratulations 祝️, now you have understood how to configure Trino and Apache Ranger.
After the rebranding from PrestoSQL to Trino, the default plugin from Apache Ranger’s GitHub repository will NOT work with the new Trino as it is still referencing old io.prestosql packages. You can track this issue on JIRA here
Rebranded Trino plugin will not be made available in the new Ranger version 2.2.0. So meanwhile, please feel free to use this GitHub repository for building Apache Ranger from source code and this GitHub repository for getting started with Trino-Ranger integration.
Configuring Ranger policies for Trino is not so intuitive because we need to configure access policies for each level. There is an open issue regarding this on Trino’s repository here.
Nonetheless, it is recommended to configure some basic policies such as information_schema and all-functions with {USER} variable as these policies are necessary for any user to execute queries.
Due to the lack of good documentation and not so intuitive nature of the integration process, integrating Apache Ranger and Trino can be painful, but I hope this article makes it a bit easier. If you are using Trino, I highly recommend you to join Trino Community Slack for more detailed discussions. Thank you for reading.
|
[
{
"code": null,
"e": 622,
"s": 172,
"text": "As demand for data grows day by day, the requirement for data security in an enterprise setup is increasing as well. In the Hadoop ecosystem, Apache Ranger has been a promising framework for data security with extensive plugins such as HDFS, Solr, Yarn, Kafka, Hive and many more. Apache Ranger added a plugin for prestosql in version 2.1.0 but recently PrestoSQL was rebranded as Trino and that broke the working prestosql plugin for Apache Ranger."
},
{
"code": null,
"e": 1074,
"s": 622,
"text": "I have submitted a patch for this issue and there is already an open JIRA issue here but that will not stop us from integrating Trino with Apache Ranger. For this tutorial, I have built the Apache Ranger 2.1.0 with the Trino plugin. If you want to build the Apache Ranger from source code including the trino plugin you can refer to this GitHub repository on the branch ranger-2.1.0-trino and for this tutorial purpose, we will this Github repository."
},
{
"code": null,
"e": 1206,
"s": 1074,
"text": "Apache Ranger has three key components ranger-admin , ranger-usersync and ranger-audit . Let us get introduced to these components."
},
{
"code": null,
"e": 1336,
"s": 1206,
"text": "Note: Configuring ranger-usersync is out of scope for this tutorial and we will not use any usersync component for this tutorial."
},
{
"code": null,
"e": 1566,
"s": 1336,
"text": "Ranger Admin component is a UI component using which we can create policies for the different access levels. Ranger Admin requires a backend database, in our case we are using Postgres as the backend database for Ranger Admin UI."
},
{
"code": null,
"e": 1826,
"s": 1566,
"text": "Ranger Audit component collects and shows logs for each access event of the resource. Ranger supports two audit methods, solr and elasticsearch . We will use elasticsearch to store ranger audit logs which will be then displayed in the Ranger Audit UI as well."
},
{
"code": null,
"e": 2123,
"s": 1826,
"text": "Trino is a fast distributed query engine. It can connect to several data sources such as hive , postgres , oracle and so on. You can read more about Trino and Trino connectors in the official documentation here. For this tutorial, we will use the default catalog tpch which comes with dummy data."
},
{
"code": null,
"e": 2653,
"s": 2123,
"text": "Apache Ranger supports many plugins such as HDFS, Hive, Yarn, Trino etc. Each of these plugins needs to be configured on the host which is running that process. Trino-Ranger-Plugin is one component that will communicate with Ranger Admin to check and download the access policies which will be then synced with Trino Server. The downloaded policies are stored as JSON files on the Trino server and can be found under the path /etc/ranger/<service-name>/policycache so in this case the policy path is /etc/ranger/trino/policycache"
},
{
"code": null,
"e": 2739,
"s": 2653,
"text": "The communication between the above components is explained in the following diagram."
},
{
"code": null,
"e": 2801,
"s": 2739,
"text": "The docker-compose file connects all of the above components."
},
{
"code": null,
"e": 2843,
"s": 2801,
"text": "Important points about docker-compose.yml"
},
{
"code": null,
"e": 3507,
"s": 2843,
"text": "We have used named-docker-volumes ex: ranger-es-data , ranger-pg-datato persist data of the services such as elasticsearch and postgres even after a container restartThe pre-built tar files of Ranger-Admin and Ranger-Trino Plugin are available as release assets on this demo repository here.The ranger-Admin process requires a minimum of 1.5 GB of memory. The Ranger-Admin tar file contains install.properties and setup.sh . The setup.sh the script reads the configuration from install.properties . The following patch file describes configuration changes made to install.properties compared to the default version of install.propertiesfor Ranger-Admin component."
},
{
"code": null,
"e": 3674,
"s": 3507,
"text": "We have used named-docker-volumes ex: ranger-es-data , ranger-pg-datato persist data of the services such as elasticsearch and postgres even after a container restart"
},
{
"code": null,
"e": 3800,
"s": 3674,
"text": "The pre-built tar files of Ranger-Admin and Ranger-Trino Plugin are available as release assets on this demo repository here."
},
{
"code": null,
"e": 4173,
"s": 3800,
"text": "The ranger-Admin process requires a minimum of 1.5 GB of memory. The Ranger-Admin tar file contains install.properties and setup.sh . The setup.sh the script reads the configuration from install.properties . The following patch file describes configuration changes made to install.properties compared to the default version of install.propertiesfor Ranger-Admin component."
},
{
"code": null,
"e": 5018,
"s": 4173,
"text": "4. Ranger-Trino-Plugin tar file also contains install.properties and enable-trino-plugin.sh script. One important point to note about the trino docker environment is that the configuration files and plugin directory are configured to different directory locations. The configuration is read from /etc/trino whereas plugins are loaded from /usr/lib/trino/plugins These two directories are important when configuring install.properties for Trino-Ranger-Plugin and hence some extra customization is required to the default script enable-trino-plugin.sh that comes with the Trino-Ranger-Plugin tar file to make it work with dockerized Trino. These changes are highlighted in the following patch file. Basically, these changes introduce two new custom variables INSTALL_ENV and COMPONENT_PLUGIN_DIR_NAME which can be configured in install.properties"
},
{
"code": null,
"e": 5279,
"s": 5018,
"text": "5. install.properties file for Trino Ranger Plugin needs to be configured as shown in the following patch file. Please note that we are using two newly introduced custom variables to inform enable-plugin-script that Trino is deployed in the docker environment."
},
{
"code": null,
"e": 5412,
"s": 5279,
"text": "6. Finally, putting it all together in the docker-compose.yml as shown below. This file is also available in Github Repository here."
},
{
"code": null,
"e": 5507,
"s": 5412,
"text": "In this part, we will deploy docker-compose services and confirm the status of each component."
},
{
"code": null,
"e": 5569,
"s": 5507,
"text": "git clone https://github.com/aakashnand/trino-ranger-demo.git"
},
{
"code": null,
"e": 5614,
"s": 5569,
"text": "$ cd trino-ranger-demo$ docker-compose up -d"
},
{
"code": null,
"e": 5749,
"s": 5614,
"text": "Once we deploy services using docker-compose, we should be able to see four running services. We can confirm this by docker-compose ps"
},
{
"code": null,
"e": 5837,
"s": 5749,
"text": "Let’s confirm that Trino and Ranger-Admin services are accessible on the following URLs"
},
{
"code": null,
"e": 5873,
"s": 5837,
"text": "Ranger Admin: http://localhost:6080"
},
{
"code": null,
"e": 5902,
"s": 5873,
"text": "Trino: http://localhost:8080"
},
{
"code": null,
"e": 5939,
"s": 5902,
"text": "Elasticsearch: http://localhost:9200"
},
{
"code": null,
"e": 6324,
"s": 5939,
"text": "Let's access Ranger-Admin UI and log in as admin user. We configured our admin user password rangeradmin1 in the above ranger-admin-install.properties file. As we can see in the following screenshot, by default, there is no trinoservice. Therefore, let's create a service with the name trino . The service name should match with the name defined in install.properties for Ranger-Admin"
},
{
"code": null,
"e": 6489,
"s": 6324,
"text": "Please note the hostname in the JDBC string. From ranger-admin container trino is reachable at my-localhost-trino hence hostname is configured as my-localhost-trino"
},
{
"code": null,
"e": 6758,
"s": 6489,
"text": "If we click on Test Connection we will get a Connection Failed error as shown below. This is because the Ranger-Admin process is already running and is still looking for a service with the nametrino which we have not created yet. It will be created once we click Add ."
},
{
"code": null,
"e": 6822,
"s": 6758,
"text": "So let's add trino service and then click Test Connection again"
},
{
"code": null,
"e": 6876,
"s": 6822,
"text": "Now Ranger-Admin is successfully connected to Trino 🎉"
},
{
"code": null,
"e": 7060,
"s": 6876,
"text": "To check audit logs, navigate to audit from the top navigation bar and click Audit . We can see that audit logs are displayed 🎉 . Ranger-Admin and Elasticsearch are working correctly."
},
{
"code": null,
"e": 7162,
"s": 7060,
"text": "Now that we have finished the setup, it is time to create actual access policies and see it in action"
},
{
"code": null,
"e": 7364,
"s": 7162,
"text": "When creating the trino service we used ranger-admin as username in the connection information. This creates default policies with this username and thus the ranger-adminuser will have super privileges"
},
{
"code": null,
"e": 7845,
"s": 7364,
"text": "To understand the access scenario and create an access policy we need to create a test user. The Ranger usersync service syncs users, groups, and group memberships from various sources, such as Unix, File, or AD/LDAP into Ranger. Ranger usersync provides a set of rich and flexible configuration properties to sync users, groups, and group memberships from AD/LDAP supporting a wide variety of use cases. In this tutorial, we will manually create a test user from Ranger-Admin UI."
},
{
"code": null,
"e": 7926,
"s": 7845,
"text": "To create a user, let’s navigate to Settings → Users/Groups/Roles → Add New User"
},
{
"code": null,
"e": 7978,
"s": 7926,
"text": "When creating a user we can choose different roles."
},
{
"code": null,
"e": 8007,
"s": 7978,
"text": "user role is the normal user"
},
{
"code": null,
"e": 8071,
"s": 8007,
"text": "Admin role can create and manage policies from Ranger Admin UI."
},
{
"code": null,
"e": 8108,
"s": 8071,
"text": "Auditor role is read-only user role."
},
{
"code": null,
"e": 8165,
"s": 8108,
"text": "For the time being, let’s create a user with Admin role."
},
{
"code": null,
"e": 8212,
"s": 8165,
"text": "Let's confirm access for the user ranger-admin"
},
{
"code": null,
"e": 8293,
"s": 8212,
"text": "As we can see ranger-admin user can access all the tables under schema tpch.sf10"
},
{
"code": null,
"e": 8496,
"s": 8293,
"text": "Since we have not configured any policy for test-user if we try to access any catalog or execute any query, we should see an access denied message. Let's confirm this by executing queries from Trino CLI"
},
{
"code": null,
"e": 8575,
"s": 8496,
"text": "Let’s create a policy that allows test-user access to tpch.sf10 to all tables."
},
{
"code": null,
"e": 8765,
"s": 8575,
"text": "We can also assign specific permissions on each policy, but for the time being let's create a policy with all permissions. After creating this policy, we have the following active policies."
},
{
"code": null,
"e": 8801,
"s": 8765,
"text": "Now let’s confirm the access again."
},
{
"code": null,
"e": 9097,
"s": 8801,
"text": "We are still getting access denied message. This is because Trino ranger policies need to be configured for each object level. For example, catalog level policy, catalog+schema level policy, catalog+schema+table level policy and information_schema policy. Let's add policy for the catalog level."
},
{
"code": null,
"e": 9132,
"s": 9097,
"text": "Let's confirm again with Trino CLI"
},
{
"code": null,
"e": 9269,
"s": 9132,
"text": "We are still getting the error but the error message is different. Let's navigate to Ranger Audit Section to understand more about this."
},
{
"code": null,
"e": 9718,
"s": 9269,
"text": "We can see an entry that denied permission to a resource called tpch.information_schema.tables.table_schema . In Trino, information_schema is the schema which contains metadata about table and table columns. So it is necessary to add policy for information_schema as well. Access to information_schema is required for any user to execute the query in Trino, therefore, we can use the {USER} variable in Ranger policy that gives access to all users."
},
{
"code": null,
"e": 9766,
"s": 9718,
"text": "Let us confirm the access from Trino CLI again."
},
{
"code": null,
"e": 10128,
"s": 9766,
"text": "We still get access denied if we try to execute any SQL function. In the default policies section, all-functionspolicy (ID:3) is the policy that allows access to execute any SQL function. Since executing SQL function is a requirement for all users, Let’s edit the all-functionspolicy (ID:3) and add all users using the {USER}variable to give access to functions"
},
{
"code": null,
"e": 10270,
"s": 10128,
"text": "So to summarize, to give access to test-user to ALL tables under sf10 we added three new policies and edited the default all-function policy."
},
{
"code": null,
"e": 10340,
"s": 10270,
"text": "Now we can access and execute queries for all tables for sf10 schema."
},
{
"code": null,
"e": 10446,
"s": 10340,
"text": "In the next step, let’s understand how to give access to test-user for a specific table under schema sf10"
},
{
"code": null,
"e": 10767,
"s": 10446,
"text": "In the previous step, we configured policies to give access to ALL tables under sf10 schema and therefore, schema-level the policy was not necessary. To give access to a specific schema we need to add schema-level policy and then we can configure table-level the policy. So let us add schema-level a policy for tpch.sf10"
},
{
"code": null,
"e": 10911,
"s": 10767,
"text": "Now let us edit sf10-all-tables-policy from all tables to specific table. We will configure a policy that will allow access to onlynation table"
},
{
"code": null,
"e": 10960,
"s": 10911,
"text": "So finally we have the following active policies"
},
{
"code": null,
"e": 11022,
"s": 10960,
"text": "Now let's execute queries from Trino CLI again for test-user."
},
{
"code": null,
"e": 11102,
"s": 11022,
"text": "test-user can now access the onlynation table from tpch.sf10 schema as desired."
},
{
"code": null,
"e": 11245,
"s": 11102,
"text": "If you have followed all the steps and reached this end, Congratulations 祝️, now you have understood how to configure Trino and Apache Ranger."
},
{
"code": null,
"e": 11474,
"s": 11245,
"text": "After the rebranding from PrestoSQL to Trino, the default plugin from Apache Ranger’s GitHub repository will NOT work with the new Trino as it is still referencing old io.prestosql packages. You can track this issue on JIRA here"
},
{
"code": null,
"e": 11740,
"s": 11474,
"text": "Rebranded Trino plugin will not be made available in the new Ranger version 2.2.0. So meanwhile, please feel free to use this GitHub repository for building Apache Ranger from source code and this GitHub repository for getting started with Trino-Ranger integration."
},
{
"code": null,
"e": 11925,
"s": 11740,
"text": "Configuring Ranger policies for Trino is not so intuitive because we need to configure access policies for each level. There is an open issue regarding this on Trino’s repository here."
},
{
"code": null,
"e": 12120,
"s": 11925,
"text": "Nonetheless, it is recommended to configure some basic policies such as information_schema and all-functions with {USER} variable as these policies are necessary for any user to execute queries."
}
] |
How to find an average color of an image using JavaScript ? - GeeksforGeeks
|
14 Feb, 2022
The average color of an image can be found with JavaScript by drawing the image on a canvas element. The following steps have to be performed to get the average color of an image:
1. The image is first drawn on the canvas using the method context.drawImage() of the Canvas 2D API. This method takes in the image and the dimensions as parameters and draws it to the canvas.
Syntax:
context.drawImage( img, width, height );
2. The image data of the canvas is returned using the context.getImageData() method. It returns an ImageData object representing the pixel data for a specified section of the canvas.
Syntax:
context.getImageData( x, y, width, height )
3. The average red, green and blue colors are then calculated with this image data by adding all the color values separately and finding the average value of that color.
Example:
html
<!DOCTYPE html><html lang="en"> <head> <title> Find Average Color of image via JavaScript? </title> <style> #img { position: absolute; top: 20%; left: 25%; } #block { position: absolute; background-color: white; height: 70px; width: 70px; left: 50%; top: 25%; } </style></head> <body> <img height="100px" width="150px" id="img" src= "image_to_find_average_color.png"> <div id="block"></div> <!-- Function to find the average color --> <script> function averageColor(imageElement) { // Create the canvas element var canvas = document.createElement('canvas'), // Get the 2D context of the canvas context = canvas.getContext && canvas.getContext('2d'), imgData, width, height, length, // Define variables for storing // the individual red, blue and // green colors rgb = { r: 0, g: 0, b: 0 }, // Define variable for the // total number of colors count = 0; // Set the height and width equal // to that of the canvas and the image height = canvas.height = imageElement.naturalHeight || imageElement.offsetHeight || imageElement.height; width = canvas.width = imageElement.naturalWidth || imageElement.offsetWidth || imageElement.width; // Draw the image to the canvas context.drawImage(imageElement, 0, 0); // Get the data of the image imgData = context.getImageData( 0, 0, width, height); // Get the length of image data object length = imgData.data.length; for (var i = 0; i < length; i += 4) { // Sum all values of red colour rgb.r += imgData.data[i]; // Sum all values of green colour rgb.g += imgData.data[i + 1]; // Sum all values of blue colour rgb.b += imgData.data[i + 2]; // Increment the total number of // values of rgb colours count++; } // Find the average of red rgb.r = Math.floor(rgb.r / count); // Find the average of green rgb.g = Math.floor(rgb.g / count); // Find the average of blue rgb.b = Math.floor(rgb.b / count); return rgb; } // Function to set the background // color of the second div as // calculated average color of image var rgb; setTimeout(() => { rgb = averageColor( document.getElementById('img')); // Select the element and set its // background color document .getElementById("block") .style.backgroundColor = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')'; }, 500) </script></body> </html>
Output:
varshagumber28
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
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)
|
[
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 25556,
"s": 25376,
"text": "The average color of an image can be found with JavaScript by drawing the image on a canvas element. The following steps have to be performed to get the average color of an image:"
},
{
"code": null,
"e": 25749,
"s": 25556,
"text": "1. The image is first drawn on the canvas using the method context.drawImage() of the Canvas 2D API. This method takes in the image and the dimensions as parameters and draws it to the canvas."
},
{
"code": null,
"e": 25757,
"s": 25749,
"text": "Syntax:"
},
{
"code": null,
"e": 25798,
"s": 25757,
"text": "context.drawImage( img, width, height );"
},
{
"code": null,
"e": 25982,
"s": 25798,
"text": "2. The image data of the canvas is returned using the context.getImageData() method. It returns an ImageData object representing the pixel data for a specified section of the canvas. "
},
{
"code": null,
"e": 25990,
"s": 25982,
"text": "Syntax:"
},
{
"code": null,
"e": 26034,
"s": 25990,
"text": "context.getImageData( x, y, width, height )"
},
{
"code": null,
"e": 26204,
"s": 26034,
"text": "3. The average red, green and blue colors are then calculated with this image data by adding all the color values separately and finding the average value of that color."
},
{
"code": null,
"e": 26213,
"s": 26204,
"text": "Example:"
},
{
"code": null,
"e": 26218,
"s": 26213,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Find Average Color of image via JavaScript? </title> <style> #img { position: absolute; top: 20%; left: 25%; } #block { position: absolute; background-color: white; height: 70px; width: 70px; left: 50%; top: 25%; } </style></head> <body> <img height=\"100px\" width=\"150px\" id=\"img\" src= \"image_to_find_average_color.png\"> <div id=\"block\"></div> <!-- Function to find the average color --> <script> function averageColor(imageElement) { // Create the canvas element var canvas = document.createElement('canvas'), // Get the 2D context of the canvas context = canvas.getContext && canvas.getContext('2d'), imgData, width, height, length, // Define variables for storing // the individual red, blue and // green colors rgb = { r: 0, g: 0, b: 0 }, // Define variable for the // total number of colors count = 0; // Set the height and width equal // to that of the canvas and the image height = canvas.height = imageElement.naturalHeight || imageElement.offsetHeight || imageElement.height; width = canvas.width = imageElement.naturalWidth || imageElement.offsetWidth || imageElement.width; // Draw the image to the canvas context.drawImage(imageElement, 0, 0); // Get the data of the image imgData = context.getImageData( 0, 0, width, height); // Get the length of image data object length = imgData.data.length; for (var i = 0; i < length; i += 4) { // Sum all values of red colour rgb.r += imgData.data[i]; // Sum all values of green colour rgb.g += imgData.data[i + 1]; // Sum all values of blue colour rgb.b += imgData.data[i + 2]; // Increment the total number of // values of rgb colours count++; } // Find the average of red rgb.r = Math.floor(rgb.r / count); // Find the average of green rgb.g = Math.floor(rgb.g / count); // Find the average of blue rgb.b = Math.floor(rgb.b / count); return rgb; } // Function to set the background // color of the second div as // calculated average color of image var rgb; setTimeout(() => { rgb = averageColor( document.getElementById('img')); // Select the element and set its // background color document .getElementById(\"block\") .style.backgroundColor = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')'; }, 500) </script></body> </html>",
"e": 29584,
"s": 26218,
"text": null
},
{
"code": null,
"e": 29592,
"s": 29584,
"text": "Output:"
},
{
"code": null,
"e": 29607,
"s": 29592,
"text": "varshagumber28"
},
{
"code": null,
"e": 29616,
"s": 29607,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29626,
"s": 29616,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29642,
"s": 29626,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29649,
"s": 29642,
"text": "Picked"
},
{
"code": null,
"e": 29653,
"s": 29649,
"text": "CSS"
},
{
"code": null,
"e": 29658,
"s": 29653,
"text": "HTML"
},
{
"code": null,
"e": 29669,
"s": 29658,
"text": "JavaScript"
},
{
"code": null,
"e": 29686,
"s": 29669,
"text": "Web Technologies"
},
{
"code": null,
"e": 29713,
"s": 29686,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29718,
"s": 29713,
"text": "HTML"
},
{
"code": null,
"e": 29816,
"s": 29718,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29853,
"s": 29816,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29882,
"s": 29853,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29921,
"s": 29882,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29963,
"s": 29921,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 30010,
"s": 29963,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 30070,
"s": 30010,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30131,
"s": 30070,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30184,
"s": 30131,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30234,
"s": 30184,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Difference between String and StringBuilder in C#
|
String is immutable in C# that would mean you couldn’t modify it after it is created. It creates a new object of string type in memory if you will perform any operation.
string str1 = "Welcome!";
// creates a new string instance
str1 += "Hello";
str1 += "World”;
StringBuilder is mutable in C#. This means that if an operation is performed on the string, it will not create a new instance every time. With that, it will not create new space in memory, unlike Strings.
StringBuilder str1 = new StringBuilder("");
str1.Append("Welcome!");
str1.Append("Hello World!");
string str2 = str1.ToString();
|
[
{
"code": null,
"e": 1232,
"s": 1062,
"text": "String is immutable in C# that would mean you couldn’t modify it after it is created. It creates a new object of string type in memory if you will perform any operation."
},
{
"code": null,
"e": 1326,
"s": 1232,
"text": "string str1 = \"Welcome!\";\n// creates a new string instance\nstr1 += \"Hello\";\nstr1 += \"World”;\n"
},
{
"code": null,
"e": 1531,
"s": 1326,
"text": "StringBuilder is mutable in C#. This means that if an operation is performed on the string, it will not create a new instance every time. With that, it will not create new space in memory, unlike Strings."
},
{
"code": null,
"e": 1661,
"s": 1531,
"text": "StringBuilder str1 = new StringBuilder(\"\");\nstr1.Append(\"Welcome!\");\nstr1.Append(\"Hello World!\");\nstring str2 = str1.ToString();\n"
}
] |
Create a Profit and Loss Calculator using JavaScript - GeeksforGeeks
|
10 Oct, 2021
In this article, we will create a profit & loss calculator using HTML, CSS & Javascript for adding the basic functionality along with adding the design and layout. Profit and Loss Calculator is basically used to calculate the amount or percentage received after selling a particular price or goods. If the amount(Selling Price) received is greater after selling than the actual amount(Cost Price), it is considered profit otherwise loss. We will denote cost price as CP & selling price as SP.
Formula Used:
Profit: (SP) – (CP)
Profit Percentage: Profit/CP x 100
Loss: (SP) – (CP)
Loss Percentage: Loss/CP x 100
Approach:
In the body tag, create the design and layout of the calculator using basic HTML.
Use CSS properties for stylings such as alignment, size, background, etc.
To calculate profit and loss call a function using JavaScript.
Example: We will use the above approach to create a calculator.
HTML
<div class="plcalculate"> <h1>Profit and Loss Calculator</h1> <p> Cost Price(CP) : <input class="cost__price" type="number" /> </p> <p> Selling Price(SP) : <input class="selling__price" type="number" /> </p> <button onclick="Calculate()">Calculate</button> <h2 class="profit__loss"></h2> <h2 class="profit__loss__percentage"></h2> <h2 class="nothing"></h2> </div>
CSS Code:
CSS
body { background-color: rgb(99, 226, 99); font-family: Verdana;}.plcalculate { text-align: center; background-color: rgb(102, 155, 22); width: 500px; margin-left: auto; margin-right: auto; padding: 10px;}h2 { color: white;}
Javascript:
Javascript
function Calculate() { const CP = document.querySelector(".cost__price").value; const SP = document.querySelector(".selling__price").value; const profit__loss = document.querySelector(".profit__loss"); const percentage = document.querySelector(".profit__loss__percentage"); const nothing = document.querySelector(".nothing"); profit__loss.innerHTML = ""; percentage.innerHTML = ""; nothing.innerHTML = ""; if (SP > CP) { const profit = SP - CP; const profit_percent = ((profit / CP) * 100).toFixed(2); profit__loss.innerHTML = "Profit : " + profit; percentage.innerHTML = "Profit Percentage : " + profit_percent; } if (SP < CP) { const loss = CP - SP; const loss_percent = ((loss / CP) * 100).toFixed(2); profit__loss.innerHTML = "Loss : " + loss; percentage.innerHTML = "Loss Percentage : " + loss_percent; } if (SP == CP) { nothing.innerHTML = "No Profit No Loss"; }};
Explanation: A Calculate() function will be invoked when the user enters the CP and SP amount in the input and clicks the Calculate button using the onclick event attribute. In this function, we have used DOM querySelector() method to select the value entered in the inputs into a variable using their class names. If the SP amount is greater than the CP amount then Calculate() function will calculate the profit and profit percentage otherwise calculate the loss and loss percentage using the above-mentioned formulae and displayed the text using the innerHTML property.
Complete Code:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Profit and Loss Calculator</title> <style> body{ background-color: rgb(99, 226, 99); font-family: Verdana; } .plcalculate{ text-align: center; background-color: rgb(102, 155, 22); width: 500px; margin-left: auto; margin-right: auto; padding: 10px; } h2{ color: white; } </style></head><body> <div class="plcalculate"> <h1>Profit and Loss Calculator</h1> <p>Cost Price(CP) : <input class="cost__price" type="number" /> </p> <p>Selling Price(SP) : <input class="selling__price" type="number" /> </p> <button onclick="Calculate()">Calculate</button> <p> <h2 class="profit__loss"></h2> <h2 class="profit__loss__percentage"></h2> <h2 class="nothing"></h2> </p> </div> <script> function Calculate(){ const CP= document.querySelector(".cost__price").value; const SP= document.querySelector(".selling__price").value; const profit__loss=document.querySelector(".profit__loss"); const percentage=document.querySelector(".profit__loss__percentage"); const nothing=document.querySelector(".nothing"); profit__loss.innerHTML=""; percentage.innerHTML=""; nothing.innerHTML=""; if(SP>CP){ const profit=SP - CP; const profit_percent= ((profit/CP)*100).toFixed(2); profit__loss.innerHTML="Profit : "+ profit; percentage.innerHTML="Profit Percentage : "+ profit_percent; } if(SP<CP){ const loss=CP - SP; const loss_percent= ((loss/CP)*100).toFixed(2); profit__loss.innerHTML="Loss : "+ loss; percentage.innerHTML="Loss Percentage : "+ loss_percent; } if(SP==CP){ nothing.innerHTML="No Profit No Loss"; } } </script></body></html>
Output:
CSS-Properties
CSS-Questions
HTML-Questions
JavaScript-Methods
JavaScript-Questions
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set input type date in dd-mm-yyyy format using HTML ?
HTML | <img> align Attribute
Form validation using HTML and JavaScript
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 25478,
"s": 24985,
"text": "In this article, we will create a profit & loss calculator using HTML, CSS & Javascript for adding the basic functionality along with adding the design and layout. Profit and Loss Calculator is basically used to calculate the amount or percentage received after selling a particular price or goods. If the amount(Selling Price) received is greater after selling than the actual amount(Cost Price), it is considered profit otherwise loss. We will denote cost price as CP & selling price as SP."
},
{
"code": null,
"e": 25493,
"s": 25478,
"text": "Formula Used: "
},
{
"code": null,
"e": 25513,
"s": 25493,
"text": "Profit: (SP) – (CP)"
},
{
"code": null,
"e": 25548,
"s": 25513,
"text": "Profit Percentage: Profit/CP x 100"
},
{
"code": null,
"e": 25566,
"s": 25548,
"text": "Loss: (SP) – (CP)"
},
{
"code": null,
"e": 25597,
"s": 25566,
"text": "Loss Percentage: Loss/CP x 100"
},
{
"code": null,
"e": 25607,
"s": 25597,
"text": "Approach:"
},
{
"code": null,
"e": 25689,
"s": 25607,
"text": "In the body tag, create the design and layout of the calculator using basic HTML."
},
{
"code": null,
"e": 25763,
"s": 25689,
"text": "Use CSS properties for stylings such as alignment, size, background, etc."
},
{
"code": null,
"e": 25826,
"s": 25763,
"text": "To calculate profit and loss call a function using JavaScript."
},
{
"code": null,
"e": 25890,
"s": 25826,
"text": "Example: We will use the above approach to create a calculator."
},
{
"code": null,
"e": 25895,
"s": 25890,
"text": "HTML"
},
{
"code": "<div class=\"plcalculate\"> <h1>Profit and Loss Calculator</h1> <p> Cost Price(CP) : <input class=\"cost__price\" type=\"number\" /> </p> <p> Selling Price(SP) : <input class=\"selling__price\" type=\"number\" /> </p> <button onclick=\"Calculate()\">Calculate</button> <h2 class=\"profit__loss\"></h2> <h2 class=\"profit__loss__percentage\"></h2> <h2 class=\"nothing\"></h2> </div>",
"e": 26321,
"s": 25895,
"text": null
},
{
"code": null,
"e": 26331,
"s": 26321,
"text": "CSS Code:"
},
{
"code": null,
"e": 26335,
"s": 26331,
"text": "CSS"
},
{
"code": "body { background-color: rgb(99, 226, 99); font-family: Verdana;}.plcalculate { text-align: center; background-color: rgb(102, 155, 22); width: 500px; margin-left: auto; margin-right: auto; padding: 10px;}h2 { color: white;}",
"e": 26569,
"s": 26335,
"text": null
},
{
"code": null,
"e": 26581,
"s": 26569,
"text": "Javascript:"
},
{
"code": null,
"e": 26592,
"s": 26581,
"text": "Javascript"
},
{
"code": "function Calculate() { const CP = document.querySelector(\".cost__price\").value; const SP = document.querySelector(\".selling__price\").value; const profit__loss = document.querySelector(\".profit__loss\"); const percentage = document.querySelector(\".profit__loss__percentage\"); const nothing = document.querySelector(\".nothing\"); profit__loss.innerHTML = \"\"; percentage.innerHTML = \"\"; nothing.innerHTML = \"\"; if (SP > CP) { const profit = SP - CP; const profit_percent = ((profit / CP) * 100).toFixed(2); profit__loss.innerHTML = \"Profit : \" + profit; percentage.innerHTML = \"Profit Percentage : \" + profit_percent; } if (SP < CP) { const loss = CP - SP; const loss_percent = ((loss / CP) * 100).toFixed(2); profit__loss.innerHTML = \"Loss : \" + loss; percentage.innerHTML = \"Loss Percentage : \" + loss_percent; } if (SP == CP) { nothing.innerHTML = \"No Profit No Loss\"; }};",
"e": 27514,
"s": 26592,
"text": null
},
{
"code": null,
"e": 28087,
"s": 27514,
"text": "Explanation: A Calculate() function will be invoked when the user enters the CP and SP amount in the input and clicks the Calculate button using the onclick event attribute. In this function, we have used DOM querySelector() method to select the value entered in the inputs into a variable using their class names. If the SP amount is greater than the CP amount then Calculate() function will calculate the profit and profit percentage otherwise calculate the loss and loss percentage using the above-mentioned formulae and displayed the text using the innerHTML property."
},
{
"code": null,
"e": 28102,
"s": 28087,
"text": "Complete Code:"
},
{
"code": null,
"e": 28107,
"s": 28102,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Profit and Loss Calculator</title> <style> body{ background-color: rgb(99, 226, 99); font-family: Verdana; } .plcalculate{ text-align: center; background-color: rgb(102, 155, 22); width: 500px; margin-left: auto; margin-right: auto; padding: 10px; } h2{ color: white; } </style></head><body> <div class=\"plcalculate\"> <h1>Profit and Loss Calculator</h1> <p>Cost Price(CP) : <input class=\"cost__price\" type=\"number\" /> </p> <p>Selling Price(SP) : <input class=\"selling__price\" type=\"number\" /> </p> <button onclick=\"Calculate()\">Calculate</button> <p> <h2 class=\"profit__loss\"></h2> <h2 class=\"profit__loss__percentage\"></h2> <h2 class=\"nothing\"></h2> </p> </div> <script> function Calculate(){ const CP= document.querySelector(\".cost__price\").value; const SP= document.querySelector(\".selling__price\").value; const profit__loss=document.querySelector(\".profit__loss\"); const percentage=document.querySelector(\".profit__loss__percentage\"); const nothing=document.querySelector(\".nothing\"); profit__loss.innerHTML=\"\"; percentage.innerHTML=\"\"; nothing.innerHTML=\"\"; if(SP>CP){ const profit=SP - CP; const profit_percent= ((profit/CP)*100).toFixed(2); profit__loss.innerHTML=\"Profit : \"+ profit; percentage.innerHTML=\"Profit Percentage : \"+ profit_percent; } if(SP<CP){ const loss=CP - SP; const loss_percent= ((loss/CP)*100).toFixed(2); profit__loss.innerHTML=\"Loss : \"+ loss; percentage.innerHTML=\"Loss Percentage : \"+ loss_percent; } if(SP==CP){ nothing.innerHTML=\"No Profit No Loss\"; } } </script></body></html>",
"e": 30179,
"s": 28107,
"text": null
},
{
"code": null,
"e": 30187,
"s": 30179,
"text": "Output:"
},
{
"code": null,
"e": 30202,
"s": 30187,
"text": "CSS-Properties"
},
{
"code": null,
"e": 30216,
"s": 30202,
"text": "CSS-Questions"
},
{
"code": null,
"e": 30231,
"s": 30216,
"text": "HTML-Questions"
},
{
"code": null,
"e": 30250,
"s": 30231,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 30271,
"s": 30250,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 30275,
"s": 30271,
"text": "CSS"
},
{
"code": null,
"e": 30280,
"s": 30275,
"text": "HTML"
},
{
"code": null,
"e": 30291,
"s": 30280,
"text": "JavaScript"
},
{
"code": null,
"e": 30308,
"s": 30291,
"text": "Web Technologies"
},
{
"code": null,
"e": 30313,
"s": 30308,
"text": "HTML"
},
{
"code": null,
"e": 30411,
"s": 30313,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30420,
"s": 30411,
"text": "Comments"
},
{
"code": null,
"e": 30433,
"s": 30420,
"text": "Old Comments"
},
{
"code": null,
"e": 30470,
"s": 30433,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30499,
"s": 30470,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30538,
"s": 30499,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30580,
"s": 30538,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 30615,
"s": 30580,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 30676,
"s": 30615,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30705,
"s": 30676,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 30747,
"s": 30705,
"text": "Form validation using HTML and JavaScript"
}
] |
Find product of prime numbers between 1 to n in C++
|
Suppose we have a number n. We have to find the product of prime numbers between 1 to n. So if n = 7, then output will be 210, as 2 * 3 * 5 * 7 = 210.
We will use the Sieve of Eratosthenes method to find all primes. Then calculate the product of them.
Live Demo
#include<iostream>
using namespace std;
long PrimeProds(int n) {
bool prime[n + 1];
for(int i = 0; i<=n; i++){
prime[i] = true;
}
for (int i = 2; i * i <= n; i++) {
if (prime[i] == true) {
for (int j = i * 2; j <= n; j += i)
prime[j] = false;
}
}
long product = 1;
for (int i = 2; i <= n; i++)
if (prime[i])
product *= i;
return product;
}
int main() {
int n = 8;
cout << "Product of primes up to " << n << " is: " << PrimeProds(n);
}
Product of primes up to 8 is: 210
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "Suppose we have a number n. We have to find the product of prime numbers between 1 to n. So if n = 7, then output will be 210, as 2 * 3 * 5 * 7 = 210."
},
{
"code": null,
"e": 1314,
"s": 1213,
"text": "We will use the Sieve of Eratosthenes method to find all primes. Then calculate the product of them."
},
{
"code": null,
"e": 1325,
"s": 1314,
"text": " Live Demo"
},
{
"code": null,
"e": 1835,
"s": 1325,
"text": "#include<iostream>\nusing namespace std;\nlong PrimeProds(int n) {\n bool prime[n + 1];\n for(int i = 0; i<=n; i++){\n prime[i] = true;\n }\n for (int i = 2; i * i <= n; i++) {\n if (prime[i] == true) {\n for (int j = i * 2; j <= n; j += i)\n prime[j] = false;\n }\n }\n long product = 1;\n for (int i = 2; i <= n; i++)\n if (prime[i])\n product *= i;\n return product;\n}\nint main() {\n int n = 8;\n cout << \"Product of primes up to \" << n << \" is: \" << PrimeProds(n);\n}"
},
{
"code": null,
"e": 1869,
"s": 1835,
"text": "Product of primes up to 8 is: 210"
}
] |
How to code a simple neural network in PyTorch? — for absolute beginners | by Harshanand B A | Towards Data Science
|
In this tutorial, we will see how to build a simple neural network for a classification problem using the PyTorch framework. This would help us to get a command over the fundamentals and framework’s basic syntaxes. For the same, we would be using Kaggle’s Titanic Dataset.
## For Windowspip install torch===1.5.0 torchvision===0.6.0 -f https://download.pytorch.org/whl/torch_stable.html## For Linuxpip install torch torchvision
If your computer configuration varies (either Conda based library or Mac system) you could check for the appropriate commands from this link.
First, download the dataset from Kaggle by joining the competition or you could get it from other sources too (Simple googling would help). Once you are setup with the dataset as well as PyTorch package we are ready to dive in further. Before designing the architecture the first and foremost thing to do is preparing your data according to PyTorch requirements which can be done using the Dataset module provided by PyTorch itself. If you find it difficult to comprehend let me dissect it for you. Most of the data that you will be dealing with will be Numpy structures. Now, this cannot be directly fed into the network since they are not tensors. Pytorch requires you to feed the data in the form of these tensors which is similar to any Numpy array except that it can also be moved to GPU while training. All your gradients, weights that your network deals with will be of the same tensor data structure. As you further read the blog you will be able to get a better understanding. So now, let’s load the data.
Now we import the Dataset module to inherit various functions such as __getitem__(), __len__(), etc predefined in the library. These functions would help us to create our custom class for initializing the dataset. The code below shows how to create a dataset class.
Note: In the above code the last column of our data frame contains the target class while rest are input features hence we split it out to self.inp and self.oup variables accordingly and we would need both inputs as well as output if we are going to train else only the input data would be needed.
The __init__() function reads the .csv file using the pandas data frame and we do some preprocessing on it later (which is irrelevant to this tutorial). The __len__ ()function returns the number of examples and __getitem__() is used to fetch data by using its index. The important thing to note from the above piece of code is that we have converted our training examples into a tensor using the torch.tensor function while calling it using its index. So throughout the tutorial wherever we fetch examples it will all be in the form of tensors.
Now since the data is ready let’s load it into batches. This can be done easily using the DataLoader function as below.
You have to pass your dataset object resulting from the previous function as your argument. According to the number of batches, the result will be a multidimensional tensor of the shape (no_of_batches, batch_size, size_of_the_vector). Now, the number of dimensions would vary for other kinds of data like Image or Sequential Data accordingly based on its nature. But for now, just understand that there are multiple batches and each batch contains some examples equal to batch size (Irrespective of whatever data you use).
Take a breath now... You’re halfway through. :)
Now since we have our data ready for training we have to design the neural network before we can start training it. Any model with conventionally used hyperparameters would be fine (Adam Optimizer, MSE Loss). To code our neural network, we can make use of the nn.Module to create the same.
nn.Linear(), nn.BatchNorm1d() all become available once you inherit nn.Module class(). You can then simply use them by calling it. Since we are using simple tabular data we can use a simple dense layer (or fully connected layer) to create the model. For activation, I have used swish() by a custom definition. One could go for ReLu also. ReLu is available in the nn.functional() module. You could simply replace swish() with F.relu(). Since its a binary classification it is not very necessary to use a softmax in the final layer. I have used the sigmoid function to classify my examples. In the above code, __init__() helps you to initialize your neural network model as soon as you call the constructor and forward() function controls the data flow through the network which makes it responsible for feedforward. As we proceed to the training loop you will see how we call the forward function.
Your training process can be laid as follow:
You define your training parameters like no of epochs, loss function, optimizer. All the optimizers are available in torch.optim(). Your optimizer function takes the weights of the network as its parameters. In the below code net variable contains the neural network model we created in the above subsection and net.parameters() refer to the network’s weights.
Every batch of data is fed into the network. Based on the loss function we calculate the loss for that particular batch. Once the loss is calculated we calculate the gradients by calling the backward() function. Once you calculate the gradients we update the existing weights. The same process happens for every batch in every epoch. As I mentioned earlier we could do the feedforward simply bypassing the input as an argument the neural network. (Like model(x) in the below code).
optimizer.step() is used to update the weights using the calculated gradients.
At the end of the epoch, we make predictions on validation data. Then finally we calculate the accuracy based on predictions from training as well as validation data.
To get an overall idea I have pasted my entire training loop below.
Based upon the available computational resources you could move your data and network to GPU using the code below. Remember whichever device your using all the input, output data, as well as the network, should be on the same device (Else, it would throw some silly errors :p).
You’re done with the tutorial... :) Be proud of yourself.
|
[
{
"code": null,
"e": 320,
"s": 47,
"text": "In this tutorial, we will see how to build a simple neural network for a classification problem using the PyTorch framework. This would help us to get a command over the fundamentals and framework’s basic syntaxes. For the same, we would be using Kaggle’s Titanic Dataset."
},
{
"code": null,
"e": 475,
"s": 320,
"text": "## For Windowspip install torch===1.5.0 torchvision===0.6.0 -f https://download.pytorch.org/whl/torch_stable.html## For Linuxpip install torch torchvision"
},
{
"code": null,
"e": 617,
"s": 475,
"text": "If your computer configuration varies (either Conda based library or Mac system) you could check for the appropriate commands from this link."
},
{
"code": null,
"e": 1632,
"s": 617,
"text": "First, download the dataset from Kaggle by joining the competition or you could get it from other sources too (Simple googling would help). Once you are setup with the dataset as well as PyTorch package we are ready to dive in further. Before designing the architecture the first and foremost thing to do is preparing your data according to PyTorch requirements which can be done using the Dataset module provided by PyTorch itself. If you find it difficult to comprehend let me dissect it for you. Most of the data that you will be dealing with will be Numpy structures. Now, this cannot be directly fed into the network since they are not tensors. Pytorch requires you to feed the data in the form of these tensors which is similar to any Numpy array except that it can also be moved to GPU while training. All your gradients, weights that your network deals with will be of the same tensor data structure. As you further read the blog you will be able to get a better understanding. So now, let’s load the data."
},
{
"code": null,
"e": 1898,
"s": 1632,
"text": "Now we import the Dataset module to inherit various functions such as __getitem__(), __len__(), etc predefined in the library. These functions would help us to create our custom class for initializing the dataset. The code below shows how to create a dataset class."
},
{
"code": null,
"e": 2196,
"s": 1898,
"text": "Note: In the above code the last column of our data frame contains the target class while rest are input features hence we split it out to self.inp and self.oup variables accordingly and we would need both inputs as well as output if we are going to train else only the input data would be needed."
},
{
"code": null,
"e": 2741,
"s": 2196,
"text": "The __init__() function reads the .csv file using the pandas data frame and we do some preprocessing on it later (which is irrelevant to this tutorial). The __len__ ()function returns the number of examples and __getitem__() is used to fetch data by using its index. The important thing to note from the above piece of code is that we have converted our training examples into a tensor using the torch.tensor function while calling it using its index. So throughout the tutorial wherever we fetch examples it will all be in the form of tensors."
},
{
"code": null,
"e": 2861,
"s": 2741,
"text": "Now since the data is ready let’s load it into batches. This can be done easily using the DataLoader function as below."
},
{
"code": null,
"e": 3384,
"s": 2861,
"text": "You have to pass your dataset object resulting from the previous function as your argument. According to the number of batches, the result will be a multidimensional tensor of the shape (no_of_batches, batch_size, size_of_the_vector). Now, the number of dimensions would vary for other kinds of data like Image or Sequential Data accordingly based on its nature. But for now, just understand that there are multiple batches and each batch contains some examples equal to batch size (Irrespective of whatever data you use)."
},
{
"code": null,
"e": 3432,
"s": 3384,
"text": "Take a breath now... You’re halfway through. :)"
},
{
"code": null,
"e": 3722,
"s": 3432,
"text": "Now since we have our data ready for training we have to design the neural network before we can start training it. Any model with conventionally used hyperparameters would be fine (Adam Optimizer, MSE Loss). To code our neural network, we can make use of the nn.Module to create the same."
},
{
"code": null,
"e": 4619,
"s": 3722,
"text": "nn.Linear(), nn.BatchNorm1d() all become available once you inherit nn.Module class(). You can then simply use them by calling it. Since we are using simple tabular data we can use a simple dense layer (or fully connected layer) to create the model. For activation, I have used swish() by a custom definition. One could go for ReLu also. ReLu is available in the nn.functional() module. You could simply replace swish() with F.relu(). Since its a binary classification it is not very necessary to use a softmax in the final layer. I have used the sigmoid function to classify my examples. In the above code, __init__() helps you to initialize your neural network model as soon as you call the constructor and forward() function controls the data flow through the network which makes it responsible for feedforward. As we proceed to the training loop you will see how we call the forward function."
},
{
"code": null,
"e": 4664,
"s": 4619,
"text": "Your training process can be laid as follow:"
},
{
"code": null,
"e": 5025,
"s": 4664,
"text": "You define your training parameters like no of epochs, loss function, optimizer. All the optimizers are available in torch.optim(). Your optimizer function takes the weights of the network as its parameters. In the below code net variable contains the neural network model we created in the above subsection and net.parameters() refer to the network’s weights."
},
{
"code": null,
"e": 5507,
"s": 5025,
"text": "Every batch of data is fed into the network. Based on the loss function we calculate the loss for that particular batch. Once the loss is calculated we calculate the gradients by calling the backward() function. Once you calculate the gradients we update the existing weights. The same process happens for every batch in every epoch. As I mentioned earlier we could do the feedforward simply bypassing the input as an argument the neural network. (Like model(x) in the below code)."
},
{
"code": null,
"e": 5586,
"s": 5507,
"text": "optimizer.step() is used to update the weights using the calculated gradients."
},
{
"code": null,
"e": 5753,
"s": 5586,
"text": "At the end of the epoch, we make predictions on validation data. Then finally we calculate the accuracy based on predictions from training as well as validation data."
},
{
"code": null,
"e": 5821,
"s": 5753,
"text": "To get an overall idea I have pasted my entire training loop below."
},
{
"code": null,
"e": 6099,
"s": 5821,
"text": "Based upon the available computational resources you could move your data and network to GPU using the code below. Remember whichever device your using all the input, output data, as well as the network, should be on the same device (Else, it would throw some silly errors :p)."
}
] |
C Program To Check Whether Two Strings Are Anagram Of Each Other - GeeksforGeeks
|
20 Dec, 2021
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other.
Method (Count characters): This method assumes that the set of possible characters in both strings is small. In the following implementation, it is assumed that the characters are stored using 8 bit and there can be 256 possible characters.
Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.Iterate through every character of both strings and increment the count of character in the corresponding count arrays.Compare count arrays. If both count arrays are same, then return true.
Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
Iterate through every character of both strings and increment the count of character in the corresponding count arrays.
Compare count arrays. If both count arrays are same, then return true.
Below is the implementation of the above idea:
C
// C program to check if two strings// are anagrams of each other#include <stdio.h>#define NO_OF_CHARS 256 /* Function to check whether two strings are anagram of each other */bool areAnagram(char* str1, char* str2){ // Create 2 count arrays and initialize // all values as 0 int count1[NO_OF_CHARS] = {0}; int count2[NO_OF_CHARS] = {0}; int i; // For each character in input strings, // increment count in the corresponding // count array for (i = 0; str1[i] && str2[i]; i++) { count1[str1[i]]++; count2[str2[i]]++; } // If both strings are of different length. // Removing this condition will make the // program fail for strings like "aaca" // and "aca" if (str1[i] || str2[i]) return false; // Compare count arrays for (i = 0; i < NO_OF_CHARS; i++) if (count1[i] != count2[i]) return false; return true;} // Driver codeint main(){ char str1[] = "geeksforgeeks"; char str2[] = "forgeeksgeeks"; // Function Call if (areAnagram(str1, str2)) printf( "The two strings are anagram of each other"); else printf("The two strings are not anagram of each " "other"); return 0;}
Output:
The two strings are anagram of each other
Please refer complete article on Check whether two strings are anagram of each other for more details!
Amazon
anagram
Goldman Sachs
Nagarro
C Programs
Strings
Amazon
Goldman Sachs
Nagarro
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 24930,
"s": 24902,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 25200,
"s": 24930,
"text": "Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other."
},
{
"code": null,
"e": 25442,
"s": 25200,
"text": "Method (Count characters): This method assumes that the set of possible characters in both strings is small. In the following implementation, it is assumed that the characters are stored using 8 bit and there can be 256 possible characters. "
},
{
"code": null,
"e": 25725,
"s": 25442,
"text": "Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.Iterate through every character of both strings and increment the count of character in the corresponding count arrays.Compare count arrays. If both count arrays are same, then return true."
},
{
"code": null,
"e": 25819,
"s": 25725,
"text": "Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0."
},
{
"code": null,
"e": 25939,
"s": 25819,
"text": "Iterate through every character of both strings and increment the count of character in the corresponding count arrays."
},
{
"code": null,
"e": 26010,
"s": 25939,
"text": "Compare count arrays. If both count arrays are same, then return true."
},
{
"code": null,
"e": 26057,
"s": 26010,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 26059,
"s": 26057,
"text": "C"
},
{
"code": "// C program to check if two strings// are anagrams of each other#include <stdio.h>#define NO_OF_CHARS 256 /* Function to check whether two strings are anagram of each other */bool areAnagram(char* str1, char* str2){ // Create 2 count arrays and initialize // all values as 0 int count1[NO_OF_CHARS] = {0}; int count2[NO_OF_CHARS] = {0}; int i; // For each character in input strings, // increment count in the corresponding // count array for (i = 0; str1[i] && str2[i]; i++) { count1[str1[i]]++; count2[str2[i]]++; } // If both strings are of different length. // Removing this condition will make the // program fail for strings like \"aaca\" // and \"aca\" if (str1[i] || str2[i]) return false; // Compare count arrays for (i = 0; i < NO_OF_CHARS; i++) if (count1[i] != count2[i]) return false; return true;} // Driver codeint main(){ char str1[] = \"geeksforgeeks\"; char str2[] = \"forgeeksgeeks\"; // Function Call if (areAnagram(str1, str2)) printf( \"The two strings are anagram of each other\"); else printf(\"The two strings are not anagram of each \" \"other\"); return 0;}",
"e": 27304,
"s": 26059,
"text": null
},
{
"code": null,
"e": 27313,
"s": 27304,
"text": "Output: "
},
{
"code": null,
"e": 27355,
"s": 27313,
"text": "The two strings are anagram of each other"
},
{
"code": null,
"e": 27458,
"s": 27355,
"text": "Please refer complete article on Check whether two strings are anagram of each other for more details!"
},
{
"code": null,
"e": 27465,
"s": 27458,
"text": "Amazon"
},
{
"code": null,
"e": 27473,
"s": 27465,
"text": "anagram"
},
{
"code": null,
"e": 27487,
"s": 27473,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 27495,
"s": 27487,
"text": "Nagarro"
},
{
"code": null,
"e": 27506,
"s": 27495,
"text": "C Programs"
},
{
"code": null,
"e": 27514,
"s": 27506,
"text": "Strings"
},
{
"code": null,
"e": 27521,
"s": 27514,
"text": "Amazon"
},
{
"code": null,
"e": 27535,
"s": 27521,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 27543,
"s": 27535,
"text": "Nagarro"
},
{
"code": null,
"e": 27551,
"s": 27543,
"text": "Strings"
},
{
"code": null,
"e": 27559,
"s": 27551,
"text": "anagram"
},
{
"code": null,
"e": 27657,
"s": 27559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27698,
"s": 27657,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27729,
"s": 27698,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 27770,
"s": 27729,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 27804,
"s": 27770,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 27829,
"s": 27804,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 27854,
"s": 27829,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27900,
"s": 27854,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 27934,
"s": 27900,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 27994,
"s": 27934,
"text": "Write a program to print all permutations of a given string"
}
] |
How to convert Integer array list to integer array in Java?
|
To convert integer array list to integer array is not a tedious task. First, create an integer array list and add some elements to it −
ArrayList < Integer > arrList = new ArrayList < Integer > ();
arrList.add(100);
arrList.add(200);
arrList.add(300);
arrList.add(400);
arrList.add(500);
Now, assign each value of the integer array list to integer array. We used size() to get the size of the integer array list and placed the same size to the newly created integer array −
final int[] arr = new int[arrList.size()];
int index = 0;
for (final Integer value: arrList) {
arr[index++] = value;
}
Live Demo
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) {
ArrayList<Integer>arrList = new ArrayList<Integer>();
arrList.add(100);
arrList.add(200);
arrList.add(300);
arrList.add(400);
arrList.add(500);
arrList.add(600);
arrList.add(700);
arrList.add(800);
arrList.add(900);
arrList.add(1000);
final int[] arr = new int[arrList.size()];
int index = 0;
for (final Integer value : arrList) {
arr[index++] = value;
}
System.out.println("Elements of int array...");
for (Integer i : arr) {
System.out.println(i);
}
}
}
Elements of int array...
100
200
300
400
500
600
700
800
900
1000
|
[
{
"code": null,
"e": 1198,
"s": 1062,
"text": "To convert integer array list to integer array is not a tedious task. First, create an integer array list and add some elements to it −"
},
{
"code": null,
"e": 1350,
"s": 1198,
"text": "ArrayList < Integer > arrList = new ArrayList < Integer > ();\narrList.add(100);\narrList.add(200);\narrList.add(300);\narrList.add(400);\narrList.add(500);"
},
{
"code": null,
"e": 1536,
"s": 1350,
"text": "Now, assign each value of the integer array list to integer array. We used size() to get the size of the integer array list and placed the same size to the newly created integer array −"
},
{
"code": null,
"e": 1658,
"s": 1536,
"text": "final int[] arr = new int[arrList.size()];\nint index = 0;\nfor (final Integer value: arrList) {\n arr[index++] = value;\n}"
},
{
"code": null,
"e": 1669,
"s": 1658,
"text": " Live Demo"
},
{
"code": null,
"e": 2346,
"s": 1669,
"text": "import java.util.ArrayList;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<Integer>arrList = new ArrayList<Integer>();\n arrList.add(100);\n arrList.add(200);\n arrList.add(300);\n arrList.add(400);\n arrList.add(500);\n arrList.add(600);\n arrList.add(700);\n arrList.add(800);\n arrList.add(900);\n arrList.add(1000);\n final int[] arr = new int[arrList.size()];\n int index = 0;\n for (final Integer value : arrList) {\n arr[index++] = value;\n }\n System.out.println(\"Elements of int array...\");\n for (Integer i : arr) {\n System.out.println(i);\n }\n }\n}"
},
{
"code": null,
"e": 2412,
"s": 2346,
"text": "Elements of int array...\n100\n200\n300\n400\n500\n600\n700\n800\n900\n1000"
}
] |
JSP - Interview Questions
|
Dear readers, these JSP Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of JSP. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
JavaServer Pages (JSP) is a technology for developing Webpages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.
JSP offer several advantages as listed below −
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself.
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
The advantages of JSP are twofold.
First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.
It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. Other advantages are −
Embedding of Java code in HTML pages.
Embedding of Java code in HTML pages.
Platform independence.
Platform independence.
Creation of database-driven Web applications.
Creation of database-driven Web applications.
Server-side programming capabilities.
Server-side programming capabilities.
SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.
JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.
Regular HTML, of course, cannot contain dynamic information.
A JSP Lifecycle consists of following steps −
Compilation − When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps −
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
Compilation − When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps −
Parsing the JSP.
Parsing the JSP.
Turning the JSP into a servlet.
Turning the JSP into a servlet.
Compiling the servlet.
Compiling the servlet.
Initialization − When a container loads a JSP it invokes the jspInit() method before servicing any requests
Initialization − When a container loads a JSP it invokes the jspInit() method before servicing any requests
Execution − Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
Execution − Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
Cleanup − The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Cleanup − The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet −
<% code fragment %>
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file.
<%! declaration; [ declaration; ]+ ... %>
A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
Its syntax is −
<%= expression %>
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments −
<%-- This is JSP comment --%>
A JSP directive affects the overall structure of the servlet class. It usually has the following form −
<%@ directive attribute = "value" %>
The types directive tags are as follows −
<%@ page ... %> − Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ page ... %> − Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %> − Includes a file during the translation phase.
<%@ include ... %> − Includes a file during the translation phase.
<%@ taglib ... %> − Declares a tag library, containing custom actions, used in the page.
<%@ taglib ... %> − Declares a tag library, containing custom actions, used in the page.
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
Its syntax is as follows −
<jsp:action_name attribute = "value" />
jsp:include, jsp:useBean,jsp:setProperty,jsp:getProperty, jsp:forward,jsp:plugin,jsp:element, jsp:attribute, jsp:body, jsp:text
Literals are the values, such as a number or a text string, that are written literally as part of a program code. The JSP expression language defines the following literals −
Boolean − true and false
Boolean − true and false
Integer − as in Java
Integer − as in Java
Floating point − as in Java
Floating point − as in Java
String − with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
String − with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
Null − null
Null − null
The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page.
Page directive contains the following 13 attributes.
language
extends
import
session
isThreadSafe
info
errorPage
isErrorpage
contentType
isELIgnored
buffer
autoFlush
isScriptingEnabled
language
language
extends
extends
import
import
session
session
isThreadSafe
isThreadSafe
info
info
errorPage
errorPage
isErrorpage
isErrorpage
contentType
contentType
isELIgnored
isELIgnored
buffer
buffer
autoFlush
autoFlush
isScriptingEnabled
isScriptingEnabled
The buffer attribute specifies buffering characteristics for the server output response object.
When buffer is set to “none”, servlet output is immediately directed to the response output object.
The autoFlush attribute specifies whether buffered output should be flushed automatically when the buffer is filled, or whether an exception should be raised to indicate buffer overflow.
A value of true (default) indicates automatic buffer flushing and a value of false throws an exception.
The contentType attribute sets the character encoding for the JSP page and for the generated response page. The default content type is text/html, which is the standard content type for HTML pages.
The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL.
The isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP.
The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false.
The extends attribute specifies a superclass that the generated servlet must extend.
The import attribute serves the same function as, and behaves like, the Java import statement. The value for the import option is the name of the package you want to import.
The info attribute lets you provide a description of the JSP.
The isThreadSafe option marks a page as being thread-safe. By default, all JSPs are considered thread-safe. If you set the isThreadSafe option to false, the JSP engine makes sure that only one thread at a time is executing your JSP.
The language attribute indicates the programming language used in scripting the JSP page.
The session attribute indicates whether or not the JSP page uses HTTP sessions. A value of true means that the JSP page has access to a builtin session object and a value of false means that the JSP page cannot access the builtin session object.
The isELIgnored option gives you the ability to disable the evaluation of Expression Language (EL) expressions.
The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.
The isScriptingEnabled attribute determines if scripting elements are allowed for use.
The default value (true) enables scriptlets, expressions, and declarations. If the attribute's value is set to false, a translation-time error will be raised if the JSP uses any scriptlets, expressions (non-EL), or declarations.
The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows −
<%@ include file = "relative url" >
The taglib directive follows the following syntax −
<%@ taglib uri = "uri" prefix = "prefixOfTag">
uri attribute value resolves to a location the container understands
prefix attribute informs a container what bits of markup are custom actions.
The taglib directive follows the following syntax −
<%@ taglib uri = "uri" prefix = "prefixOfTag" >
Id attribute − The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext
Id attribute − The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext
Scope attribute − This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.
Scope attribute − This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.
This action lets you insert files into the page being generated. The syntax looks like this −
<jsp:include page = "relative URL" flush = "true" />
Where page is the relative URL of the page to be included.
Flush is the boolean attribute the determines whether the included resource has its buffer flushed before it is included.
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, include action inserts the file at the time the page is requested.
The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows −
<jsp:useBean id = "name" class = "package.class" />
The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action.
The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.
The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet.
The simple syntax of this action is as follows −
<jsp:forward page = "Relative URL" />
The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean.
The scope attribute identifies the lifecycle of the Action element. It has four possible values: (a) page, (b)request, (c)session, and (d) application.
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
request, response, out, session, application, config, pageContext, page, Exception
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.
Using getHeaderNames() method of HttpServletRequest to read the HTTP header information. This method returns an Enumeration that contains the header information associated with the current HTTP request.
The response object is an instance of a javax.servlet.http.HttpServletRequest object. Just as the server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.
The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.
The session object is an instance of javax.servlet.http.HttpSession and is used to track client session between client requests
The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.
The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.
This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.
The page object is really a direct synonym for the this object.
The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? Character.
The POST method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing.
JSP handles form data parsing automatically using the following methods depending on the situation −
getParameter() − You call request.getParameter() method to get the value of a form parameter.
getParameter() − You call request.getParameter() method to get the value of a form parameter.
getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters in the current request.
getParameterNames() − Call this method if you want a complete list of all parameters in the current request.
getInputStream() − Call this method to read binary data stream coming from the client.
getInputStream() − Call this method to read binary data stream coming from the client.
JSP Filters are Java classes that can be used in JSP Programming for the following purposes −
To intercept requests from a client before they access a resource at back end.
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
To manipulate responses from server before they are sent back to the client.
Filters are defined in the deployment descriptor file web.xml and then mapped to either servlet or JSP names or URL patterns in your application's deployment descriptor.
When the JSP container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
Cookies are text files stored on the client computer and they are kept for various information tracking purpose.
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser).If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.
Setting cookies with JSP involves three steps −
Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid.
Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid.
Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header
Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps −
Read an already existing cookie and store it in Cookie object.
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
Add this cookie back into response header.
Add this cookie back into response header.
Session management can be achieved by the use of −
Cookies − A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
Cookies − A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
Hidden Form Fields − A web server can send a hidden HTML form field along with a unique session ID as follows −
Hidden Form Fields − A web server can send a hidden HTML form field along with a unique session ID as follows −
<input type = "hidden" name = "sessionid" value = "12345">
This implies that when the form is submitted, the specified name and value will be getting included in GET or POST method.
URL Rewriting − In URL rewriting some extra information is added on the end of each URL that identifies the session. This URL rewriting can be useful where a cookie is disabled.
URL Rewriting − In URL rewriting some extra information is added on the end of each URL that identifies the session. This URL rewriting can be useful where a cookie is disabled.
The session Object − JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
The session Object − JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
When you are done with a user's session data, you have several options −
Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with the a particular key.
Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with the a particular key.
Delete the whole session − You can call public void invalidate() method to discard an entire session.
Delete the whole session − You can call public void invalidate() method to discard an entire session.
Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.
web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.
To upload a single file you should use a single <input .../> tag with attribute type = "file".To allow multiple files uploading, include more than one input tags with different values for the name attribute.
You can hard code this in your program or this directory name could also be added using an external configuration such as a context-param element in web.xml.
Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization.
The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page.
A hit counter tells you about the number of visits on a particular page of your web site.
To implement a hit counter you can make use of Application Implicit object and associated methods getAttribute() and setAttribute().
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
You can follow the below steps −
Define a database table with a single count, let us say hitcount. Assign a zero value to it.
Define a database table with a single count, let us say hitcount. Assign a zero value to it.
With every hit, read the table to get the value of hitcount.
With every hit, read the table to get the value of hitcount.
Increase the value of hitcount by one and update the table with new value.
Increase the value of hitcount by one and update the table with new value.
Display new value of hitcount as total page hit counts.
Display new value of hitcount as total page hit counts.
If you want to count hits for all the pages, implement above logic for all the pages.
If you want to count hits for all the pages, implement above logic for all the pages.
Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your Webpage regularly using refresh or reload button with your browser.
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.
The simplest way of refreshing a Webpage is using method setIntHeader() of response object. Following is the signature of this method −
public void setIntHeader(String header, int headerValue)
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags.
Types of JSTL tags are −
Core Tags
Core Tags
Formatting tags
Formatting tags
SQL tags
SQL tags
XML tags
XML tags
JSTL Functions
JSTL Functions
The <c:set > tag is JSTL-friendly version of the setProperty action. The tag is helpful because it evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map object.
The <c:remove > tag removes a variable from either a specified scope or the first scope where the variable is found (if no scope is specified).
The <c:catch> tag catches any Throwable that occurs in its body and optionally exposes it. Simply it is used for error handling and to deal more gracefully with the problem.
The <c:if> tag evaluates an expression and displays its body content only if the expression evaluates to true.
The <c:choose> works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <c:choose> tag has <c:when> tags. A a switch statement has default clause to specify a default action and similar way <c:choose> has <otherwise> as default clause.
The <c:forEach >, <c:forTokens> tags exist as a good alternative to embedding a Java for, while, or do-while loop via a scriptlet.
The <c:param> tag allows proper URL request parameter to be specified with URL and it does any necessary URL encoding required.
The <c:redirect > tag redirects the browser to an alternate URL by providing automatically URL rewriting, it supports context-relative URLs, and it supports the <c:param> tag.
The <c:url> tag formats a URL into a string and stores it into a variable. This tag automatically performs URL rewriting when necessary.
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites. Following is the syntax to include Formatting library in your JSP −
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP −
<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. Following is the syntax to include JSTL XML library in your JSP.
<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>
A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.
JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. A simple syntax for JSP EL is −
${expr}
Here expr specifies the expression itself.
The JSP expression language supports the following implicit objects −
pageScope − Scoped variables from page scope
pageScope − Scoped variables from page scope
requestScope − Scoped variables from request scope
requestScope − Scoped variables from request scope
sessionScope − Scoped variables from session scope
sessionScope − Scoped variables from session scope
applicationScope − Scoped variables from application scope
applicationScope − Scoped variables from application scope
param − Request parameters as strings
param − Request parameters as strings
paramValues − Request parameters as collections of strings
paramValues − Request parameters as collections of strings
headerHTTP − request headers as strings
headerHTTP − request headers as strings
headerValues − HTTP request headers as collections of strings
headerValues − HTTP request headers as collections of strings
initParam − Context-initialization parameters
initParam − Context-initialization parameters
cookie − Cookie values
cookie − Cookie values
pageContext − The JSP PageContext object for the current page
pageContext − The JSP PageContext object for the current page
We can disable using isELIgnored attribute of the page directive −
<%@ page isELIgnored = "true|false" %>
If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.
Checked exceptions − Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
Checked exceptions − Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions − A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Runtime exceptions − A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
Example: <%@ page errorPage = "error.jsp" %>
It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage="true" %>
Internationalization means enabling a web site to provide different versions of content translated into the visitor's language or nationality.
Localization means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site.
This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example "en_US" represents english locale for US.
<%-- comment --%> is JSP comment and is ignored by the JSP engine.
<!-- comment --> is an HTML comment and is ignored by the browser.
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.
Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression.
Use the following ways to pass control of a request from one servlet to another or one jsp to another −
The RequestDispatcher object ‘s forward method to pass the control.
The RequestDispatcher object ‘s forward method to pass the control.
Using the response.sendRedirect method.
Using the response.sendRedirect method.
No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.
A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not.
<%@ page session = "false">
Using <%jsp:param> tag.
We can override jspinit() and jspDestroy() methods but not _jspService().
_jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.
It causes compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error.
Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows −
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
If we want to make our data available to the entire application then we have to use application scope.
In JSP, we can perform inclusion in the following ways −
By include directive − For example −
By include directive − For example −
<%@ include file = ”header.jsp” %>
By include action − For example −
By include action − For example −
<%@ include file = ”header.jsp” %>
By using pageContext implicit object For example −
By using pageContext implicit object For example −
<% pageContext.include(“/header.jsp”); %>
By using RequestDispatcher object − For example −
By using RequestDispatcher object − For example −
<%
RequestDispatcher rd = request.getRequestDispatcher(“/header.jsp”);
Rd.include(request,response);
%>
JSP engines will always instantiate a new tag handler instance every time a tag is encountered in a JSP page. A pool of tag instances are maintained and reusing them where possible. When a tag is encountered, the JSP engine will try to find a Tag instance that is not being used and use the same and then release it.
JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them −
Taglibs are for generating presentation elements while JavaBeans are good for storing information and state.
Taglibs are for generating presentation elements while JavaBeans are good for storing information and state.
Use custom tags to implement actions and JavaBeans to present information.
Use custom tags to implement actions and JavaBeans to present information.
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2670,
"s": 2239,
"text": "Dear readers, these JSP Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of JSP. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −"
},
{
"code": null,
"e": 2896,
"s": 2670,
"text": "JavaServer Pages (JSP) is a technology for developing Webpages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>."
},
{
"code": null,
"e": 2943,
"s": 2896,
"text": "JSP offer several advantages as listed below −"
},
{
"code": null,
"e": 3047,
"s": 2943,
"text": "Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself."
},
{
"code": null,
"e": 3151,
"s": 3047,
"text": "Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself."
},
{
"code": null,
"e": 3331,
"s": 3151,
"text": "JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested."
},
{
"code": null,
"e": 3511,
"s": 3331,
"text": "JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested."
},
{
"code": null,
"e": 3688,
"s": 3511,
"text": "JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc."
},
{
"code": null,
"e": 3865,
"s": 3688,
"text": "JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc."
},
{
"code": null,
"e": 4002,
"s": 3865,
"text": "JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines."
},
{
"code": null,
"e": 4139,
"s": 4002,
"text": "JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines."
},
{
"code": null,
"e": 4174,
"s": 4139,
"text": "The advantages of JSP are twofold."
},
{
"code": null,
"e": 4308,
"s": 4174,
"text": "First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use."
},
{
"code": null,
"e": 4389,
"s": 4308,
"text": "Second, it is portable to other operating systems and non-Microsoft Web servers."
},
{
"code": null,
"e": 4539,
"s": 4389,
"text": "It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. Other advantages are −"
},
{
"code": null,
"e": 4577,
"s": 4539,
"text": "Embedding of Java code in HTML pages."
},
{
"code": null,
"e": 4615,
"s": 4577,
"text": "Embedding of Java code in HTML pages."
},
{
"code": null,
"e": 4638,
"s": 4615,
"text": "Platform independence."
},
{
"code": null,
"e": 4661,
"s": 4638,
"text": "Platform independence."
},
{
"code": null,
"e": 4707,
"s": 4661,
"text": "Creation of database-driven Web applications."
},
{
"code": null,
"e": 4753,
"s": 4707,
"text": "Creation of database-driven Web applications."
},
{
"code": null,
"e": 4791,
"s": 4753,
"text": "Server-side programming capabilities."
},
{
"code": null,
"e": 4829,
"s": 4791,
"text": "Server-side programming capabilities."
},
{
"code": null,
"e": 4965,
"s": 4829,
"text": "SSI is really only intended for simple inclusions, not for \"real\" programs that use form data, make database connections, and the like."
},
{
"code": null,
"e": 5136,
"s": 4965,
"text": "JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc."
},
{
"code": null,
"e": 5197,
"s": 5136,
"text": "Regular HTML, of course, cannot contain dynamic information."
},
{
"code": null,
"e": 5243,
"s": 5197,
"text": "A JSP Lifecycle consists of following steps −"
},
{
"code": null,
"e": 5614,
"s": 5243,
"text": "Compilation − When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.\nThe compilation process involves three steps −\n\nParsing the JSP.\nTurning the JSP into a servlet.\nCompiling the servlet.\n\n"
},
{
"code": null,
"e": 5863,
"s": 5614,
"text": "Compilation − When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page."
},
{
"code": null,
"e": 5910,
"s": 5863,
"text": "The compilation process involves three steps −"
},
{
"code": null,
"e": 5927,
"s": 5910,
"text": "Parsing the JSP."
},
{
"code": null,
"e": 5944,
"s": 5927,
"text": "Parsing the JSP."
},
{
"code": null,
"e": 5976,
"s": 5944,
"text": "Turning the JSP into a servlet."
},
{
"code": null,
"e": 6008,
"s": 5976,
"text": "Turning the JSP into a servlet."
},
{
"code": null,
"e": 6031,
"s": 6008,
"text": "Compiling the servlet."
},
{
"code": null,
"e": 6054,
"s": 6031,
"text": "Compiling the servlet."
},
{
"code": null,
"e": 6162,
"s": 6054,
"text": "Initialization − When a container loads a JSP it invokes the jspInit() method before servicing any requests"
},
{
"code": null,
"e": 6270,
"s": 6162,
"text": "Initialization − When a container loads a JSP it invokes the jspInit() method before servicing any requests"
},
{
"code": null,
"e": 6670,
"s": 6270,
"text": "Execution − Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc."
},
{
"code": null,
"e": 7070,
"s": 6670,
"text": "Execution − Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc."
},
{
"code": null,
"e": 7269,
"s": 7070,
"text": "Cleanup − The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets."
},
{
"code": null,
"e": 7468,
"s": 7269,
"text": "Cleanup − The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets."
},
{
"code": null,
"e": 7627,
"s": 7468,
"text": "A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language."
},
{
"code": null,
"e": 7666,
"s": 7627,
"text": "Following is the syntax of Scriptlet −"
},
{
"code": null,
"e": 7687,
"s": 7666,
"text": "<% code fragment %>\n"
},
{
"code": null,
"e": 7871,
"s": 7687,
"text": "A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file."
},
{
"code": null,
"e": 7914,
"s": 7871,
"text": "<%! declaration; [ declaration; ]+ ... %>\n"
},
{
"code": null,
"e": 8081,
"s": 7914,
"text": "A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file."
},
{
"code": null,
"e": 8243,
"s": 8081,
"text": "The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression."
},
{
"code": null,
"e": 8259,
"s": 8243,
"text": "Its syntax is −"
},
{
"code": null,
"e": 8278,
"s": 8259,
"text": "<%= expression %>\n"
},
{
"code": null,
"e": 8439,
"s": 8278,
"text": "JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or \"comment out\" part of your JSP page."
},
{
"code": null,
"e": 8481,
"s": 8439,
"text": "Following is the syntax of JSP comments −"
},
{
"code": null,
"e": 8512,
"s": 8481,
"text": "<%-- This is JSP comment --%>\n"
},
{
"code": null,
"e": 8616,
"s": 8512,
"text": "A JSP directive affects the overall structure of the servlet class. It usually has the following form −"
},
{
"code": null,
"e": 8654,
"s": 8616,
"text": "<%@ directive attribute = \"value\" %>\n"
},
{
"code": null,
"e": 8696,
"s": 8654,
"text": "The types directive tags are as follows −"
},
{
"code": null,
"e": 8817,
"s": 8696,
"text": "<%@ page ... %> − Defines page-dependent attributes, such as scripting language, error page, and buffering requirements."
},
{
"code": null,
"e": 8938,
"s": 8817,
"text": "<%@ page ... %> − Defines page-dependent attributes, such as scripting language, error page, and buffering requirements."
},
{
"code": null,
"e": 9005,
"s": 8938,
"text": "<%@ include ... %> − Includes a file during the translation phase."
},
{
"code": null,
"e": 9072,
"s": 9005,
"text": "<%@ include ... %> − Includes a file during the translation phase."
},
{
"code": null,
"e": 9161,
"s": 9072,
"text": "<%@ taglib ... %> − Declares a tag library, containing custom actions, used in the page."
},
{
"code": null,
"e": 9250,
"s": 9161,
"text": "<%@ taglib ... %> − Declares a tag library, containing custom actions, used in the page."
},
{
"code": null,
"e": 9473,
"s": 9250,
"text": "JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin."
},
{
"code": null,
"e": 9500,
"s": 9473,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 9541,
"s": 9500,
"text": "<jsp:action_name attribute = \"value\" />\n"
},
{
"code": null,
"e": 9669,
"s": 9541,
"text": "jsp:include, jsp:useBean,jsp:setProperty,jsp:getProperty, jsp:forward,jsp:plugin,jsp:element, jsp:attribute, jsp:body, jsp:text"
},
{
"code": null,
"e": 9844,
"s": 9669,
"text": "Literals are the values, such as a number or a text string, that are written literally as part of a program code. The JSP expression language defines the following literals −"
},
{
"code": null,
"e": 9869,
"s": 9844,
"text": "Boolean − true and false"
},
{
"code": null,
"e": 9894,
"s": 9869,
"text": "Boolean − true and false"
},
{
"code": null,
"e": 9915,
"s": 9894,
"text": "Integer − as in Java"
},
{
"code": null,
"e": 9936,
"s": 9915,
"text": "Integer − as in Java"
},
{
"code": null,
"e": 9964,
"s": 9936,
"text": "Floating point − as in Java"
},
{
"code": null,
"e": 9992,
"s": 9964,
"text": "Floating point − as in Java"
},
{
"code": null,
"e": 10096,
"s": 9992,
"text": "String − with single and double quotes; \" is escaped as \\\", ' is escaped as \\', and \\ is escaped as \\\\."
},
{
"code": null,
"e": 10200,
"s": 10096,
"text": "String − with single and double quotes; \" is escaped as \\\", ' is escaped as \\', and \\ is escaped as \\\\."
},
{
"code": null,
"e": 10212,
"s": 10200,
"text": "Null − null"
},
{
"code": null,
"e": 10224,
"s": 10212,
"text": "Null − null"
},
{
"code": null,
"e": 10386,
"s": 10224,
"text": "The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page."
},
{
"code": null,
"e": 10439,
"s": 10386,
"text": "Page directive contains the following 13 attributes."
},
{
"code": null,
"e": 10573,
"s": 10439,
"text": "\nlanguage\nextends\nimport\nsession\nisThreadSafe\ninfo\nerrorPage\nisErrorpage\ncontentType\nisELIgnored\nbuffer\nautoFlush\nisScriptingEnabled\n"
},
{
"code": null,
"e": 10582,
"s": 10573,
"text": "language"
},
{
"code": null,
"e": 10591,
"s": 10582,
"text": "language"
},
{
"code": null,
"e": 10599,
"s": 10591,
"text": "extends"
},
{
"code": null,
"e": 10607,
"s": 10599,
"text": "extends"
},
{
"code": null,
"e": 10614,
"s": 10607,
"text": "import"
},
{
"code": null,
"e": 10621,
"s": 10614,
"text": "import"
},
{
"code": null,
"e": 10629,
"s": 10621,
"text": "session"
},
{
"code": null,
"e": 10637,
"s": 10629,
"text": "session"
},
{
"code": null,
"e": 10650,
"s": 10637,
"text": "isThreadSafe"
},
{
"code": null,
"e": 10663,
"s": 10650,
"text": "isThreadSafe"
},
{
"code": null,
"e": 10668,
"s": 10663,
"text": "info"
},
{
"code": null,
"e": 10673,
"s": 10668,
"text": "info"
},
{
"code": null,
"e": 10683,
"s": 10673,
"text": "errorPage"
},
{
"code": null,
"e": 10693,
"s": 10683,
"text": "errorPage"
},
{
"code": null,
"e": 10705,
"s": 10693,
"text": "isErrorpage"
},
{
"code": null,
"e": 10717,
"s": 10705,
"text": "isErrorpage"
},
{
"code": null,
"e": 10729,
"s": 10717,
"text": "contentType"
},
{
"code": null,
"e": 10741,
"s": 10729,
"text": "contentType"
},
{
"code": null,
"e": 10753,
"s": 10741,
"text": "isELIgnored"
},
{
"code": null,
"e": 10765,
"s": 10753,
"text": "isELIgnored"
},
{
"code": null,
"e": 10772,
"s": 10765,
"text": "buffer"
},
{
"code": null,
"e": 10779,
"s": 10772,
"text": "buffer"
},
{
"code": null,
"e": 10789,
"s": 10779,
"text": "autoFlush"
},
{
"code": null,
"e": 10799,
"s": 10789,
"text": "autoFlush"
},
{
"code": null,
"e": 10818,
"s": 10799,
"text": "isScriptingEnabled"
},
{
"code": null,
"e": 10837,
"s": 10818,
"text": "isScriptingEnabled"
},
{
"code": null,
"e": 10933,
"s": 10837,
"text": "The buffer attribute specifies buffering characteristics for the server output response object."
},
{
"code": null,
"e": 11033,
"s": 10933,
"text": "When buffer is set to “none”, servlet output is immediately directed to the response output object."
},
{
"code": null,
"e": 11220,
"s": 11033,
"text": "The autoFlush attribute specifies whether buffered output should be flushed automatically when the buffer is filled, or whether an exception should be raised to indicate buffer overflow."
},
{
"code": null,
"e": 11324,
"s": 11220,
"text": "A value of true (default) indicates automatic buffer flushing and a value of false throws an exception."
},
{
"code": null,
"e": 11522,
"s": 11324,
"text": "The contentType attribute sets the character encoding for the JSP page and for the generated response page. The default content type is text/html, which is the standard content type for HTML pages."
},
{
"code": null,
"e": 11695,
"s": 11522,
"text": "The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL."
},
{
"code": null,
"e": 11799,
"s": 11695,
"text": "The isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP."
},
{
"code": null,
"e": 11906,
"s": 11799,
"text": "The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false."
},
{
"code": null,
"e": 11991,
"s": 11906,
"text": "The extends attribute specifies a superclass that the generated servlet must extend."
},
{
"code": null,
"e": 12165,
"s": 11991,
"text": "The import attribute serves the same function as, and behaves like, the Java import statement. The value for the import option is the name of the package you want to import."
},
{
"code": null,
"e": 12227,
"s": 12165,
"text": "The info attribute lets you provide a description of the JSP."
},
{
"code": null,
"e": 12460,
"s": 12227,
"text": "The isThreadSafe option marks a page as being thread-safe. By default, all JSPs are considered thread-safe. If you set the isThreadSafe option to false, the JSP engine makes sure that only one thread at a time is executing your JSP."
},
{
"code": null,
"e": 12550,
"s": 12460,
"text": "The language attribute indicates the programming language used in scripting the JSP page."
},
{
"code": null,
"e": 12796,
"s": 12550,
"text": "The session attribute indicates whether or not the JSP page uses HTTP sessions. A value of true means that the JSP page has access to a builtin session object and a value of false means that the JSP page cannot access the builtin session object."
},
{
"code": null,
"e": 12908,
"s": 12796,
"text": "The isELIgnored option gives you the ability to disable the evaluation of Expression Language (EL) expressions."
},
{
"code": null,
"e": 13142,
"s": 12908,
"text": "The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text."
},
{
"code": null,
"e": 13229,
"s": 13142,
"text": "The isScriptingEnabled attribute determines if scripting elements are allowed for use."
},
{
"code": null,
"e": 13458,
"s": 13229,
"text": "The default value (true) enables scriptlets, expressions, and declarations. If the attribute's value is set to false, a translation-time error will be raised if the JSP uses any scriptlets, expressions (non-EL), or declarations."
},
{
"code": null,
"e": 13727,
"s": 13458,
"text": "The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page."
},
{
"code": null,
"e": 13784,
"s": 13727,
"text": "The general usage form of this directive is as follows −"
},
{
"code": null,
"e": 13821,
"s": 13784,
"text": "<%@ include file = \"relative url\" >\n"
},
{
"code": null,
"e": 13873,
"s": 13821,
"text": "The taglib directive follows the following syntax −"
},
{
"code": null,
"e": 13920,
"s": 13873,
"text": "<%@ taglib uri = \"uri\" prefix = \"prefixOfTag\">"
},
{
"code": null,
"e": 13989,
"s": 13920,
"text": "uri attribute value resolves to a location the container understands"
},
{
"code": null,
"e": 14066,
"s": 13989,
"text": "prefix attribute informs a container what bits of markup are custom actions."
},
{
"code": null,
"e": 14118,
"s": 14066,
"text": "The taglib directive follows the following syntax −"
},
{
"code": null,
"e": 14167,
"s": 14118,
"text": "<%@ taglib uri = \"uri\" prefix = \"prefixOfTag\" >\n"
},
{
"code": null,
"e": 14427,
"s": 14167,
"text": "Id attribute − The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext"
},
{
"code": null,
"e": 14687,
"s": 14427,
"text": "Id attribute − The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext"
},
{
"code": null,
"e": 15017,
"s": 14687,
"text": "Scope attribute − This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application."
},
{
"code": null,
"e": 15347,
"s": 15017,
"text": "Scope attribute − This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application."
},
{
"code": null,
"e": 15441,
"s": 15347,
"text": "This action lets you insert files into the page being generated. The syntax looks like this −"
},
{
"code": null,
"e": 15495,
"s": 15441,
"text": "<jsp:include page = \"relative URL\" flush = \"true\" />\n"
},
{
"code": null,
"e": 15554,
"s": 15495,
"text": "Where page is the relative URL of the page to be included."
},
{
"code": null,
"e": 15676,
"s": 15554,
"text": "Flush is the boolean attribute the determines whether the included resource has its buffer flushed before it is included."
},
{
"code": null,
"e": 15851,
"s": 15676,
"text": "Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, include action inserts the file at the time the page is requested."
},
{
"code": null,
"e": 16042,
"s": 15851,
"text": "The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object."
},
{
"code": null,
"e": 16090,
"s": 16042,
"text": "The simplest way to load a bean is as follows −"
},
{
"code": null,
"e": 16143,
"s": 16090,
"text": "<jsp:useBean id = \"name\" class = \"package.class\" />\n"
},
{
"code": null,
"e": 16260,
"s": 16143,
"text": "The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action."
},
{
"code": null,
"e": 16402,
"s": 16260,
"text": "The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output."
},
{
"code": null,
"e": 16569,
"s": 16402,
"text": "The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet."
},
{
"code": null,
"e": 16618,
"s": 16569,
"text": "The simple syntax of this action is as follows −"
},
{
"code": null,
"e": 16657,
"s": 16618,
"text": "<jsp:forward page = \"Relative URL\" />\n"
},
{
"code": null,
"e": 16812,
"s": 16657,
"text": "The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the <object> or <embed> tags as needed."
},
{
"code": null,
"e": 16969,
"s": 16812,
"text": "If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean."
},
{
"code": null,
"e": 17121,
"s": 16969,
"text": "The scope attribute identifies the lifecycle of the Action element. It has four possible values: (a) page, (b)request, (c)session, and (d) application."
},
{
"code": null,
"e": 17361,
"s": 17121,
"text": "JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables."
},
{
"code": null,
"e": 17444,
"s": 17361,
"text": "request, response, out, session, application, config, pageContext, page, Exception"
},
{
"code": null,
"e": 17627,
"s": 17444,
"text": "The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request."
},
{
"code": null,
"e": 17742,
"s": 17627,
"text": "The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc."
},
{
"code": null,
"e": 17945,
"s": 17742,
"text": "Using getHeaderNames() method of HttpServletRequest to read the HTTP header information. This method returns an Enumeration that contains the header information associated with the current HTTP request."
},
{
"code": null,
"e": 18145,
"s": 17945,
"text": "The response object is an instance of a javax.servlet.http.HttpServletRequest object. Just as the server creates the request object, it also creates an object to represent the response to the client."
},
{
"code": null,
"e": 18333,
"s": 18145,
"text": "The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc."
},
{
"code": null,
"e": 18455,
"s": 18333,
"text": "The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response."
},
{
"code": null,
"e": 18686,
"s": 18455,
"text": "The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions."
},
{
"code": null,
"e": 18814,
"s": 18686,
"text": "The session object is an instance of javax.servlet.http.HttpSession and is used to track client session between client requests"
},
{
"code": null,
"e": 18983,
"s": 18814,
"text": "The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object."
},
{
"code": null,
"e": 19194,
"s": 18983,
"text": "This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method."
},
{
"code": null,
"e": 19346,
"s": 19194,
"text": "The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet."
},
{
"code": null,
"e": 19487,
"s": 19346,
"text": "This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc."
},
{
"code": null,
"e": 19633,
"s": 19487,
"text": "The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page."
},
{
"code": null,
"e": 19819,
"s": 19633,
"text": "This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object."
},
{
"code": null,
"e": 19984,
"s": 19819,
"text": "The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope."
},
{
"code": null,
"e": 20119,
"s": 19984,
"text": "This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page."
},
{
"code": null,
"e": 20183,
"s": 20119,
"text": "The page object is really a direct synonym for the this object."
},
{
"code": null,
"e": 20354,
"s": 20183,
"text": "The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition."
},
{
"code": null,
"e": 20505,
"s": 20354,
"text": "The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? Character."
},
{
"code": null,
"e": 20811,
"s": 20505,
"text": "The POST method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing."
},
{
"code": null,
"e": 20912,
"s": 20811,
"text": "JSP handles form data parsing automatically using the following methods depending on the situation −"
},
{
"code": null,
"e": 21006,
"s": 20912,
"text": "getParameter() − You call request.getParameter() method to get the value of a form parameter."
},
{
"code": null,
"e": 21100,
"s": 21006,
"text": "getParameter() − You call request.getParameter() method to get the value of a form parameter."
},
{
"code": null,
"e": 21231,
"s": 21100,
"text": "getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox."
},
{
"code": null,
"e": 21362,
"s": 21231,
"text": "getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox."
},
{
"code": null,
"e": 21471,
"s": 21362,
"text": "getParameterNames() − Call this method if you want a complete list of all parameters in the current request."
},
{
"code": null,
"e": 21580,
"s": 21471,
"text": "getParameterNames() − Call this method if you want a complete list of all parameters in the current request."
},
{
"code": null,
"e": 21667,
"s": 21580,
"text": "getInputStream() − Call this method to read binary data stream coming from the client."
},
{
"code": null,
"e": 21754,
"s": 21667,
"text": "getInputStream() − Call this method to read binary data stream coming from the client."
},
{
"code": null,
"e": 21848,
"s": 21754,
"text": "JSP Filters are Java classes that can be used in JSP Programming for the following purposes −"
},
{
"code": null,
"e": 21927,
"s": 21848,
"text": "To intercept requests from a client before they access a resource at back end."
},
{
"code": null,
"e": 22006,
"s": 21927,
"text": "To intercept requests from a client before they access a resource at back end."
},
{
"code": null,
"e": 22083,
"s": 22006,
"text": "To manipulate responses from server before they are sent back to the client."
},
{
"code": null,
"e": 22160,
"s": 22083,
"text": "To manipulate responses from server before they are sent back to the client."
},
{
"code": null,
"e": 22330,
"s": 22160,
"text": "Filters are defined in the deployment descriptor file web.xml and then mapped to either servlet or JSP names or URL patterns in your application's deployment descriptor."
},
{
"code": null,
"e": 22562,
"s": 22330,
"text": "When the JSP container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor."
},
{
"code": null,
"e": 22675,
"s": 22562,
"text": "Cookies are text files stored on the client computer and they are kept for various information tracking purpose."
},
{
"code": null,
"e": 23020,
"s": 22675,
"text": "Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser).If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server."
},
{
"code": null,
"e": 23068,
"s": 23020,
"text": "Setting cookies with JSP involves three steps −"
},
{
"code": null,
"e": 23193,
"s": 23068,
"text": "Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings."
},
{
"code": null,
"e": 23318,
"s": 23193,
"text": "Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings."
},
{
"code": null,
"e": 23423,
"s": 23318,
"text": "Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid."
},
{
"code": null,
"e": 23528,
"s": 23423,
"text": "Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid."
},
{
"code": null,
"e": 23650,
"s": 23528,
"text": "Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header"
},
{
"code": null,
"e": 23772,
"s": 23650,
"text": "Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header"
},
{
"code": null,
"e": 24028,
"s": 23772,
"text": "To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value."
},
{
"code": null,
"e": 24151,
"s": 24028,
"text": "To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps −"
},
{
"code": null,
"e": 24215,
"s": 24151,
"text": "Read an already existing cookie and store it in Cookie object."
},
{
"code": null,
"e": 24279,
"s": 24215,
"text": "Read an already existing cookie and store it in Cookie object."
},
{
"code": null,
"e": 24357,
"s": 24279,
"text": "Set cookie age as zero using setMaxAge() method to delete an existing cookie."
},
{
"code": null,
"e": 24435,
"s": 24357,
"text": "Set cookie age as zero using setMaxAge() method to delete an existing cookie."
},
{
"code": null,
"e": 24478,
"s": 24435,
"text": "Add this cookie back into response header."
},
{
"code": null,
"e": 24521,
"s": 24478,
"text": "Add this cookie back into response header."
},
{
"code": null,
"e": 24572,
"s": 24521,
"text": "Session management can be achieved by the use of −"
},
{
"code": null,
"e": 24750,
"s": 24572,
"text": "Cookies − A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie."
},
{
"code": null,
"e": 24928,
"s": 24750,
"text": "Cookies − A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie."
},
{
"code": null,
"e": 25040,
"s": 24928,
"text": "Hidden Form Fields − A web server can send a hidden HTML form field along with a unique session ID as follows −"
},
{
"code": null,
"e": 25152,
"s": 25040,
"text": "Hidden Form Fields − A web server can send a hidden HTML form field along with a unique session ID as follows −"
},
{
"code": null,
"e": 25211,
"s": 25152,
"text": "<input type = \"hidden\" name = \"sessionid\" value = \"12345\">"
},
{
"code": null,
"e": 25334,
"s": 25211,
"text": "This implies that when the form is submitted, the specified name and value will be getting included in GET or POST method."
},
{
"code": null,
"e": 25512,
"s": 25334,
"text": "URL Rewriting − In URL rewriting some extra information is added on the end of each URL that identifies the session. This URL rewriting can be useful where a cookie is disabled."
},
{
"code": null,
"e": 25690,
"s": 25512,
"text": "URL Rewriting − In URL rewriting some extra information is added on the end of each URL that identifies the session. This URL rewriting can be useful where a cookie is disabled."
},
{
"code": null,
"e": 25906,
"s": 25690,
"text": "The session Object − JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user."
},
{
"code": null,
"e": 26122,
"s": 25906,
"text": "The session Object − JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user."
},
{
"code": null,
"e": 26195,
"s": 26122,
"text": "When you are done with a user's session data, you have several options −"
},
{
"code": null,
"e": 26347,
"s": 26195,
"text": "Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with the a particular key."
},
{
"code": null,
"e": 26499,
"s": 26347,
"text": "Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with the a particular key."
},
{
"code": null,
"e": 26601,
"s": 26499,
"text": "Delete the whole session − You can call public void invalidate() method to discard an entire session."
},
{
"code": null,
"e": 26703,
"s": 26601,
"text": "Delete the whole session − You can call public void invalidate() method to discard an entire session."
},
{
"code": null,
"e": 26845,
"s": 26703,
"text": "Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually."
},
{
"code": null,
"e": 26987,
"s": 26845,
"text": "Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually."
},
{
"code": null,
"e": 27161,
"s": 26987,
"text": "Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users."
},
{
"code": null,
"e": 27335,
"s": 27161,
"text": "Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users."
},
{
"code": null,
"e": 27487,
"s": 27335,
"text": "web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows."
},
{
"code": null,
"e": 27639,
"s": 27487,
"text": "web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows."
},
{
"code": null,
"e": 27847,
"s": 27639,
"text": "To upload a single file you should use a single <input .../> tag with attribute type = \"file\".To allow multiple files uploading, include more than one input tags with different values for the name attribute."
},
{
"code": null,
"e": 28005,
"s": 27847,
"text": "You can hard code this in your program or this directory name could also be added using an external configuration such as a context-param element in web.xml."
},
{
"code": null,
"e": 28198,
"s": 28005,
"text": "Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization."
},
{
"code": null,
"e": 28475,
"s": 28198,
"text": "The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file."
},
{
"code": null,
"e": 28604,
"s": 28475,
"text": "sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page."
},
{
"code": null,
"e": 28694,
"s": 28604,
"text": "A hit counter tells you about the number of visits on a particular page of your web site."
},
{
"code": null,
"e": 28827,
"s": 28694,
"text": "To implement a hit counter you can make use of Application Implicit object and associated methods getAttribute() and setAttribute()."
},
{
"code": null,
"e": 29038,
"s": 28827,
"text": "This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method."
},
{
"code": null,
"e": 29071,
"s": 29038,
"text": "You can follow the below steps −"
},
{
"code": null,
"e": 29164,
"s": 29071,
"text": "Define a database table with a single count, let us say hitcount. Assign a zero value to it."
},
{
"code": null,
"e": 29257,
"s": 29164,
"text": "Define a database table with a single count, let us say hitcount. Assign a zero value to it."
},
{
"code": null,
"e": 29318,
"s": 29257,
"text": "With every hit, read the table to get the value of hitcount."
},
{
"code": null,
"e": 29379,
"s": 29318,
"text": "With every hit, read the table to get the value of hitcount."
},
{
"code": null,
"e": 29454,
"s": 29379,
"text": "Increase the value of hitcount by one and update the table with new value."
},
{
"code": null,
"e": 29529,
"s": 29454,
"text": "Increase the value of hitcount by one and update the table with new value."
},
{
"code": null,
"e": 29585,
"s": 29529,
"text": "Display new value of hitcount as total page hit counts."
},
{
"code": null,
"e": 29641,
"s": 29585,
"text": "Display new value of hitcount as total page hit counts."
},
{
"code": null,
"e": 29727,
"s": 29641,
"text": "If you want to count hits for all the pages, implement above logic for all the pages."
},
{
"code": null,
"e": 29813,
"s": 29727,
"text": "If you want to count hits for all the pages, implement above logic for all the pages."
},
{
"code": null,
"e": 30047,
"s": 29813,
"text": "Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your Webpage regularly using refresh or reload button with your browser."
},
{
"code": null,
"e": 30203,
"s": 30047,
"text": "JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval."
},
{
"code": null,
"e": 30339,
"s": 30203,
"text": "The simplest way of refreshing a Webpage is using method setIntHeader() of response object. Following is the signature of this method −"
},
{
"code": null,
"e": 30396,
"s": 30339,
"text": "public void setIntHeader(String header, int headerValue)"
},
{
"code": null,
"e": 30521,
"s": 30396,
"text": "This method sends back header \"Refresh\" to the browser along with an integer value which indicates time interval in seconds."
},
{
"code": null,
"e": 30676,
"s": 30521,
"text": "The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications."
},
{
"code": null,
"e": 30918,
"s": 30676,
"text": "JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags."
},
{
"code": null,
"e": 30943,
"s": 30918,
"text": "Types of JSTL tags are −"
},
{
"code": null,
"e": 30953,
"s": 30943,
"text": "Core Tags"
},
{
"code": null,
"e": 30963,
"s": 30953,
"text": "Core Tags"
},
{
"code": null,
"e": 30979,
"s": 30963,
"text": "Formatting tags"
},
{
"code": null,
"e": 30995,
"s": 30979,
"text": "Formatting tags"
},
{
"code": null,
"e": 31004,
"s": 30995,
"text": "SQL tags"
},
{
"code": null,
"e": 31013,
"s": 31004,
"text": "SQL tags"
},
{
"code": null,
"e": 31022,
"s": 31013,
"text": "XML tags"
},
{
"code": null,
"e": 31031,
"s": 31022,
"text": "XML tags"
},
{
"code": null,
"e": 31046,
"s": 31031,
"text": "JSTL Functions"
},
{
"code": null,
"e": 31061,
"s": 31046,
"text": "JSTL Functions"
},
{
"code": null,
"e": 31261,
"s": 31061,
"text": "The <c:set > tag is JSTL-friendly version of the setProperty action. The tag is helpful because it evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map object."
},
{
"code": null,
"e": 31405,
"s": 31261,
"text": "The <c:remove > tag removes a variable from either a specified scope or the first scope where the variable is found (if no scope is specified)."
},
{
"code": null,
"e": 31579,
"s": 31405,
"text": "The <c:catch> tag catches any Throwable that occurs in its body and optionally exposes it. Simply it is used for error handling and to deal more gracefully with the problem."
},
{
"code": null,
"e": 31690,
"s": 31579,
"text": "The <c:if> tag evaluates an expression and displays its body content only if the expression evaluates to true."
},
{
"code": null,
"e": 32017,
"s": 31690,
"text": "The <c:choose> works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <c:choose> tag has <c:when> tags. A a switch statement has default clause to specify a default action and similar way <c:choose> has <otherwise> as default clause."
},
{
"code": null,
"e": 32148,
"s": 32017,
"text": "The <c:forEach >, <c:forTokens> tags exist as a good alternative to embedding a Java for, while, or do-while loop via a scriptlet."
},
{
"code": null,
"e": 32276,
"s": 32148,
"text": "The <c:param> tag allows proper URL request parameter to be specified with URL and it does any necessary URL encoding required."
},
{
"code": null,
"e": 32452,
"s": 32276,
"text": "The <c:redirect > tag redirects the browser to an alternate URL by providing automatically URL rewriting, it supports context-relative URLs, and it supports the <c:param> tag."
},
{
"code": null,
"e": 32589,
"s": 32452,
"text": "The <c:url> tag formats a URL into a string and stores it into a variable. This tag automatically performs URL rewriting when necessary."
},
{
"code": null,
"e": 32784,
"s": 32589,
"text": "The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites. Following is the syntax to include Formatting library in your JSP −"
},
{
"code": null,
"e": 32854,
"s": 32784,
"text": "<%@ taglib prefix = \"fmt\" uri = \"http://java.sun.com/jsp/jstl/fmt\" %>"
},
{
"code": null,
"e": 32992,
"s": 32854,
"text": "The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server."
},
{
"code": null,
"e": 33058,
"s": 32992,
"text": "Following is the syntax to include JSTL SQL library in your JSP −"
},
{
"code": null,
"e": 33129,
"s": 33058,
"text": "<%@ taglib prefix = \"sql\" uri = \"http://java.sun.com/jsp/jstl/sql\" %>\n"
},
{
"code": null,
"e": 33282,
"s": 33129,
"text": "The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. Following is the syntax to include JSTL XML library in your JSP."
},
{
"code": null,
"e": 33350,
"s": 33282,
"text": "<%@ taglib prefix = \"x\" uri = \"http://java.sun.com/jsp/jstl/xml\" %>"
},
{
"code": null,
"e": 33632,
"s": 33350,
"text": "A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed."
},
{
"code": null,
"e": 33855,
"s": 33632,
"text": "JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. A simple syntax for JSP EL is −"
},
{
"code": null,
"e": 33866,
"s": 33855,
"text": " \n${expr}\n"
},
{
"code": null,
"e": 33909,
"s": 33866,
"text": "Here expr specifies the expression itself."
},
{
"code": null,
"e": 33979,
"s": 33909,
"text": "The JSP expression language supports the following implicit objects −"
},
{
"code": null,
"e": 34024,
"s": 33979,
"text": "pageScope − Scoped variables from page scope"
},
{
"code": null,
"e": 34069,
"s": 34024,
"text": "pageScope − Scoped variables from page scope"
},
{
"code": null,
"e": 34120,
"s": 34069,
"text": "requestScope − Scoped variables from request scope"
},
{
"code": null,
"e": 34171,
"s": 34120,
"text": "requestScope − Scoped variables from request scope"
},
{
"code": null,
"e": 34222,
"s": 34171,
"text": "sessionScope − Scoped variables from session scope"
},
{
"code": null,
"e": 34273,
"s": 34222,
"text": "sessionScope − Scoped variables from session scope"
},
{
"code": null,
"e": 34332,
"s": 34273,
"text": "applicationScope − Scoped variables from application scope"
},
{
"code": null,
"e": 34391,
"s": 34332,
"text": "applicationScope − Scoped variables from application scope"
},
{
"code": null,
"e": 34429,
"s": 34391,
"text": "param − Request parameters as strings"
},
{
"code": null,
"e": 34467,
"s": 34429,
"text": "param − Request parameters as strings"
},
{
"code": null,
"e": 34526,
"s": 34467,
"text": "paramValues − Request parameters as collections of strings"
},
{
"code": null,
"e": 34585,
"s": 34526,
"text": "paramValues − Request parameters as collections of strings"
},
{
"code": null,
"e": 34625,
"s": 34585,
"text": "headerHTTP − request headers as strings"
},
{
"code": null,
"e": 34665,
"s": 34625,
"text": "headerHTTP − request headers as strings"
},
{
"code": null,
"e": 34727,
"s": 34665,
"text": "headerValues − HTTP request headers as collections of strings"
},
{
"code": null,
"e": 34789,
"s": 34727,
"text": "headerValues − HTTP request headers as collections of strings"
},
{
"code": null,
"e": 34835,
"s": 34789,
"text": "initParam − Context-initialization parameters"
},
{
"code": null,
"e": 34881,
"s": 34835,
"text": "initParam − Context-initialization parameters"
},
{
"code": null,
"e": 34904,
"s": 34881,
"text": "cookie − Cookie values"
},
{
"code": null,
"e": 34927,
"s": 34904,
"text": "cookie − Cookie values"
},
{
"code": null,
"e": 34989,
"s": 34927,
"text": "pageContext − The JSP PageContext object for the current page"
},
{
"code": null,
"e": 35051,
"s": 34989,
"text": "pageContext − The JSP PageContext object for the current page"
},
{
"code": null,
"e": 35118,
"s": 35051,
"text": "We can disable using isELIgnored attribute of the page directive −"
},
{
"code": null,
"e": 35158,
"s": 35118,
"text": "<%@ page isELIgnored = \"true|false\" %>\n"
},
{
"code": null,
"e": 35314,
"s": 35158,
"text": "If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container."
},
{
"code": null,
"e": 35618,
"s": 35314,
"text": "Checked exceptions − Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation."
},
{
"code": null,
"e": 35922,
"s": 35618,
"text": "Checked exceptions − Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation."
},
{
"code": null,
"e": 36141,
"s": 35922,
"text": "Runtime exceptions − A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation."
},
{
"code": null,
"e": 36360,
"s": 36141,
"text": "Runtime exceptions − A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation."
},
{
"code": null,
"e": 36681,
"s": 36360,
"text": "Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation."
},
{
"code": null,
"e": 37002,
"s": 36681,
"text": "Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation."
},
{
"code": null,
"e": 37149,
"s": 37002,
"text": "We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page."
},
{
"code": null,
"e": 37194,
"s": 37149,
"text": "Example: <%@ page errorPage = \"error.jsp\" %>"
},
{
"code": null,
"e": 37445,
"s": 37194,
"text": "It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage=\"true\" %>"
},
{
"code": null,
"e": 37588,
"s": 37445,
"text": "Internationalization means enabling a web site to provide different versions of content translated into the visitor's language or nationality."
},
{
"code": null,
"e": 37743,
"s": 37588,
"text": "Localization means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site."
},
{
"code": null,
"e": 37965,
"s": 37743,
"text": "This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example \"en_US\" represents english locale for US."
},
{
"code": null,
"e": 38032,
"s": 37965,
"text": "<%-- comment --%> is JSP comment and is ignored by the JSP engine."
},
{
"code": null,
"e": 38099,
"s": 38032,
"text": "<!-- comment --> is an HTML comment and is ignored by the browser."
},
{
"code": null,
"e": 38226,
"s": 38099,
"text": "YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries."
},
{
"code": null,
"e": 38606,
"s": 38226,
"text": "Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request."
},
{
"code": null,
"e": 38866,
"s": 38606,
"text": "Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression."
},
{
"code": null,
"e": 38970,
"s": 38866,
"text": "Use the following ways to pass control of a request from one servlet to another or one jsp to another −"
},
{
"code": null,
"e": 39038,
"s": 38970,
"text": "The RequestDispatcher object ‘s forward method to pass the control."
},
{
"code": null,
"e": 39106,
"s": 39038,
"text": "The RequestDispatcher object ‘s forward method to pass the control."
},
{
"code": null,
"e": 39146,
"s": 39106,
"text": "Using the response.sendRedirect method."
},
{
"code": null,
"e": 39186,
"s": 39146,
"text": "Using the response.sendRedirect method."
},
{
"code": null,
"e": 39325,
"s": 39186,
"text": "No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients."
},
{
"code": null,
"e": 39486,
"s": 39325,
"text": "A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not."
},
{
"code": null,
"e": 39514,
"s": 39486,
"text": "<%@ page session = \"false\">"
},
{
"code": null,
"e": 39538,
"s": 39514,
"text": "Using <%jsp:param> tag."
},
{
"code": null,
"e": 39612,
"s": 39538,
"text": "We can override jspinit() and jspDestroy() methods but not _jspService()."
},
{
"code": null,
"e": 39854,
"s": 39612,
"text": "_jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page."
},
{
"code": null,
"e": 40133,
"s": 39854,
"text": "It causes compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error."
},
{
"code": null,
"e": 40364,
"s": 40133,
"text": "Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows −"
},
{
"code": null,
"e": 40490,
"s": 40364,
"text": "<jsp-property-group>\n <url-pattern>*.jsp</url-pattern>\n <scripting-invalid>true</scripting-invalid>\n</jsp-property-group>"
},
{
"code": null,
"e": 40593,
"s": 40490,
"text": "If we want to make our data available to the entire application then we have to use application scope."
},
{
"code": null,
"e": 40650,
"s": 40593,
"text": "In JSP, we can perform inclusion in the following ways −"
},
{
"code": null,
"e": 40687,
"s": 40650,
"text": "By include directive − For example −"
},
{
"code": null,
"e": 40724,
"s": 40687,
"text": "By include directive − For example −"
},
{
"code": null,
"e": 40760,
"s": 40724,
"text": "<%@ include file = ”header.jsp” %>\n"
},
{
"code": null,
"e": 40794,
"s": 40760,
"text": "By include action − For example −"
},
{
"code": null,
"e": 40828,
"s": 40794,
"text": "By include action − For example −"
},
{
"code": null,
"e": 40864,
"s": 40828,
"text": "<%@ include file = ”header.jsp” %>\n"
},
{
"code": null,
"e": 40915,
"s": 40864,
"text": "By using pageContext implicit object For example −"
},
{
"code": null,
"e": 40966,
"s": 40915,
"text": "By using pageContext implicit object For example −"
},
{
"code": null,
"e": 41009,
"s": 40966,
"text": "<% pageContext.include(“/header.jsp”); %>\n"
},
{
"code": null,
"e": 41059,
"s": 41009,
"text": "By using RequestDispatcher object − For example −"
},
{
"code": null,
"e": 41109,
"s": 41059,
"text": "By using RequestDispatcher object − For example −"
},
{
"code": null,
"e": 41216,
"s": 41109,
"text": "<%\n RequestDispatcher rd = request.getRequestDispatcher(“/header.jsp”);\n Rd.include(request,response);\n%>\n"
},
{
"code": null,
"e": 41533,
"s": 41216,
"text": "JSP engines will always instantiate a new tag handler instance every time a tag is encountered in a JSP page. A pool of tag instances are maintained and reusing them where possible. When a tag is encountered, the JSP engine will try to find a Tag instance that is not being used and use the same and then release it."
},
{
"code": null,
"e": 41655,
"s": 41533,
"text": "JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them −"
},
{
"code": null,
"e": 41764,
"s": 41655,
"text": "Taglibs are for generating presentation elements while JavaBeans are good for storing information and state."
},
{
"code": null,
"e": 41873,
"s": 41764,
"text": "Taglibs are for generating presentation elements while JavaBeans are good for storing information and state."
},
{
"code": null,
"e": 41948,
"s": 41873,
"text": "Use custom tags to implement actions and JavaBeans to present information."
},
{
"code": null,
"e": 42023,
"s": 41948,
"text": "Use custom tags to implement actions and JavaBeans to present information."
},
{
"code": null,
"e": 42310,
"s": 42023,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
},
{
"code": null,
"e": 42640,
"s": 42310,
"text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)"
},
{
"code": null,
"e": 42675,
"s": 42640,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 42690,
"s": 42675,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 42725,
"s": 42690,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 42740,
"s": 42725,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 42775,
"s": 42740,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 42789,
"s": 42775,
"text": " Karthikeya T"
},
{
"code": null,
"e": 42824,
"s": 42789,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 42840,
"s": 42824,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 42873,
"s": 42840,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 42889,
"s": 42873,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 42923,
"s": 42889,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 42931,
"s": 42923,
"text": " Uplatz"
},
{
"code": null,
"e": 42938,
"s": 42931,
"text": " Print"
},
{
"code": null,
"e": 42949,
"s": 42938,
"text": " Add Notes"
}
] |
AlgorithmParameterGenerator init() method in Java with Examples - GeeksforGeeks
|
01 Jul, 2021
The init() method of java.security.AlgorithmParameterGenerator class is used to initialize AlgorithmParameterGenerator for particular size to use further. Syntax:
public final void init(int size)
Parameters: This method takes size of int type as a parameter.Return Value: This method returns nothing.Below are the examples to illustrate the init(int size) method:Example 1:
Java
// Java program to demonstrate// init() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of // AlgorithmParameterGenerator // and getting instance // using getInstance() method AlgorithmParameterGenerator sr = AlgorithmParameterGenerator .getInstance("DSA"); // initializing the AlgorithmParameterGenerator // with 1024 using initialize() method sr.init(1024); // generating the Parameters // using generateParameters() method AlgorithmParameters param = sr.generateParameters(); // printing the keypair System.out.println("AlgorithmParameters : " + param); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (ProviderException e) { System.out.println("Exception thrown : " + e); } }}
AlgorithmParameters : p: a695be97 15fe7cdf 3f9b4e5f a2b640cf ecec7852 2f3208dc 941187c5 4be1a391 cfe13145 62310769 17b051e2 4fa62871 4aefada2 e0dbb0fe b0987482 9cb9a290 09e340dd 61a9bc49 34175131 afc3d452 d8d6a439 de1ed044 3dfeeda9 32741d06 17d490b7 23a31141 0a4c09d6 7f69d68e 59f7b912 81f20d7f 9f6ede2c 504e267f q: a85d0845 5d188578 b39074d9 8797be08 9620d4f9 g: 9abd9824 d319bf88 381f4f88 4f83282c ae3555e6 a91d2a94 d0b9c18e 3d82b1a6 412acd42 a7a2e3b7 f524ffaf 8843fe1c d6845c3c ec240815 33d26dd5 af457b65 aa1f670d 6ade4789 2c504a21 67e781c9 c1797a7a 1e39eeae 8da5433b bdbffbdd a64efcfc 209f25f4 c162d88a d3f9b4f9 f0a247b8 a6b97c1c aec2ac91 b8bb279b
The init() method of java.security.AlgorithmParameterGenerator class is used to initialize AlgorithmParameterGenerator for particular size with SecureRandom object to use further . Syntax:
public final void init(int size,
SecureRandom random)
Parameters: This method takes the following arguments as a parameters:
size which is the size to be specified for initialization
random which is the object of SecureRandom type to be specified to this AlgorithmParameterGenerator object
Return Value: This method returns the new AlgorithmParameterGenerator object.Below are the examples to illustrate the init() method:Example 1:
Java
// Java program to demonstrate// init() method import java.security.*;import java.util.*; public class GFG { public static void main(String[] argv) { try { // creating the object of // AlgorithmParameterGenerator // and getting instance // using getInstance() method AlgorithmParameterGenerator sr = AlgorithmParameterGenerator .getInstance("DSA"); // creating the object of SecureRandom SecureRandom se = SecureRandom.getInstance("SHA1PRNG"); // initializing the AlgorithmParameterGenerator // with 1024 and SecureRandom object // using init() method sr.init(1024, se); // generating the Parameters // using generateParameters() method AlgorithmParameters param = sr.generateParameters(); // printing the keypair System.out.println("AlgorithmParameters : " + param); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (ProviderException e) { System.out.println("Exception thrown : " + e); } }}
AlgorithmParameters : p: b1da365d af3829d0 11eb4e13 3bd01aef 3c25e6e3 1c6f993b 5633a4bf 81ca9680 587717e4 08c3a9e7 ead7b7a1 ff02561f efd2efa0 601c3f4c 90080ad0 ec29f3a9 3e167027 c7a2b3f8 a04c79a8 837f9be9 7731f2d2 499eb86c 37612953 32b5ad71 cbbf5bf4 6407f18a fd716be0 706e1717 e7357af9 1c1bee1e fa9c5cf7 f3506a75 q: bf8d23a2 5d590c5c fb6b6df2 bb104a06 c1492a3b g: 3510f6d8 a55b2c00 645e1dca 66448d2a 7d8e54d3 5caa67b9 00de36d2 518c0a40 985433c3 be45c8ed 2dc04c61 173c663f 030290fe 0158ef11 3642e12f f243ac6c 2bbe2a83 80a1f1ae 4a750d3e eab3bc27 bb56a7d1 12c6676a 6142a380 8a5ca7d9 f07375e6 56c33723 5de931e7 0339f95a bd9cbd18 eebed3bc d7f6365b 235f7d65
Reference:
https://docs.oracle.com/javase/9/docs/api/java/security/AlgorithmParameterGenerator.html#init-int-
https://docs.oracle.com/javase/9/docs/api/java/security/AlgorithmParameterGenerator.html#init-int-java.security.SecureRandom-
akshaysingh98088
Java-AlgorithmParameterGenerator
Java-Functions
Java-security package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 23722,
"s": 23557,
"text": "The init() method of java.security.AlgorithmParameterGenerator class is used to initialize AlgorithmParameterGenerator for particular size to use further. Syntax: "
},
{
"code": null,
"e": 23755,
"s": 23722,
"text": "public final void init(int size)"
},
{
"code": null,
"e": 23935,
"s": 23755,
"text": "Parameters: This method takes size of int type as a parameter.Return Value: This method returns nothing.Below are the examples to illustrate the init(int size) method:Example 1: "
},
{
"code": null,
"e": 23940,
"s": 23935,
"text": "Java"
},
{
"code": "// Java program to demonstrate// init() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of // AlgorithmParameterGenerator // and getting instance // using getInstance() method AlgorithmParameterGenerator sr = AlgorithmParameterGenerator .getInstance(\"DSA\"); // initializing the AlgorithmParameterGenerator // with 1024 using initialize() method sr.init(1024); // generating the Parameters // using generateParameters() method AlgorithmParameters param = sr.generateParameters(); // printing the keypair System.out.println(\"AlgorithmParameters : \" + param); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (ProviderException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 25077,
"s": 23940,
"text": null
},
{
"code": null,
"e": 25730,
"s": 25077,
"text": "AlgorithmParameters : p: a695be97 15fe7cdf 3f9b4e5f a2b640cf ecec7852 2f3208dc 941187c5 4be1a391 cfe13145 62310769 17b051e2 4fa62871 4aefada2 e0dbb0fe b0987482 9cb9a290 09e340dd 61a9bc49 34175131 afc3d452 d8d6a439 de1ed044 3dfeeda9 32741d06 17d490b7 23a31141 0a4c09d6 7f69d68e 59f7b912 81f20d7f 9f6ede2c 504e267f q: a85d0845 5d188578 b39074d9 8797be08 9620d4f9 g: 9abd9824 d319bf88 381f4f88 4f83282c ae3555e6 a91d2a94 d0b9c18e 3d82b1a6 412acd42 a7a2e3b7 f524ffaf 8843fe1c d6845c3c ec240815 33d26dd5 af457b65 aa1f670d 6ade4789 2c504a21 67e781c9 c1797a7a 1e39eeae 8da5433b bdbffbdd a64efcfc 209f25f4 c162d88a d3f9b4f9 f0a247b8 a6b97c1c aec2ac91 b8bb279b "
},
{
"code": null,
"e": 25923,
"s": 25732,
"text": "The init() method of java.security.AlgorithmParameterGenerator class is used to initialize AlgorithmParameterGenerator for particular size with SecureRandom object to use further . Syntax: "
},
{
"code": null,
"e": 26000,
"s": 25923,
"text": "public final void init(int size,\n SecureRandom random)"
},
{
"code": null,
"e": 26073,
"s": 26000,
"text": "Parameters: This method takes the following arguments as a parameters: "
},
{
"code": null,
"e": 26131,
"s": 26073,
"text": "size which is the size to be specified for initialization"
},
{
"code": null,
"e": 26238,
"s": 26131,
"text": "random which is the object of SecureRandom type to be specified to this AlgorithmParameterGenerator object"
},
{
"code": null,
"e": 26382,
"s": 26238,
"text": "Return Value: This method returns the new AlgorithmParameterGenerator object.Below are the examples to illustrate the init() method:Example 1: "
},
{
"code": null,
"e": 26387,
"s": 26382,
"text": "Java"
},
{
"code": "// Java program to demonstrate// init() method import java.security.*;import java.util.*; public class GFG { public static void main(String[] argv) { try { // creating the object of // AlgorithmParameterGenerator // and getting instance // using getInstance() method AlgorithmParameterGenerator sr = AlgorithmParameterGenerator .getInstance(\"DSA\"); // creating the object of SecureRandom SecureRandom se = SecureRandom.getInstance(\"SHA1PRNG\"); // initializing the AlgorithmParameterGenerator // with 1024 and SecureRandom object // using init() method sr.init(1024, se); // generating the Parameters // using generateParameters() method AlgorithmParameters param = sr.generateParameters(); // printing the keypair System.out.println(\"AlgorithmParameters : \" + param); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (ProviderException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27692,
"s": 26387,
"text": null
},
{
"code": null,
"e": 28345,
"s": 27692,
"text": "AlgorithmParameters : p: b1da365d af3829d0 11eb4e13 3bd01aef 3c25e6e3 1c6f993b 5633a4bf 81ca9680 587717e4 08c3a9e7 ead7b7a1 ff02561f efd2efa0 601c3f4c 90080ad0 ec29f3a9 3e167027 c7a2b3f8 a04c79a8 837f9be9 7731f2d2 499eb86c 37612953 32b5ad71 cbbf5bf4 6407f18a fd716be0 706e1717 e7357af9 1c1bee1e fa9c5cf7 f3506a75 q: bf8d23a2 5d590c5c fb6b6df2 bb104a06 c1492a3b g: 3510f6d8 a55b2c00 645e1dca 66448d2a 7d8e54d3 5caa67b9 00de36d2 518c0a40 985433c3 be45c8ed 2dc04c61 173c663f 030290fe 0158ef11 3642e12f f243ac6c 2bbe2a83 80a1f1ae 4a750d3e eab3bc27 bb56a7d1 12c6676a 6142a380 8a5ca7d9 f07375e6 56c33723 5de931e7 0339f95a bd9cbd18 eebed3bc d7f6365b 235f7d65 "
},
{
"code": null,
"e": 28360,
"s": 28347,
"text": "Reference: "
},
{
"code": null,
"e": 28459,
"s": 28360,
"text": "https://docs.oracle.com/javase/9/docs/api/java/security/AlgorithmParameterGenerator.html#init-int-"
},
{
"code": null,
"e": 28585,
"s": 28459,
"text": "https://docs.oracle.com/javase/9/docs/api/java/security/AlgorithmParameterGenerator.html#init-int-java.security.SecureRandom-"
},
{
"code": null,
"e": 28604,
"s": 28587,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 28637,
"s": 28604,
"text": "Java-AlgorithmParameterGenerator"
},
{
"code": null,
"e": 28652,
"s": 28637,
"text": "Java-Functions"
},
{
"code": null,
"e": 28674,
"s": 28652,
"text": "Java-security package"
},
{
"code": null,
"e": 28679,
"s": 28674,
"text": "Java"
},
{
"code": null,
"e": 28684,
"s": 28679,
"text": "Java"
},
{
"code": null,
"e": 28782,
"s": 28684,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28791,
"s": 28782,
"text": "Comments"
},
{
"code": null,
"e": 28804,
"s": 28791,
"text": "Old Comments"
},
{
"code": null,
"e": 28834,
"s": 28804,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28849,
"s": 28834,
"text": "Stream In Java"
},
{
"code": null,
"e": 28870,
"s": 28849,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28916,
"s": 28870,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28935,
"s": 28916,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28952,
"s": 28935,
"text": "Generics in Java"
},
{
"code": null,
"e": 28995,
"s": 28952,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29011,
"s": 28995,
"text": "Strings in Java"
},
{
"code": null,
"e": 29067,
"s": 29011,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
This article gains insights into Catboost, a simple and lesser-known way to use embeddings with gradient boosted models. | Towards Data Science
|
When working with a large amount of data, it becomes necessary to compress the space with features into vectors. An example is text embeddings, which are an integral part of almost any NLP model creation process. Unfortunately, it is far from always possible to use neural networks to work with this type of data — the reason, for example, maybe a low fitting or inference rates.
I want to suggest an interesting way to use gradient boosting that few people know about.
One of Kaggle’s competitions recently ended, and a small dataset with text data was presented there. I decided to take this data for experiments since the competition showed that the dataset was labelled well, and I did not face any unpleasant surprises.
Columns:
id - unique ID for excerpt
url_legal - URL of source
license - license of source material
excerpt - text to predict reading ease of
target - reading ease
standard_error - measure of the spread of scores among multiple raters for each excerpt
As a target in the dataset, it is a numerical variable, and it is proposed to solve the regression problem. However, I decided to replace it with a classification problem. The main reason is that the library I will use does not support working with text and embeddings in regression problems. I hope that developers will eliminate this deficiency in the future. But in any case, the problems of regression and classification are closely related, and for analysis, it makes no difference which of the problems to solve.
Let’s calculate the number of bins by Sturge’s rule:
num_bins = int(np.floor(1 + np.log2(len(train))))train['target_q'], bin_edges = pd.qcut(train['target'], q=num_bins, labels=False, retbins=True, precision=0)
But, first, I clean up the data.
train['license'] = train['license'].fillna('nan')train['license'] = train['license'].astype('category').cat.codes
With the help of a small self-written function, I clean and lemmatize the text. The function can be complicated, but this is enough for my experiment.
def clean_text(text): table = text.maketrans( dict.fromkeys(string.punctuation)) words = word_tokenize( text.lower().strip().translate(table)) words = [word for word in words if word not in stopwords.words('english')] lemmed = [WordNetLemmatizer().lemmatize(word) for word in words] return " ".join(lemmed)
I saved the cleaned text as a new feature.
train['clean_excerpt'] = train['excerpt'].apply(clean_text)
In addition to text, I can select individual words in URLs and turn this data into a new text feature.
def getWordsFromURL(url): return re.compile(r'[\:/?=\-&.]+',re.UNICODE).split(url)train['url_legal'] = train['url_legal'].fillna("nan").apply(getWordsFromURL).apply( lambda x: " ".join(x))
I created several new features from the text — these are various pieces of statistical information. Again, there is a lot of room for creativity, but this data is enough for us. The primary purpose of these features is to be helpful for the baseline model.
def get_sentence_lengths(text): tokened = sent_tokenize(text) lengths = [] for idx,i in enumerate(tokened): splited = list(i.split(" ")) lengths.append(len(splited)) return (max(lengths), min(lengths), round(mean(lengths), 3))def create_features(df): df_f = pd.DataFrame(index=df.index) df_f['text_len'] = df['excerpt'].apply(len) df_f['text_clean_len' ]= df['clean_excerpt'].apply(len) df_f['text_len_div'] = df_f['text_clean_len' ] / df_f['text_len'] df_f['text_word_count'] = df['clean_excerpt'].apply( lambda x : len(x.split(' '))) df_f[['max_len_sent','min_len_sent','avg_len_sent']] = \ df_f.apply( lambda x: get_sentence_lengths(x['excerpt']), axis=1, result_type='expand') return df_ftrain = pd.concat( [train, create_features(train)], axis=1, copy=False, sort=False)basic_f_columns = [ 'text_len', 'text_clean_len', 'text_len_div', 'text_word_count', 'max_len_sent', 'min_len_sent', 'avg_len_sent']
When data is scarce, it is difficult to test hypotheses, and the results are usually unstable. Therefore, to be more confident in the results, I prefer to use OOF(Out-of-Fold) predictions in such cases.
I chose Catboost as the free library for the model. Catboost is a high-performance, open-source library for gradient boosting on decision trees. From release 0.19.1, it supports text features for classification on GPU out-of-the-box. The main advantage is that CatBoost can include categorical functions and text functions in your data without additional preprocessing.
In Unconventional Sentiment Analysis: BERT vs. Catboost, I expanded on how Catboost worked with text and compared it with BERT.
This library has a killer feature: it knows how to work with embeddings. Unfortunately, at the moment, there is not a word about this in the documentation, and very few people know about this Catboost advantage.
!pip install catboost
When working with Catboost, I recommend using Pool. It is a convenience wrapper combining features, labels and further metadata like categorical and text features.
To compare experiments, I created a baseline model that uses only numerical and categorical features.
I wrote a function to initialize and train the model. By the way, I didn’t select the optimal parameters.
def fit_model_classifier(train_pool, test_pool, **kwargs): model = CatBoostClassifier( task_type='GPU', iterations=5000, eval_metric='AUC', od_type='Iter', od_wait=500, l2_leaf_reg=10, bootstrap_type='Bernoulli', subsample=0.7, **kwargs ) return model.fit( train_pool, eval_set=test_pool, verbose=100, plot=False, use_best_model=True)
For OOF implementation, I wrote a small and straightforward function.
def get_oof_classifier( n_folds, x_train, y, embedding_features, cat_features, text_features, tpo, seeds, num_bins, emb=None, tolist=True): ntrain = x_train.shape[0] oof_train = np.zeros((len(seeds), ntrain, num_bins)) models = {} for iseed, seed in enumerate(seeds): kf = StratifiedKFold( n_splits=n_folds, shuffle=True, random_state=seed) for i, (tr_i, t_i) in enumerate(kf.split(x_train, y)): if emb and len(emb) > 0: x_tr = pd.concat( [x_train.iloc[tr_i, :], get_embeddings( x_train.iloc[tr_i, :], emb, tolist)], axis=1, copy=False, sort=False) x_te = pd.concat( [x_train.iloc[t_i, :], get_embeddings( x_train.iloc[t_i, :], emb, tolist)], axis=1, copy=False, sort=False) columns = [ x for x in x_tr if (x not in ['excerpt'])] if not embedding_features: for c in emb: columns.remove(c) else: x_tr = x_train.iloc[tr_i, :] x_te = x_train.iloc[t_i, :] columns = [ x for x in x_tr if (x not in ['excerpt'])] x_tr = x_tr[columns] x_te = x_te[columns] y_tr = y[tr_i] y_te = y[t_i] train_pool = Pool( data=x_tr, label=y_tr, cat_features=cat_features, embedding_features=embedding_features, text_features=text_features) valid_pool = Pool( data=x_te, label=y_te, cat_features=cat_features, embedding_features=embedding_features, text_features=text_features) model = fit_model_classifier( train_pool, valid_pool, random_seed=seed, text_processing=tpo ) oof_train[iseed, t_i, :] = \ model.predict_proba(valid_pool) models[(seed, i)] = model oof_train = oof_train.mean(axis=0) return oof_train, models
I’ll write about the get_embeddings function below, but it is not used to get the model’s baseline for now.
I trained the baseline model with the following parameters:
columns = ['license', 'url_legal'] + basic_f_columns oof_train_cb, models_cb = get_oof_classifier( n_folds=5, x_train=train[columns], y=train['target_q'].values, embedding_features=None, cat_features=['license'], text_features=['url_legal'], tpo=tpo, seeds=[0, 42, 888], num_bins=num_bins)
Quality of the trained model:
roc_auc_score(train['target_q'], oof_train_cb, multi_class="ovo")AUC: 0.684407
Now I have a benchmark for the model’s quality. Judging by the numbers, the model turned out weak, and I would not implement it in production.
You can translate multidimensional vectors into embedding, which is a relatively low-dimensional space. Thus, embeddings simplify machine learning for large inputs such as sparse vectors representing words. Ideally, embedding captures some of the input semantics by placing semantically similar inputs close to each other in the embedding space.
There are many ways to obtain such vectors, and I do not consider them in this article since this is not the purpose of the study. However, it is enough for me to get embeddings in any way; the main thing is that they save the necessary information. In most cases, I use the popular method at the moment — pre-trained transformers.
from sentence_transformers import SentenceTransformerSTRANSFORMERS = { 'sentence-transformers/paraphrase-mpnet-base-v2': ('mpnet', 768), 'sentence-transformers/bert-base-wikipedia-sections-mean-tokens': ('wikipedia', 768)}def get_encode(df, encoder, name): device = torch.device( "cuda:0" if torch.cuda.is_available() else "cpu") model = SentenceTransformer( encoder, cache_folder=f'./hf_{name}/' ) model.to(device) model.eval() return np.array(model.encode(df['excerpt']))def get_embeddings(df, emb=None, tolist=True): ret = pd.DataFrame(index=df.index) for e, s in STRANSFORMERS.items(): if emb and s[0] not in emb: continue ret[s[0]] = list(get_encode(df, e, s[0])) if tolist: ret = pd.concat( [ret, pd.DataFrame( ret[s[0]].tolist(), columns=[f'{s[0]}_{x}' for x in range(s[1])], index=ret.index)], axis=1, copy=False, sort=False) return ret
Now I have everything to start testing different versions of the models.
I have several options for fitting models:
text features;
embedding features;
embedding features like a list of separated numerical features.
I have consistently trained various combinations of these options, which allowed me to conclude how useful embeddings might be, or, perhaps, it is just an over-engineering.
As an example, I give a code that uses all three options:
columns = ['license', 'url_legal', 'clean_excerpt', 'excerpt'] oof_train_cb, models_cb = get_oof_classifier( n_folds=FOLDS, x_train=train[columns], y=train['target_q'].values, embedding_features=['mpnet', 'wikipedia'], cat_features=['license'], text_features=['clean_excerpt','url_legal'], tpo=tpo, seeds=[0, 42, 888], num_bins=num_bins, emb=['mpnet', 'wikipedia'], tolist=True)
For more information, I trained models on both GPU and CPU; and summarized the results in one table.
The first thing that shocked me was the extremely poor interaction of the text feature and embeddings. Unfortunately, I don’t have any logical explanation for this fact yet — here, a more detailed study of this issue on other datasets is required. In the meantime, note that the combined use of text and embedding for the same text can bring down the quality of the model.
update: I got comments from developers:
“Thank you for the report! This bug was fixed in the commit and will be in the next release”
And another revelation for me was that embeddings do not work when training modes on a CPU.
And now a good thing — if you have a GPU and could get embeddings, the best quality will be when you simultaneously use embedding both as a feature and as a list of separate numerical features.
In this article, I:
selected a small free dataset for tests;
created several statistical features for the text data to use them for making a baseline model;
tested various combinations of embeddings, texts, and simple features;
got some non-obvious insights.
I hope that this little-known information will be helpful to the community and benefit from your projects. Unfortunately, the functionality of Catboost for working with embeddings and texts is still raw. But, it is actively being improved, and I hope there will be a stable release soon, and developers will update the documentation. The complete code to reproduce the results from this article is available here.
|
[
{
"code": null,
"e": 552,
"s": 172,
"text": "When working with a large amount of data, it becomes necessary to compress the space with features into vectors. An example is text embeddings, which are an integral part of almost any NLP model creation process. Unfortunately, it is far from always possible to use neural networks to work with this type of data — the reason, for example, maybe a low fitting or inference rates."
},
{
"code": null,
"e": 642,
"s": 552,
"text": "I want to suggest an interesting way to use gradient boosting that few people know about."
},
{
"code": null,
"e": 897,
"s": 642,
"text": "One of Kaggle’s competitions recently ended, and a small dataset with text data was presented there. I decided to take this data for experiments since the competition showed that the dataset was labelled well, and I did not face any unpleasant surprises."
},
{
"code": null,
"e": 906,
"s": 897,
"text": "Columns:"
},
{
"code": null,
"e": 933,
"s": 906,
"text": "id - unique ID for excerpt"
},
{
"code": null,
"e": 959,
"s": 933,
"text": "url_legal - URL of source"
},
{
"code": null,
"e": 996,
"s": 959,
"text": "license - license of source material"
},
{
"code": null,
"e": 1038,
"s": 996,
"text": "excerpt - text to predict reading ease of"
},
{
"code": null,
"e": 1060,
"s": 1038,
"text": "target - reading ease"
},
{
"code": null,
"e": 1148,
"s": 1060,
"text": "standard_error - measure of the spread of scores among multiple raters for each excerpt"
},
{
"code": null,
"e": 1667,
"s": 1148,
"text": "As a target in the dataset, it is a numerical variable, and it is proposed to solve the regression problem. However, I decided to replace it with a classification problem. The main reason is that the library I will use does not support working with text and embeddings in regression problems. I hope that developers will eliminate this deficiency in the future. But in any case, the problems of regression and classification are closely related, and for analysis, it makes no difference which of the problems to solve."
},
{
"code": null,
"e": 1720,
"s": 1667,
"text": "Let’s calculate the number of bins by Sturge’s rule:"
},
{
"code": null,
"e": 1881,
"s": 1720,
"text": "num_bins = int(np.floor(1 + np.log2(len(train))))train['target_q'], bin_edges = pd.qcut(train['target'], q=num_bins, labels=False, retbins=True, precision=0)"
},
{
"code": null,
"e": 1914,
"s": 1881,
"text": "But, first, I clean up the data."
},
{
"code": null,
"e": 2028,
"s": 1914,
"text": "train['license'] = train['license'].fillna('nan')train['license'] = train['license'].astype('category').cat.codes"
},
{
"code": null,
"e": 2179,
"s": 2028,
"text": "With the help of a small self-written function, I clean and lemmatize the text. The function can be complicated, but this is enough for my experiment."
},
{
"code": null,
"e": 2527,
"s": 2179,
"text": "def clean_text(text): table = text.maketrans( dict.fromkeys(string.punctuation)) words = word_tokenize( text.lower().strip().translate(table)) words = [word for word in words if word not in stopwords.words('english')] lemmed = [WordNetLemmatizer().lemmatize(word) for word in words] return \" \".join(lemmed)"
},
{
"code": null,
"e": 2570,
"s": 2527,
"text": "I saved the cleaned text as a new feature."
},
{
"code": null,
"e": 2630,
"s": 2570,
"text": "train['clean_excerpt'] = train['excerpt'].apply(clean_text)"
},
{
"code": null,
"e": 2733,
"s": 2630,
"text": "In addition to text, I can select individual words in URLs and turn this data into a new text feature."
},
{
"code": null,
"e": 2928,
"s": 2733,
"text": "def getWordsFromURL(url): return re.compile(r'[\\:/?=\\-&.]+',re.UNICODE).split(url)train['url_legal'] = train['url_legal'].fillna(\"nan\").apply(getWordsFromURL).apply( lambda x: \" \".join(x))"
},
{
"code": null,
"e": 3185,
"s": 2928,
"text": "I created several new features from the text — these are various pieces of statistical information. Again, there is a lot of room for creativity, but this data is enough for us. The primary purpose of these features is to be helpful for the baseline model."
},
{
"code": null,
"e": 4223,
"s": 3185,
"text": "def get_sentence_lengths(text): tokened = sent_tokenize(text) lengths = [] for idx,i in enumerate(tokened): splited = list(i.split(\" \")) lengths.append(len(splited)) return (max(lengths), min(lengths), round(mean(lengths), 3))def create_features(df): df_f = pd.DataFrame(index=df.index) df_f['text_len'] = df['excerpt'].apply(len) df_f['text_clean_len' ]= df['clean_excerpt'].apply(len) df_f['text_len_div'] = df_f['text_clean_len' ] / df_f['text_len'] df_f['text_word_count'] = df['clean_excerpt'].apply( lambda x : len(x.split(' '))) df_f[['max_len_sent','min_len_sent','avg_len_sent']] = \\ df_f.apply( lambda x: get_sentence_lengths(x['excerpt']), axis=1, result_type='expand') return df_ftrain = pd.concat( [train, create_features(train)], axis=1, copy=False, sort=False)basic_f_columns = [ 'text_len', 'text_clean_len', 'text_len_div', 'text_word_count', 'max_len_sent', 'min_len_sent', 'avg_len_sent']"
},
{
"code": null,
"e": 4426,
"s": 4223,
"text": "When data is scarce, it is difficult to test hypotheses, and the results are usually unstable. Therefore, to be more confident in the results, I prefer to use OOF(Out-of-Fold) predictions in such cases."
},
{
"code": null,
"e": 4796,
"s": 4426,
"text": "I chose Catboost as the free library for the model. Catboost is a high-performance, open-source library for gradient boosting on decision trees. From release 0.19.1, it supports text features for classification on GPU out-of-the-box. The main advantage is that CatBoost can include categorical functions and text functions in your data without additional preprocessing."
},
{
"code": null,
"e": 4924,
"s": 4796,
"text": "In Unconventional Sentiment Analysis: BERT vs. Catboost, I expanded on how Catboost worked with text and compared it with BERT."
},
{
"code": null,
"e": 5136,
"s": 4924,
"text": "This library has a killer feature: it knows how to work with embeddings. Unfortunately, at the moment, there is not a word about this in the documentation, and very few people know about this Catboost advantage."
},
{
"code": null,
"e": 5158,
"s": 5136,
"text": "!pip install catboost"
},
{
"code": null,
"e": 5322,
"s": 5158,
"text": "When working with Catboost, I recommend using Pool. It is a convenience wrapper combining features, labels and further metadata like categorical and text features."
},
{
"code": null,
"e": 5424,
"s": 5322,
"text": "To compare experiments, I created a baseline model that uses only numerical and categorical features."
},
{
"code": null,
"e": 5530,
"s": 5424,
"text": "I wrote a function to initialize and train the model. By the way, I didn’t select the optimal parameters."
},
{
"code": null,
"e": 5972,
"s": 5530,
"text": "def fit_model_classifier(train_pool, test_pool, **kwargs): model = CatBoostClassifier( task_type='GPU', iterations=5000, eval_metric='AUC', od_type='Iter', od_wait=500, l2_leaf_reg=10, bootstrap_type='Bernoulli', subsample=0.7, **kwargs ) return model.fit( train_pool, eval_set=test_pool, verbose=100, plot=False, use_best_model=True)"
},
{
"code": null,
"e": 6042,
"s": 5972,
"text": "For OOF implementation, I wrote a small and straightforward function."
},
{
"code": null,
"e": 8385,
"s": 6042,
"text": "def get_oof_classifier( n_folds, x_train, y, embedding_features, cat_features, text_features, tpo, seeds, num_bins, emb=None, tolist=True): ntrain = x_train.shape[0] oof_train = np.zeros((len(seeds), ntrain, num_bins)) models = {} for iseed, seed in enumerate(seeds): kf = StratifiedKFold( n_splits=n_folds, shuffle=True, random_state=seed) for i, (tr_i, t_i) in enumerate(kf.split(x_train, y)): if emb and len(emb) > 0: x_tr = pd.concat( [x_train.iloc[tr_i, :], get_embeddings( x_train.iloc[tr_i, :], emb, tolist)], axis=1, copy=False, sort=False) x_te = pd.concat( [x_train.iloc[t_i, :], get_embeddings( x_train.iloc[t_i, :], emb, tolist)], axis=1, copy=False, sort=False) columns = [ x for x in x_tr if (x not in ['excerpt'])] if not embedding_features: for c in emb: columns.remove(c) else: x_tr = x_train.iloc[tr_i, :] x_te = x_train.iloc[t_i, :] columns = [ x for x in x_tr if (x not in ['excerpt'])] x_tr = x_tr[columns] x_te = x_te[columns] y_tr = y[tr_i] y_te = y[t_i] train_pool = Pool( data=x_tr, label=y_tr, cat_features=cat_features, embedding_features=embedding_features, text_features=text_features) valid_pool = Pool( data=x_te, label=y_te, cat_features=cat_features, embedding_features=embedding_features, text_features=text_features) model = fit_model_classifier( train_pool, valid_pool, random_seed=seed, text_processing=tpo ) oof_train[iseed, t_i, :] = \\ model.predict_proba(valid_pool) models[(seed, i)] = model oof_train = oof_train.mean(axis=0) return oof_train, models"
},
{
"code": null,
"e": 8493,
"s": 8385,
"text": "I’ll write about the get_embeddings function below, but it is not used to get the model’s baseline for now."
},
{
"code": null,
"e": 8553,
"s": 8493,
"text": "I trained the baseline model with the following parameters:"
},
{
"code": null,
"e": 8870,
"s": 8553,
"text": "columns = ['license', 'url_legal'] + basic_f_columns oof_train_cb, models_cb = get_oof_classifier( n_folds=5, x_train=train[columns], y=train['target_q'].values, embedding_features=None, cat_features=['license'], text_features=['url_legal'], tpo=tpo, seeds=[0, 42, 888], num_bins=num_bins)"
},
{
"code": null,
"e": 8900,
"s": 8870,
"text": "Quality of the trained model:"
},
{
"code": null,
"e": 8979,
"s": 8900,
"text": "roc_auc_score(train['target_q'], oof_train_cb, multi_class=\"ovo\")AUC: 0.684407"
},
{
"code": null,
"e": 9122,
"s": 8979,
"text": "Now I have a benchmark for the model’s quality. Judging by the numbers, the model turned out weak, and I would not implement it in production."
},
{
"code": null,
"e": 9468,
"s": 9122,
"text": "You can translate multidimensional vectors into embedding, which is a relatively low-dimensional space. Thus, embeddings simplify machine learning for large inputs such as sparse vectors representing words. Ideally, embedding captures some of the input semantics by placing semantically similar inputs close to each other in the embedding space."
},
{
"code": null,
"e": 9800,
"s": 9468,
"text": "There are many ways to obtain such vectors, and I do not consider them in this article since this is not the purpose of the study. However, it is enough for me to get embeddings in any way; the main thing is that they save the necessary information. In most cases, I use the popular method at the moment — pre-trained transformers."
},
{
"code": null,
"e": 10854,
"s": 9800,
"text": "from sentence_transformers import SentenceTransformerSTRANSFORMERS = { 'sentence-transformers/paraphrase-mpnet-base-v2': ('mpnet', 768), 'sentence-transformers/bert-base-wikipedia-sections-mean-tokens': ('wikipedia', 768)}def get_encode(df, encoder, name): device = torch.device( \"cuda:0\" if torch.cuda.is_available() else \"cpu\") model = SentenceTransformer( encoder, cache_folder=f'./hf_{name}/' ) model.to(device) model.eval() return np.array(model.encode(df['excerpt']))def get_embeddings(df, emb=None, tolist=True): ret = pd.DataFrame(index=df.index) for e, s in STRANSFORMERS.items(): if emb and s[0] not in emb: continue ret[s[0]] = list(get_encode(df, e, s[0])) if tolist: ret = pd.concat( [ret, pd.DataFrame( ret[s[0]].tolist(), columns=[f'{s[0]}_{x}' for x in range(s[1])], index=ret.index)], axis=1, copy=False, sort=False) return ret"
},
{
"code": null,
"e": 10927,
"s": 10854,
"text": "Now I have everything to start testing different versions of the models."
},
{
"code": null,
"e": 10970,
"s": 10927,
"text": "I have several options for fitting models:"
},
{
"code": null,
"e": 10985,
"s": 10970,
"text": "text features;"
},
{
"code": null,
"e": 11005,
"s": 10985,
"text": "embedding features;"
},
{
"code": null,
"e": 11069,
"s": 11005,
"text": "embedding features like a list of separated numerical features."
},
{
"code": null,
"e": 11242,
"s": 11069,
"text": "I have consistently trained various combinations of these options, which allowed me to conclude how useful embeddings might be, or, perhaps, it is just an over-engineering."
},
{
"code": null,
"e": 11300,
"s": 11242,
"text": "As an example, I give a code that uses all three options:"
},
{
"code": null,
"e": 11712,
"s": 11300,
"text": "columns = ['license', 'url_legal', 'clean_excerpt', 'excerpt'] oof_train_cb, models_cb = get_oof_classifier( n_folds=FOLDS, x_train=train[columns], y=train['target_q'].values, embedding_features=['mpnet', 'wikipedia'], cat_features=['license'], text_features=['clean_excerpt','url_legal'], tpo=tpo, seeds=[0, 42, 888], num_bins=num_bins, emb=['mpnet', 'wikipedia'], tolist=True)"
},
{
"code": null,
"e": 11813,
"s": 11712,
"text": "For more information, I trained models on both GPU and CPU; and summarized the results in one table."
},
{
"code": null,
"e": 12186,
"s": 11813,
"text": "The first thing that shocked me was the extremely poor interaction of the text feature and embeddings. Unfortunately, I don’t have any logical explanation for this fact yet — here, a more detailed study of this issue on other datasets is required. In the meantime, note that the combined use of text and embedding for the same text can bring down the quality of the model."
},
{
"code": null,
"e": 12226,
"s": 12186,
"text": "update: I got comments from developers:"
},
{
"code": null,
"e": 12319,
"s": 12226,
"text": "“Thank you for the report! This bug was fixed in the commit and will be in the next release”"
},
{
"code": null,
"e": 12411,
"s": 12319,
"text": "And another revelation for me was that embeddings do not work when training modes on a CPU."
},
{
"code": null,
"e": 12605,
"s": 12411,
"text": "And now a good thing — if you have a GPU and could get embeddings, the best quality will be when you simultaneously use embedding both as a feature and as a list of separate numerical features."
},
{
"code": null,
"e": 12625,
"s": 12605,
"text": "In this article, I:"
},
{
"code": null,
"e": 12666,
"s": 12625,
"text": "selected a small free dataset for tests;"
},
{
"code": null,
"e": 12762,
"s": 12666,
"text": "created several statistical features for the text data to use them for making a baseline model;"
},
{
"code": null,
"e": 12833,
"s": 12762,
"text": "tested various combinations of embeddings, texts, and simple features;"
},
{
"code": null,
"e": 12864,
"s": 12833,
"text": "got some non-obvious insights."
}
] |
Pandas - Cleaning Data
|
Data cleaning means fixing bad data in your data set.
Bad data could be:
Empty cells
Data in wrong format
Wrong data
Duplicates
In this tutorial you will learn how to deal with all of them.
In the next chapters we will use this data set:
Duration Date Pulse Maxpulse Calories
0 60 '2020/12/01' 110 130 409.1
1 60 '2020/12/02' 117 145 479.0
2 60 '2020/12/03' 103 135 340.0
3 45 '2020/12/04' 109 175 282.4
4 45 '2020/12/05' 117 148 406.0
5 60 '2020/12/06' 102 127 300.0
6 60 '2020/12/07' 110 136 374.0
7 450 '2020/12/08' 104 134 253.3
8 30 '2020/12/09' 109 133 195.1
9 60 '2020/12/10' 98 124 269.0
10 60 '2020/12/11' 103 147 329.3
11 60 '2020/12/12' 100 120 250.7
12 60 '2020/12/12' 100 120 250.7
13 60 '2020/12/13' 106 128 345.3
14 60 '2020/12/14' 104 132 379.3
15 60 '2020/12/15' 98 123 275.0
16 60 '2020/12/16' 98 120 215.2
17 60 '2020/12/17' 100 120 300.0
18 45 '2020/12/18' 90 112 NaN
19 60 '2020/12/19' 103 123 323.0
20 45 '2020/12/20' 97 125 243.0
21 60 '2020/12/21' 108 131 364.2
22 45 NaN 100 119 282.0
23 60 '2020/12/23' 130 101 300.0
24 45 '2020/12/24' 105 132 246.0
25 60 '2020/12/25' 102 126 334.5
26 60 2020/12/26 100 120 250.0
27 60 '2020/12/27' 92 118 241.0
28 60 '2020/12/28' 103 132 NaN
29 60 '2020/12/29' 100 132 280.0
30 60 '2020/12/30' 102 129 380.3
31 60 '2020/12/31' 92 115 243.0
The data set contains some empty cells ("Date" in row 22, and "Calories" in row 18 and 28).
The data set contains wrong format ("Date" in row 26).
The data set contains wrong data ("Duration" in row 7).
The data set contains duplicates (row 11 and 12).
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": 54,
"s": 0,
"text": "Data cleaning means fixing bad data in your data set."
},
{
"code": null,
"e": 74,
"s": 54,
"text": "Bad data could be: "
},
{
"code": null,
"e": 86,
"s": 74,
"text": "Empty cells"
},
{
"code": null,
"e": 107,
"s": 86,
"text": "Data in wrong format"
},
{
"code": null,
"e": 118,
"s": 107,
"text": "Wrong data"
},
{
"code": null,
"e": 129,
"s": 118,
"text": "Duplicates"
},
{
"code": null,
"e": 191,
"s": 129,
"text": "In this tutorial you will learn how to deal with all of them."
},
{
"code": null,
"e": 239,
"s": 191,
"text": "In the next chapters we will use this data set:"
},
{
"code": null,
"e": 2090,
"s": 239,
"text": "\n Duration Date Pulse Maxpulse Calories\n 0 60 '2020/12/01' 110 130 409.1\n 1 60 '2020/12/02' 117 145 479.0\n 2 60 '2020/12/03' 103 135 340.0\n 3 45 '2020/12/04' 109 175 282.4\n 4 45 '2020/12/05' 117 148 406.0\n 5 60 '2020/12/06' 102 127 300.0\n 6 60 '2020/12/07' 110 136 374.0\n 7 450 '2020/12/08' 104 134 253.3\n 8 30 '2020/12/09' 109 133 195.1\n 9 60 '2020/12/10' 98 124 269.0\n 10 60 '2020/12/11' 103 147 329.3\n 11 60 '2020/12/12' 100 120 250.7\n 12 60 '2020/12/12' 100 120 250.7\n 13 60 '2020/12/13' 106 128 345.3\n 14 60 '2020/12/14' 104 132 379.3\n 15 60 '2020/12/15' 98 123 275.0\n 16 60 '2020/12/16' 98 120 215.2\n 17 60 '2020/12/17' 100 120 300.0\n 18 45 '2020/12/18' 90 112 NaN\n 19 60 '2020/12/19' 103 123 323.0\n 20 45 '2020/12/20' 97 125 243.0\n 21 60 '2020/12/21' 108 131 364.2\n 22 45 NaN 100 119 282.0\n 23 60 '2020/12/23' 130 101 300.0\n 24 45 '2020/12/24' 105 132 246.0\n 25 60 '2020/12/25' 102 126 334.5\n 26 60 2020/12/26 100 120 250.0\n 27 60 '2020/12/27' 92 118 241.0\n 28 60 '2020/12/28' 103 132 NaN\n 29 60 '2020/12/29' 100 132 280.0\n 30 60 '2020/12/30' 102 129 380.3\n 31 60 '2020/12/31' 92 115 243.0\n\n"
},
{
"code": null,
"e": 2182,
"s": 2090,
"text": "The data set contains some empty cells (\"Date\" in row 22, and \"Calories\" in row 18 and 28)."
},
{
"code": null,
"e": 2237,
"s": 2182,
"text": "The data set contains wrong format (\"Date\" in row 26)."
},
{
"code": null,
"e": 2293,
"s": 2237,
"text": "The data set contains wrong data (\"Duration\" in row 7)."
},
{
"code": null,
"e": 2343,
"s": 2293,
"text": "The data set contains duplicates (row 11 and 12)."
},
{
"code": null,
"e": 2376,
"s": 2343,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2418,
"s": 2376,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2525,
"s": 2418,
"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": 2544,
"s": 2525,
"text": "help@w3schools.com"
}
] |
Android - Activities
|
If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in an Activity starting with a call on onCreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity as shown in the below Activity life cycle diagram: (image courtesy : android.com )
The Activity class defines the following call backs i.e. events. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect.
onCreate()
This is the first callback and called when the activity is first created.
onStart()
This callback is called when the activity becomes visible to the user.
onResume()
This is called when the user starts interacting with the application.
onPause()
The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed.
onStop()
This callback is called when the activity is no longer visible.
onDestroy()
This callback is called before the activity is destroyed by the system.
onRestart()
This callback is called when the activity restarts after stopping it.
This example will take you through simple steps to show Android application activity life cycle. Follow the following steps to modify the Android application we created in Hello World Example chapter −
Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file includes each of the fundamental life cycle methods. The Log.d() method has been used to generate log messages −
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class MainActivity extends Activity {
String msg = "Android : ";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event");
}
/** Called when the activity is about to become visible. */
@Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event");
}
/** Called when the activity has become visible. */
@Override
protected void onResume() {
super.onResume();
Log.d(msg, "The onResume() event");
}
/** Called when another activity is taking focus. */
@Override
protected void onPause() {
super.onPause();
Log.d(msg, "The onPause() event");
}
/** Called when the activity is no longer visible. */
@Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event");
}
/** Called just before the activity is destroyed. */
@Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
}
}
An activity class loads all the UI component using the XML file available in res/layout folder of the project. Following statement loads UI components from res/layout/activity_main.xml file:
setContentView(R.layout.activity_main);
An application can have one or more activities without any restrictions. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of apps.
Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window and you should see following log messages in LogCat window in Android studio −
08-23 10:32:07.682 4480-4480/com.example.helloworld D/Android :: The onCreate() event
08-23 10:32:07.683 4480-4480/com.example.helloworld D/Android :: The onStart() event
08-23 10:32:07.685 4480-4480/com.example.helloworld D/Android :: The onResume() event
Let us try to click lock screen button on the Android emulator and it will generate following events messages in LogCat window in android studio:
08-23 10:32:53.230 4480-4480/com.example.helloworld D/Android :: The onPause() event
08-23 10:32:53.294 4480-4480/com.example.helloworld D/Android :: The onStop() event
Let us again try to unlock your screen on the Android emulator and it will generate following events messages in LogCat window in Android studio:
08-23 10:34:41.390 4480-4480/com.example.helloworld D/Android :: The onStart() event
08-23 10:34:41.392 4480-4480/com.example.helloworld D/Android :: The onResume() event
Next, let us again try to click Back button on the Android emulator and it will generate following events messages in LogCat window in Android studio and this completes the Activity Life Cycle for an Android Application.
08-23 10:37:24.806 4480-4480/com.example.helloworld D/Android :: The onPause() event
08-23 10:37:25.668 4480-4480/com.example.helloworld D/Android :: The onStop() event
08-23 10:37:25.669 4480-4480/com.example.helloworld D/Android :: The onDestroy() event
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 4077,
"s": 3607,
"text": "If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in an Activity starting with a call on onCreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity as shown in the below Activity life cycle diagram: (image courtesy : android.com )"
},
{
"code": null,
"e": 4321,
"s": 4077,
"text": "The Activity class defines the following call backs i.e. events. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect."
},
{
"code": null,
"e": 4332,
"s": 4321,
"text": "onCreate()"
},
{
"code": null,
"e": 4406,
"s": 4332,
"text": "This is the first callback and called when the activity is first created."
},
{
"code": null,
"e": 4416,
"s": 4406,
"text": "onStart()"
},
{
"code": null,
"e": 4487,
"s": 4416,
"text": "This callback is called when the activity becomes visible to the user."
},
{
"code": null,
"e": 4498,
"s": 4487,
"text": "onResume()"
},
{
"code": null,
"e": 4568,
"s": 4498,
"text": "This is called when the user starts interacting with the application."
},
{
"code": null,
"e": 4578,
"s": 4568,
"text": "onPause()"
},
{
"code": null,
"e": 4751,
"s": 4578,
"text": "The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed."
},
{
"code": null,
"e": 4760,
"s": 4751,
"text": "onStop()"
},
{
"code": null,
"e": 4824,
"s": 4760,
"text": "This callback is called when the activity is no longer visible."
},
{
"code": null,
"e": 4836,
"s": 4824,
"text": "onDestroy()"
},
{
"code": null,
"e": 4908,
"s": 4836,
"text": "This callback is called before the activity is destroyed by the system."
},
{
"code": null,
"e": 4920,
"s": 4908,
"text": "onRestart()"
},
{
"code": null,
"e": 4990,
"s": 4920,
"text": "This callback is called when the activity restarts after stopping it."
},
{
"code": null,
"e": 5192,
"s": 4990,
"text": "This example will take you through simple steps to show Android application activity life cycle. Follow the following steps to modify the Android application we created in Hello World Example chapter −"
},
{
"code": null,
"e": 5421,
"s": 5192,
"text": "Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file includes each of the fundamental life cycle methods. The Log.d() method has been used to generate log messages −"
},
{
"code": null,
"e": 6725,
"s": 5421,
"text": "package com.example.helloworld;\n\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.util.Log;\n\npublic class MainActivity extends Activity {\n String msg = \"Android : \";\n \n /** Called when the activity is first created. */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Log.d(msg, \"The onCreate() event\");\n }\n\n /** Called when the activity is about to become visible. */\n @Override\n protected void onStart() {\n super.onStart();\n Log.d(msg, \"The onStart() event\");\n }\n\n /** Called when the activity has become visible. */\n @Override\n protected void onResume() {\n super.onResume();\n Log.d(msg, \"The onResume() event\");\n }\n\n /** Called when another activity is taking focus. */\n @Override\n protected void onPause() {\n super.onPause();\n Log.d(msg, \"The onPause() event\");\n }\n\n /** Called when the activity is no longer visible. */\n @Override\n protected void onStop() {\n super.onStop();\n Log.d(msg, \"The onStop() event\");\n }\n\n /** Called just before the activity is destroyed. */\n @Override\n public void onDestroy() {\n super.onDestroy();\n Log.d(msg, \"The onDestroy() event\");\n }\n}"
},
{
"code": null,
"e": 6916,
"s": 6725,
"text": "An activity class loads all the UI component using the XML file available in res/layout folder of the project. Following statement loads UI components from res/layout/activity_main.xml file:"
},
{
"code": null,
"e": 6956,
"s": 6916,
"text": "setContentView(R.layout.activity_main);"
},
{
"code": null,
"e": 7282,
"s": 6956,
"text": "An application can have one or more activities without any restrictions. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category as follows:"
},
{
"code": null,
"e": 7964,
"s": 7282,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.tutorialspoint7.myapplication\">\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\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\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n\n</manifest>"
},
{
"code": null,
"e": 8126,
"s": 7964,
"text": "If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of apps."
},
{
"code": null,
"e": 8608,
"s": 8126,
"text": "Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window and you should see following log messages in LogCat window in Android studio −"
},
{
"code": null,
"e": 8866,
"s": 8608,
"text": "08-23 10:32:07.682 4480-4480/com.example.helloworld D/Android :: The onCreate() event\n08-23 10:32:07.683 4480-4480/com.example.helloworld D/Android :: The onStart() event\n08-23 10:32:07.685 4480-4480/com.example.helloworld D/Android :: The onResume() event\n"
},
{
"code": null,
"e": 9012,
"s": 8866,
"text": "Let us try to click lock screen button on the Android emulator and it will generate following events messages in LogCat window in android studio:"
},
{
"code": null,
"e": 9182,
"s": 9012,
"text": "08-23 10:32:53.230 4480-4480/com.example.helloworld D/Android :: The onPause() event\n08-23 10:32:53.294 4480-4480/com.example.helloworld D/Android :: The onStop() event\n"
},
{
"code": null,
"e": 9328,
"s": 9182,
"text": "Let us again try to unlock your screen on the Android emulator and it will generate following events messages in LogCat window in Android studio:"
},
{
"code": null,
"e": 9500,
"s": 9328,
"text": "08-23 10:34:41.390 4480-4480/com.example.helloworld D/Android :: The onStart() event\n08-23 10:34:41.392 4480-4480/com.example.helloworld D/Android :: The onResume() event\n"
},
{
"code": null,
"e": 9722,
"s": 9500,
"text": "Next, let us again try to click Back button on the Android emulator and it will generate following events messages in LogCat window in Android studio and this completes the Activity Life Cycle for an Android Application."
},
{
"code": null,
"e": 9979,
"s": 9722,
"text": "08-23 10:37:24.806 4480-4480/com.example.helloworld D/Android :: The onPause() event\n08-23 10:37:25.668 4480-4480/com.example.helloworld D/Android :: The onStop() event\n08-23 10:37:25.669 4480-4480/com.example.helloworld D/Android :: The onDestroy() event\n"
},
{
"code": null,
"e": 10014,
"s": 9979,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10026,
"s": 10014,
"text": " Aditya Dua"
},
{
"code": null,
"e": 10061,
"s": 10026,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10075,
"s": 10061,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 10107,
"s": 10075,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10124,
"s": 10107,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10159,
"s": 10124,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10176,
"s": 10159,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10211,
"s": 10176,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10228,
"s": 10211,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10261,
"s": 10228,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10278,
"s": 10261,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10285,
"s": 10278,
"text": " Print"
},
{
"code": null,
"e": 10296,
"s": 10285,
"text": " Add Notes"
}
] |
Underscore.JS - Quick Guide
|
Underscore.JS is a popular javascript based library which provides 100+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on. Underscore.JS can be used directly inside a browser and also with Node.js.
Working with objects using JavaScript can be quite challenging, specifically if you have lots of manipulation to be done with them. Underscore comes with lots of features that eases your work with objects.
Underscore.JS is an open source project and you can easily contribute to the library and add features in the form of plugins and make it available on GitHub and in Node.js.
Let us understand in detail all the important features available with Underscore −
Underscore.JS provides various functions for collections like each, map, reduce which are used to apply an operation on each item of a collection. It provides method like groupBy, countBy, max, min which processes collections and ease lot of tasks.
Underscore.JS provides various functions for arrays like to iterate and process arrays like first, initial, lastIndexOf, intersection, difference etc.
Underscore.JS provides functions such as bind, delay, before, after etc.
Underscore.JS provides functions to manipulate objects, to map objects and comparing objects. For example, keys, values, extends, extendsOwn, isEqual, isEmpty etc.
Underscore.JS provides various utilities methods like noConflict, random, iteratee, escape etc.
Underscore.JS provides chaining methods as well like chain, value.
In subsequent chapters, we'll cover importants functions of Underscore.JS
In this chapter, you will learn in detail about setting up the working environment of Underscore.JS on your local computer. Before you begin with working on Underscore.JS, you need to have the access to the library. You can access its files in any of the following methods −
In this method, we are going to need Underscore.JS file from its official website and will use it directly in the browser.
As a first step, go to the official website of Underscore.JS https://underscorejs.org/.
Observe that there is a download option available which gives you the latest underscore-min.js file UMD (Production) available. Right Click on the link and choose save as. Note that the file is available with and without minification.
Now, include underscore-min.js inside the script tag and start working with Underscore.JS. For this, you can use the code given below −
<script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
Given here is a working example and its output for a better understanding −
<html>
<head>
<title>Underscore.JS - Working Example</title>
<script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
<style>
div {
border: solid 1px #ccc;
padding:10px;
font-family: "Segoe UI",Arial,sans-serif;
width: 50%;
}
</style>
</head>
<body>
<div style = "font-size:25px" id = "list">
</div>
<script type = "text/JavaScript">
var numbers = [1, 2, 3, 4];
var listOfNumbers = '';
_.each(numbers, function(x) { listOfNumbers += x + ' ' });
document.getElementById("list").innerHTML = listOfNumbers;
</script>
</body>
</html>
If you are opting for this method, make sure you have Node.js and npm installed on your system. You can use the following command to install Underscore.JS −
npm install underscore
You can observe the following output once Underscore.JS is successfully installed −
+ underscore@1.10.2
added 1 package from 1 contributor and audited 1 package in 6.331s
found 0 vulnerabilities
Now, to test if Underscore.JS works fine with Node.js, create the file tester.js and add the following code to it −
var _ = require('underscore');
var numbers = [1, 2, 3, 4];
var listOfNumbers = '';
_.each(numbers, function(x) { listOfNumbers += x + ' ' });
console.log(listOfNumbers);
Save the above program in tester.js. The following commands are used to compile and execute this program.
\>node tester.js
1 2 3 4
Underscore.JS has many easy to use methods which helps in iterating Collections. This chapter discusses them in detail.
Underscore.JS provides various methods to iterate the Collections as listed below −
_.each(list, iteratee, [context])
_.map(list, iteratee, [context])
_.reduce(list, iteratee, [memo], [context])
_.reduceRight(list, iteratee, [memo], [context])
_.find(list, predicate, [context])
_.filter(list, predicate, [context])
_.where(list, properties)
_.findWhere(list, properties)
_.reject(list, predicate, [context])
_.every(list, [predicate], [context])
_.some(list, [predicate], [context])
Underscore.JS has many easy to use methods which helps in processing Collections. This chapter discusses them in detail.
Underscore.JS provides various methods to process the Collections as listed below −
_.contains(list, value, [fromIndex])
_.invoke(list, methodName, *arguments)
_.pluck(list, propertyName)
_.max(list, [iteratee], [context])
_.min(list, [iteratee], [context])
_.sortBy(list, iteratee, [context])
_.groupBy(list, iteratee, [context])
_.indexBy(list, iteratee, [context])
_.countBy(list, iteratee, [context])
_.shuffle(list)
_.sample(list, [n])
_.toArray(list)
_.size(list)
_.partition(list, predicate)
_.compact(list)
Underscore.JS has many easy to use methods which helps in iterating Arrays. This chapter discusses them in detail.
Underscore.JS provides various methods to iterate the Arrays as listed below −
_.first(array, [n])
_.initial(array, [n])
_.last(array, [n])
_.rest(array, [index])
_.indexOf(array, value, [isSorted])
_.lastIndexOf(array, value, [fromIndex])
_.sortedIndex(array, value, [iteratee], [context])
_.findIndex(array, predicate, [context])
_.findLastIndex(array, predicate, [context])
Underscore.JS has many easy to use methods which helps in processing Arrays. This chapter discusses them in detail.
Underscore.JS provides various methods to process the Arrays as listed below −
_.flatten(array, [shallow])
_.without(array, *values)
_.union(*arrays)
_.intersection(*arrays)
_.difference(array, *others)
_.uniq(array, [isSorted], [iteratee])
_.zip(*arrays)
_.unzip(array)
_.object(list, [values])
_.chunk(array, length)
_.range([start], stop, [step])
Underscore.JS has many easy to use methods which helps in handling functions. This chapter discusses them in detail.
Underscore.JS provides various methods to handle functions as listed below −
_.bind(function, object, *arguments)
_.partial(function, *arguments)
_.memoize(function, [hashFunction])
_.delay(function, wait, *arguments)
_.once(function)
_.before(count, function)
_.wrap(function, wrapper)
_.negate(predicate)
_.compose(*functions)
Underscore.JS has many easy to use methods which helps in mapping objects. This chapter discusses them in detail.
Underscore.JS provides various methods to handle object mapping as listed below −
_.keys(object)
_.allKeys(object)
_.values(object)
_.mapObject(object, iteratee, [context])
_.pairs(object)
_.invert(object)
_.create(prototype, props)
_.functions(object)
_.findKey(object, predicate, [context])
Underscore.JS has many easy to use methods which helps in updating objects. This chapter discusses them in detail.
Underscore.JS provides various methods to handle object updates as listed below −
_.extend(destination, *sources)
_.pick(object, *keys)
_.omit(object, *keys)
_.defaults(object, *defaults)
_.clone(object)
_.tap(object, interceptor)
_.has(object, key)
_.property(path)
_.propertyOf(object)
Underscore.JS has many easy to use methods which helps in comparing objects. This chapter discusses them in detail.
Underscore.JS provides various methods to handle object comparison as listed below −
_.matcher(attrs)
_.isEqual(object, other)
_.isMatch(object, properties)
_.isEmpty(object)
_.isArray(object)
_.isObject(value)
_.isArguments(object)
_.isFunction(object)
_.isString(object)
_.isNumber(object)
_.isFinite(object)
_.isBoolean(object)
_.isDate(object)
_.isRegExp(object)
_.isError(object)
_.isSymbol(object)
_.isMap(object)
_.isWeakMap(object)
_.isSet(object)
_.isWeakSet(object)
_.isNaN(object)
_.isNull(object)
_.isUndefined(value)
Underscore.JS has many easy to use utility methods. This chapter discusses them in detail.
Underscore.JS provides various utility methods as listed below −
_.identity(value)
_.constant(value)
_.noop()
_.times(n, iteratee, [context])
_.random(min, max)
_.mixin(object)
_.iteratee(value, [context])
_.uniqueId([prefix])
_.escape(string)
_.unescape(string)
_.result(object, property, [defaultValue])
_.now()
_.template(templateString, [settings])
Underscore.JS has methods to create a chain of methods and then retrive their effective result. This chapter discusses them in detail.
Underscore.JS provides various utility methods as listed below −
_.chain(object)
_.chain(obj).value()
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2336,
"s": 1992,
"text": "Underscore.JS is a popular javascript based library which provides 100+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on. Underscore.JS can be used directly inside a browser and also with Node.js."
},
{
"code": null,
"e": 2542,
"s": 2336,
"text": "Working with objects using JavaScript can be quite challenging, specifically if you have lots of manipulation to be done with them. Underscore comes with lots of features that eases your work with objects."
},
{
"code": null,
"e": 2715,
"s": 2542,
"text": "Underscore.JS is an open source project and you can easily contribute to the library and add features in the form of plugins and make it available on GitHub and in Node.js."
},
{
"code": null,
"e": 2798,
"s": 2715,
"text": "Let us understand in detail all the important features available with Underscore −"
},
{
"code": null,
"e": 3047,
"s": 2798,
"text": "Underscore.JS provides various functions for collections like each, map, reduce which are used to apply an operation on each item of a collection. It provides method like groupBy, countBy, max, min which processes collections and ease lot of tasks."
},
{
"code": null,
"e": 3198,
"s": 3047,
"text": "Underscore.JS provides various functions for arrays like to iterate and process arrays like first, initial, lastIndexOf, intersection, difference etc."
},
{
"code": null,
"e": 3271,
"s": 3198,
"text": "Underscore.JS provides functions such as bind, delay, before, after etc."
},
{
"code": null,
"e": 3435,
"s": 3271,
"text": "Underscore.JS provides functions to manipulate objects, to map objects and comparing objects. For example, keys, values, extends, extendsOwn, isEqual, isEmpty etc."
},
{
"code": null,
"e": 3531,
"s": 3435,
"text": "Underscore.JS provides various utilities methods like noConflict, random, iteratee, escape etc."
},
{
"code": null,
"e": 3598,
"s": 3531,
"text": "Underscore.JS provides chaining methods as well like chain, value."
},
{
"code": null,
"e": 3672,
"s": 3598,
"text": "In subsequent chapters, we'll cover importants functions of Underscore.JS"
},
{
"code": null,
"e": 3947,
"s": 3672,
"text": "In this chapter, you will learn in detail about setting up the working environment of Underscore.JS on your local computer. Before you begin with working on Underscore.JS, you need to have the access to the library. You can access its files in any of the following methods −"
},
{
"code": null,
"e": 4070,
"s": 3947,
"text": "In this method, we are going to need Underscore.JS file from its official website and will use it directly in the browser."
},
{
"code": null,
"e": 4158,
"s": 4070,
"text": "As a first step, go to the official website of Underscore.JS https://underscorejs.org/."
},
{
"code": null,
"e": 4393,
"s": 4158,
"text": "Observe that there is a download option available which gives you the latest underscore-min.js file UMD (Production) available. Right Click on the link and choose save as. Note that the file is available with and without minification."
},
{
"code": null,
"e": 4529,
"s": 4393,
"text": "Now, include underscore-min.js inside the script tag and start working with Underscore.JS. For this, you can use the code given below −"
},
{
"code": null,
"e": 4623,
"s": 4529,
"text": "<script type = \"text/JavaScript\" src = \"https://underscorejs.org/underscore-min.js\"></script>"
},
{
"code": null,
"e": 4699,
"s": 4623,
"text": "Given here is a working example and its output for a better understanding −"
},
{
"code": null,
"e": 5425,
"s": 4699,
"text": "<html>\n <head>\n <title>Underscore.JS - Working Example</title>\n <script type = \"text/JavaScript\" src = \"https://underscorejs.org/underscore-min.js\"></script>\n <style>\n div {\n border: solid 1px #ccc;\n padding:10px;\n font-family: \"Segoe UI\",Arial,sans-serif;\n width: 50%;\n }\n </style>\n </head>\n <body>\n <div style = \"font-size:25px\" id = \"list\">\n\t </div>\n <script type = \"text/JavaScript\">\n var numbers = [1, 2, 3, 4];\n var listOfNumbers = '';\n _.each(numbers, function(x) { listOfNumbers += x + ' ' });\n document.getElementById(\"list\").innerHTML = listOfNumbers;\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 5582,
"s": 5425,
"text": "If you are opting for this method, make sure you have Node.js and npm installed on your system. You can use the following command to install Underscore.JS −"
},
{
"code": null,
"e": 5605,
"s": 5582,
"text": "npm install underscore"
},
{
"code": null,
"e": 5689,
"s": 5605,
"text": "You can observe the following output once Underscore.JS is successfully installed −"
},
{
"code": null,
"e": 5801,
"s": 5689,
"text": "+ underscore@1.10.2\nadded 1 package from 1 contributor and audited 1 package in 6.331s\nfound 0 vulnerabilities\n"
},
{
"code": null,
"e": 5917,
"s": 5801,
"text": "Now, to test if Underscore.JS works fine with Node.js, create the file tester.js and add the following code to it −"
},
{
"code": null,
"e": 6087,
"s": 5917,
"text": "var _ = require('underscore');\nvar numbers = [1, 2, 3, 4];\nvar listOfNumbers = '';\n_.each(numbers, function(x) { listOfNumbers += x + ' ' });\nconsole.log(listOfNumbers);"
},
{
"code": null,
"e": 6193,
"s": 6087,
"text": "Save the above program in tester.js. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 6211,
"s": 6193,
"text": "\\>node tester.js\n"
},
{
"code": null,
"e": 6220,
"s": 6211,
"text": "1 2 3 4\n"
},
{
"code": null,
"e": 6340,
"s": 6220,
"text": "Underscore.JS has many easy to use methods which helps in iterating Collections. This chapter discusses them in detail."
},
{
"code": null,
"e": 6424,
"s": 6340,
"text": "Underscore.JS provides various methods to iterate the Collections as listed below −"
},
{
"code": null,
"e": 6458,
"s": 6424,
"text": "_.each(list, iteratee, [context])"
},
{
"code": null,
"e": 6491,
"s": 6458,
"text": "_.map(list, iteratee, [context])"
},
{
"code": null,
"e": 6535,
"s": 6491,
"text": "_.reduce(list, iteratee, [memo], [context])"
},
{
"code": null,
"e": 6584,
"s": 6535,
"text": "_.reduceRight(list, iteratee, [memo], [context])"
},
{
"code": null,
"e": 6619,
"s": 6584,
"text": "_.find(list, predicate, [context])"
},
{
"code": null,
"e": 6656,
"s": 6619,
"text": "_.filter(list, predicate, [context])"
},
{
"code": null,
"e": 6682,
"s": 6656,
"text": "_.where(list, properties)"
},
{
"code": null,
"e": 6712,
"s": 6682,
"text": "_.findWhere(list, properties)"
},
{
"code": null,
"e": 6749,
"s": 6712,
"text": "_.reject(list, predicate, [context])"
},
{
"code": null,
"e": 6787,
"s": 6749,
"text": "_.every(list, [predicate], [context])"
},
{
"code": null,
"e": 6824,
"s": 6787,
"text": "_.some(list, [predicate], [context])"
},
{
"code": null,
"e": 6945,
"s": 6824,
"text": "Underscore.JS has many easy to use methods which helps in processing Collections. This chapter discusses them in detail."
},
{
"code": null,
"e": 7029,
"s": 6945,
"text": "Underscore.JS provides various methods to process the Collections as listed below −"
},
{
"code": null,
"e": 7066,
"s": 7029,
"text": "_.contains(list, value, [fromIndex])"
},
{
"code": null,
"e": 7105,
"s": 7066,
"text": "_.invoke(list, methodName, *arguments)"
},
{
"code": null,
"e": 7133,
"s": 7105,
"text": "_.pluck(list, propertyName)"
},
{
"code": null,
"e": 7168,
"s": 7133,
"text": "_.max(list, [iteratee], [context])"
},
{
"code": null,
"e": 7203,
"s": 7168,
"text": "_.min(list, [iteratee], [context])"
},
{
"code": null,
"e": 7239,
"s": 7203,
"text": "_.sortBy(list, iteratee, [context])"
},
{
"code": null,
"e": 7276,
"s": 7239,
"text": "_.groupBy(list, iteratee, [context])"
},
{
"code": null,
"e": 7313,
"s": 7276,
"text": "_.indexBy(list, iteratee, [context])"
},
{
"code": null,
"e": 7350,
"s": 7313,
"text": "_.countBy(list, iteratee, [context])"
},
{
"code": null,
"e": 7366,
"s": 7350,
"text": "_.shuffle(list)"
},
{
"code": null,
"e": 7386,
"s": 7366,
"text": "_.sample(list, [n])"
},
{
"code": null,
"e": 7402,
"s": 7386,
"text": "_.toArray(list)"
},
{
"code": null,
"e": 7415,
"s": 7402,
"text": "_.size(list)"
},
{
"code": null,
"e": 7444,
"s": 7415,
"text": "_.partition(list, predicate)"
},
{
"code": null,
"e": 7460,
"s": 7444,
"text": "_.compact(list)"
},
{
"code": null,
"e": 7575,
"s": 7460,
"text": "Underscore.JS has many easy to use methods which helps in iterating Arrays. This chapter discusses them in detail."
},
{
"code": null,
"e": 7654,
"s": 7575,
"text": "Underscore.JS provides various methods to iterate the Arrays as listed below −"
},
{
"code": null,
"e": 7674,
"s": 7654,
"text": "_.first(array, [n])"
},
{
"code": null,
"e": 7696,
"s": 7674,
"text": "_.initial(array, [n])"
},
{
"code": null,
"e": 7715,
"s": 7696,
"text": "_.last(array, [n])"
},
{
"code": null,
"e": 7739,
"s": 7715,
"text": "_.rest(array, [index]) "
},
{
"code": null,
"e": 7775,
"s": 7739,
"text": "_.indexOf(array, value, [isSorted])"
},
{
"code": null,
"e": 7816,
"s": 7775,
"text": "_.lastIndexOf(array, value, [fromIndex])"
},
{
"code": null,
"e": 7867,
"s": 7816,
"text": "_.sortedIndex(array, value, [iteratee], [context])"
},
{
"code": null,
"e": 7908,
"s": 7867,
"text": "_.findIndex(array, predicate, [context])"
},
{
"code": null,
"e": 7953,
"s": 7908,
"text": "_.findLastIndex(array, predicate, [context])"
},
{
"code": null,
"e": 8069,
"s": 7953,
"text": "Underscore.JS has many easy to use methods which helps in processing Arrays. This chapter discusses them in detail."
},
{
"code": null,
"e": 8148,
"s": 8069,
"text": "Underscore.JS provides various methods to process the Arrays as listed below −"
},
{
"code": null,
"e": 8176,
"s": 8148,
"text": "_.flatten(array, [shallow])"
},
{
"code": null,
"e": 8202,
"s": 8176,
"text": "_.without(array, *values)"
},
{
"code": null,
"e": 8219,
"s": 8202,
"text": "_.union(*arrays)"
},
{
"code": null,
"e": 8243,
"s": 8219,
"text": "_.intersection(*arrays)"
},
{
"code": null,
"e": 8272,
"s": 8243,
"text": "_.difference(array, *others)"
},
{
"code": null,
"e": 8310,
"s": 8272,
"text": "_.uniq(array, [isSorted], [iteratee])"
},
{
"code": null,
"e": 8325,
"s": 8310,
"text": "_.zip(*arrays)"
},
{
"code": null,
"e": 8340,
"s": 8325,
"text": "_.unzip(array)"
},
{
"code": null,
"e": 8365,
"s": 8340,
"text": "_.object(list, [values])"
},
{
"code": null,
"e": 8388,
"s": 8365,
"text": "_.chunk(array, length)"
},
{
"code": null,
"e": 8419,
"s": 8388,
"text": "_.range([start], stop, [step])"
},
{
"code": null,
"e": 8536,
"s": 8419,
"text": "Underscore.JS has many easy to use methods which helps in handling functions. This chapter discusses them in detail."
},
{
"code": null,
"e": 8613,
"s": 8536,
"text": "Underscore.JS provides various methods to handle functions as listed below −"
},
{
"code": null,
"e": 8650,
"s": 8613,
"text": "_.bind(function, object, *arguments)"
},
{
"code": null,
"e": 8682,
"s": 8650,
"text": "_.partial(function, *arguments)"
},
{
"code": null,
"e": 8718,
"s": 8682,
"text": "_.memoize(function, [hashFunction])"
},
{
"code": null,
"e": 8754,
"s": 8718,
"text": "_.delay(function, wait, *arguments)"
},
{
"code": null,
"e": 8771,
"s": 8754,
"text": "_.once(function)"
},
{
"code": null,
"e": 8797,
"s": 8771,
"text": "_.before(count, function)"
},
{
"code": null,
"e": 8823,
"s": 8797,
"text": "_.wrap(function, wrapper)"
},
{
"code": null,
"e": 8843,
"s": 8823,
"text": "_.negate(predicate)"
},
{
"code": null,
"e": 8865,
"s": 8843,
"text": "_.compose(*functions)"
},
{
"code": null,
"e": 8979,
"s": 8865,
"text": "Underscore.JS has many easy to use methods which helps in mapping objects. This chapter discusses them in detail."
},
{
"code": null,
"e": 9061,
"s": 8979,
"text": "Underscore.JS provides various methods to handle object mapping as listed below −"
},
{
"code": null,
"e": 9076,
"s": 9061,
"text": "_.keys(object)"
},
{
"code": null,
"e": 9094,
"s": 9076,
"text": "_.allKeys(object)"
},
{
"code": null,
"e": 9111,
"s": 9094,
"text": "_.values(object)"
},
{
"code": null,
"e": 9152,
"s": 9111,
"text": "_.mapObject(object, iteratee, [context])"
},
{
"code": null,
"e": 9168,
"s": 9152,
"text": "_.pairs(object)"
},
{
"code": null,
"e": 9185,
"s": 9168,
"text": "_.invert(object)"
},
{
"code": null,
"e": 9212,
"s": 9185,
"text": "_.create(prototype, props)"
},
{
"code": null,
"e": 9232,
"s": 9212,
"text": "_.functions(object)"
},
{
"code": null,
"e": 9272,
"s": 9232,
"text": "_.findKey(object, predicate, [context])"
},
{
"code": null,
"e": 9387,
"s": 9272,
"text": "Underscore.JS has many easy to use methods which helps in updating objects. This chapter discusses them in detail."
},
{
"code": null,
"e": 9469,
"s": 9387,
"text": "Underscore.JS provides various methods to handle object updates as listed below −"
},
{
"code": null,
"e": 9501,
"s": 9469,
"text": "_.extend(destination, *sources)"
},
{
"code": null,
"e": 9523,
"s": 9501,
"text": "_.pick(object, *keys)"
},
{
"code": null,
"e": 9545,
"s": 9523,
"text": "_.omit(object, *keys)"
},
{
"code": null,
"e": 9575,
"s": 9545,
"text": "_.defaults(object, *defaults)"
},
{
"code": null,
"e": 9591,
"s": 9575,
"text": "_.clone(object)"
},
{
"code": null,
"e": 9618,
"s": 9591,
"text": "_.tap(object, interceptor)"
},
{
"code": null,
"e": 9637,
"s": 9618,
"text": "_.has(object, key)"
},
{
"code": null,
"e": 9654,
"s": 9637,
"text": "_.property(path)"
},
{
"code": null,
"e": 9675,
"s": 9654,
"text": "_.propertyOf(object)"
},
{
"code": null,
"e": 9791,
"s": 9675,
"text": "Underscore.JS has many easy to use methods which helps in comparing objects. This chapter discusses them in detail."
},
{
"code": null,
"e": 9876,
"s": 9791,
"text": "Underscore.JS provides various methods to handle object comparison as listed below −"
},
{
"code": null,
"e": 9893,
"s": 9876,
"text": "_.matcher(attrs)"
},
{
"code": null,
"e": 9918,
"s": 9893,
"text": "_.isEqual(object, other)"
},
{
"code": null,
"e": 9948,
"s": 9918,
"text": "_.isMatch(object, properties)"
},
{
"code": null,
"e": 9966,
"s": 9948,
"text": "_.isEmpty(object)"
},
{
"code": null,
"e": 9984,
"s": 9966,
"text": "_.isArray(object)"
},
{
"code": null,
"e": 10002,
"s": 9984,
"text": "_.isObject(value)"
},
{
"code": null,
"e": 10024,
"s": 10002,
"text": "_.isArguments(object)"
},
{
"code": null,
"e": 10045,
"s": 10024,
"text": "_.isFunction(object)"
},
{
"code": null,
"e": 10064,
"s": 10045,
"text": "_.isString(object)"
},
{
"code": null,
"e": 10083,
"s": 10064,
"text": "_.isNumber(object)"
},
{
"code": null,
"e": 10102,
"s": 10083,
"text": "_.isFinite(object)"
},
{
"code": null,
"e": 10122,
"s": 10102,
"text": "_.isBoolean(object)"
},
{
"code": null,
"e": 10139,
"s": 10122,
"text": "_.isDate(object)"
},
{
"code": null,
"e": 10158,
"s": 10139,
"text": "_.isRegExp(object)"
},
{
"code": null,
"e": 10176,
"s": 10158,
"text": "_.isError(object)"
},
{
"code": null,
"e": 10195,
"s": 10176,
"text": "_.isSymbol(object)"
},
{
"code": null,
"e": 10211,
"s": 10195,
"text": "_.isMap(object)"
},
{
"code": null,
"e": 10231,
"s": 10211,
"text": "_.isWeakMap(object)"
},
{
"code": null,
"e": 10247,
"s": 10231,
"text": "_.isSet(object)"
},
{
"code": null,
"e": 10267,
"s": 10247,
"text": "_.isWeakSet(object)"
},
{
"code": null,
"e": 10283,
"s": 10267,
"text": "_.isNaN(object)"
},
{
"code": null,
"e": 10300,
"s": 10283,
"text": "_.isNull(object)"
},
{
"code": null,
"e": 10321,
"s": 10300,
"text": "_.isUndefined(value)"
},
{
"code": null,
"e": 10412,
"s": 10321,
"text": "Underscore.JS has many easy to use utility methods. This chapter discusses them in detail."
},
{
"code": null,
"e": 10477,
"s": 10412,
"text": "Underscore.JS provides various utility methods as listed below −"
},
{
"code": null,
"e": 10495,
"s": 10477,
"text": "_.identity(value)"
},
{
"code": null,
"e": 10513,
"s": 10495,
"text": "_.constant(value)"
},
{
"code": null,
"e": 10522,
"s": 10513,
"text": "_.noop()"
},
{
"code": null,
"e": 10554,
"s": 10522,
"text": "_.times(n, iteratee, [context])"
},
{
"code": null,
"e": 10573,
"s": 10554,
"text": "_.random(min, max)"
},
{
"code": null,
"e": 10589,
"s": 10573,
"text": "_.mixin(object)"
},
{
"code": null,
"e": 10618,
"s": 10589,
"text": "_.iteratee(value, [context])"
},
{
"code": null,
"e": 10639,
"s": 10618,
"text": "_.uniqueId([prefix])"
},
{
"code": null,
"e": 10656,
"s": 10639,
"text": "_.escape(string)"
},
{
"code": null,
"e": 10675,
"s": 10656,
"text": "_.unescape(string)"
},
{
"code": null,
"e": 10718,
"s": 10675,
"text": "_.result(object, property, [defaultValue])"
},
{
"code": null,
"e": 10726,
"s": 10718,
"text": "_.now()"
},
{
"code": null,
"e": 10765,
"s": 10726,
"text": "_.template(templateString, [settings])"
},
{
"code": null,
"e": 10900,
"s": 10765,
"text": "Underscore.JS has methods to create a chain of methods and then retrive their effective result. This chapter discusses them in detail."
},
{
"code": null,
"e": 10965,
"s": 10900,
"text": "Underscore.JS provides various utility methods as listed below −"
},
{
"code": null,
"e": 10981,
"s": 10965,
"text": "_.chain(object)"
},
{
"code": null,
"e": 11002,
"s": 10981,
"text": "_.chain(obj).value()"
},
{
"code": null,
"e": 11009,
"s": 11002,
"text": " Print"
},
{
"code": null,
"e": 11020,
"s": 11009,
"text": " Add Notes"
}
] |
ExpressJS - Environment
|
In this chapter, we will learn how to start developing and using the Express Framework. To start with, you should have the Node and the npm (node package manager) installed. If you don’t already have these, go to the Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal.
node --version
npm --version
You should get an output similar to the following.
v5.0.0
3.5.2
Now that we have Node and npm set up, let us understand what npm is and how to use it.
npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS.
There are two ways to install a package using npm: globally and locally.
Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code.
Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code.
npm install -g <package-name>
Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag.
Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag.
npm install <package-name>
Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project.
Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create directory) into it −
Step 2 − Now to create the package.json file using npm, use the following code.
npm init
It will ask you for the following information.
Just keep pressing enter, and enter your name at the “author name” field.
Step 3 − Now we have our package.json file set up, we will further install Express. To install Express and add it to our package.json file, use the following command −
npm install --save express
To confirm that Express has installed correctly, run the following code.
ls node_modules #(dir node_modules for windows)
Tip − The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us.
This is all we need to start development using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command −
npm install -g nodemon
You can now start working on Express.
16 Lectures
1 hours
Anadi Sharma
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2419,
"s": 2061,
"text": "In this chapter, we will learn how to start developing and using the Express Framework. To start with, you should have the Node and the npm (node package manager) installed. If you don’t already have these, go to the Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal."
},
{
"code": null,
"e": 2449,
"s": 2419,
"text": "node --version\nnpm --version\n"
},
{
"code": null,
"e": 2500,
"s": 2449,
"text": "You should get an output similar to the following."
},
{
"code": null,
"e": 2514,
"s": 2500,
"text": "v5.0.0\n3.5.2\n"
},
{
"code": null,
"e": 2601,
"s": 2514,
"text": "Now that we have Node and npm set up, let us understand what npm is and how to use it."
},
{
"code": null,
"e": 2968,
"s": 2601,
"text": "npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS."
},
{
"code": null,
"e": 3041,
"s": 2968,
"text": "There are two ways to install a package using npm: globally and locally."
},
{
"code": null,
"e": 3190,
"s": 3041,
"text": "Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code."
},
{
"code": null,
"e": 3339,
"s": 3190,
"text": "Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code."
},
{
"code": null,
"e": 3370,
"s": 3339,
"text": "npm install -g <package-name>\n"
},
{
"code": null,
"e": 3611,
"s": 3370,
"text": "Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag."
},
{
"code": null,
"e": 3852,
"s": 3611,
"text": "Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag."
},
{
"code": null,
"e": 3880,
"s": 3852,
"text": "npm install <package-name>\n"
},
{
"code": null,
"e": 4090,
"s": 3880,
"text": "Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project."
},
{
"code": null,
"e": 4198,
"s": 4090,
"text": "Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create directory) into it −"
},
{
"code": null,
"e": 4278,
"s": 4198,
"text": "Step 2 − Now to create the package.json file using npm, use the following code."
},
{
"code": null,
"e": 4288,
"s": 4278,
"text": "npm init\n"
},
{
"code": null,
"e": 4335,
"s": 4288,
"text": "It will ask you for the following information."
},
{
"code": null,
"e": 4409,
"s": 4335,
"text": "Just keep pressing enter, and enter your name at the “author name” field."
},
{
"code": null,
"e": 4577,
"s": 4409,
"text": "Step 3 − Now we have our package.json file set up, we will further install Express. To install Express and add it to our package.json file, use the following command −"
},
{
"code": null,
"e": 4605,
"s": 4577,
"text": "npm install --save express\n"
},
{
"code": null,
"e": 4678,
"s": 4605,
"text": "To confirm that Express has installed correctly, run the following code."
},
{
"code": null,
"e": 4727,
"s": 4678,
"text": "ls node_modules #(dir node_modules for windows)\n"
},
{
"code": null,
"e": 5067,
"s": 4727,
"text": "Tip − The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us."
},
{
"code": null,
"e": 5431,
"s": 5067,
"text": "This is all we need to start development using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command −"
},
{
"code": null,
"e": 5455,
"s": 5431,
"text": "npm install -g nodemon\n"
},
{
"code": null,
"e": 5493,
"s": 5455,
"text": "You can now start working on Express."
},
{
"code": null,
"e": 5526,
"s": 5493,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5540,
"s": 5526,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5547,
"s": 5540,
"text": " Print"
},
{
"code": null,
"e": 5558,
"s": 5547,
"text": " Add Notes"
}
] |
Jackson Annotations - @JsonSerialize
|
@JsonSerialize is used to specify custom serializer to marshall the json object.
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class JacksonTester {
public static void main(String args[]) throws ParseException {
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Student student = new Student("Mark", 1, dateFormat.parse("20-11-1984"));
String jsonString = mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(student);
System.out.println(jsonString);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int rollNo;
@JsonSerialize(using = CustomDateSerializer.class)
private Date dateOfBirth;
public Student(String name, int rollNo, Date dob){
this.name = name;
this.rollNo = rollNo;
this.dateOfBirth = dob;
}
public String getName(){
return name;
}
public int getRollNo(){
return rollNo;
}
public Date getDateOfBirth(){
return dateOfBirth;
}
}
class CustomDateSerializer extends StdSerializer<Date> {
private static final long serialVersionUID = 1L;
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
public CustomDateSerializer() {
this(null);
}
public CustomDateSerializer(Class<Date> t) {
super(t);
}
@Override
public void serialize(Date value,
JsonGenerator generator, SerializerProvider arg2) throws IOException {
generator.writeString(formatter.format(value));
}
}
{
"name" : "Mark",
"rollNo" : 1,
"dateOfBirth" : "20-11-1984"
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2556,
"s": 2475,
"text": "@JsonSerialize is used to specify custom serializer to marshall the json object."
},
{
"code": null,
"e": 4529,
"s": 2556,
"text": "import java.io.IOException; \nimport java.text.ParseException; \nimport java.text.SimpleDateFormat; \nimport java.util.Date; \n\nimport com.fasterxml.jackson.core.JsonGenerator; \nimport com.fasterxml.jackson.databind.ObjectMapper; \nimport com.fasterxml.jackson.databind.SerializerProvider; \nimport com.fasterxml.jackson.databind.annotation.JsonSerialize; \nimport com.fasterxml.jackson.databind.ser.std.StdSerializer; \n\npublic class JacksonTester {\n public static void main(String args[]) throws ParseException {\n ObjectMapper mapper = new ObjectMapper(); \n SimpleDateFormat dateFormat = new SimpleDateFormat(\"dd-MM-yyyy\"); \n try {\n Student student = new Student(\"Mark\", 1, dateFormat.parse(\"20-11-1984\")); \n String jsonString = mapper \n .writerWithDefaultPrettyPrinter() \n .writeValueAsString(student); \n System.out.println(jsonString); \n } \n catch (IOException e) { \n e.printStackTrace(); \n } \n }\n}\nclass Student {\n private String name; \n private int rollNo; \n @JsonSerialize(using = CustomDateSerializer.class) \n private Date dateOfBirth; \n public Student(String name, int rollNo, Date dob){ \n this.name = name; \n this.rollNo = rollNo; \n this.dateOfBirth = dob; \n }\n public String getName(){\n return name;\n }\n public int getRollNo(){\n return rollNo; \n }\n public Date getDateOfBirth(){ \n return dateOfBirth; \n }\n}\nclass CustomDateSerializer extends StdSerializer<Date> {\n private static final long serialVersionUID = 1L; \n private static SimpleDateFormat formatter = new SimpleDateFormat(\"dd-MM-yyyy\");\n public CustomDateSerializer() { \n this(null); \n } \n public CustomDateSerializer(Class<Date> t) { \n super(t); \n } \n @Override \n public void serialize(Date value, \n JsonGenerator generator, SerializerProvider arg2) throws IOException { \n generator.writeString(formatter.format(value)); \n } \n}"
},
{
"code": null,
"e": 4603,
"s": 4529,
"text": "{\n \"name\" : \"Mark\",\n \"rollNo\" : 1,\n \"dateOfBirth\" : \"20-11-1984\"\n}\n"
},
{
"code": null,
"e": 4610,
"s": 4603,
"text": " Print"
},
{
"code": null,
"e": 4621,
"s": 4610,
"text": " Add Notes"
}
] |
How to add a YouTube Video to your Website?
|
To add a YouTube Video to your website, you need to embed it. To embed a video in an HTML page, use the <iframe> element. The source attribute included the video URL. For the dimensions of the video player, set the width and height of the video appropriately.
The Video URL is the video embed link. The video we will be embedding our example will be YouTube.To get the embed link, go to a YouTube Video and click embed as shown below. You will get a link fro embed here −
You can try to run the following code to learn how to embed a video using HTML code. Copy the embed link as shown above and add it to the HTML document
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Video embed</title>
</head>
<body>
<p>Learn Eclipse</p>
<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/y881t8ilMyc" frameborder="0" allowfullscreen></iframe>
</iframe>
</body>
</html>
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "To add a YouTube Video to your website, you need to embed it. To embed a video in an HTML page, use the <iframe> element. The source attribute included the video URL. For the dimensions of the video player, set the width and height of the video appropriately."
},
{
"code": null,
"e": 1534,
"s": 1322,
"text": "The Video URL is the video embed link. The video we will be embedding our example will be YouTube.To get the embed link, go to a YouTube Video and click embed as shown below. You will get a link fro embed here −"
},
{
"code": null,
"e": 1686,
"s": 1534,
"text": "You can try to run the following code to learn how to embed a video using HTML code. Copy the embed link as shown above and add it to the HTML document"
},
{
"code": null,
"e": 1696,
"s": 1686,
"text": "Live Demo"
},
{
"code": null,
"e": 1992,
"s": 1696,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Video embed</title>\n </head>\n <body>\n <p>Learn Eclipse</p>\n <br />\n <iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/y881t8ilMyc\" frameborder=\"0\" allowfullscreen></iframe>\n </iframe>\n </body>\n</html>"
}
] |
Groovy - sort()
|
Returns a sorted copy of the original List.
List sort()
None
The sorted list.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
def lst = [13, 12, 15, 14];
def newlst = lst.sort();
println(newlst);
}
}
When we run the above program, we will get the following result −
[12, 13, 14, 15]
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2282,
"s": 2238,
"text": "Returns a sorted copy of the original List."
},
{
"code": null,
"e": 2295,
"s": 2282,
"text": "List sort()\n"
},
{
"code": null,
"e": 2300,
"s": 2295,
"text": "None"
},
{
"code": null,
"e": 2317,
"s": 2300,
"text": "The sorted list."
},
{
"code": null,
"e": 2371,
"s": 2317,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2523,
"s": 2371,
"text": "class Example { \n static void main(String[] args) { \n def lst = [13, 12, 15, 14]; \n def newlst = lst.sort(); \n println(newlst);\n }\n}"
},
{
"code": null,
"e": 2589,
"s": 2523,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2607,
"s": 2589,
"text": "[12, 13, 14, 15]\n"
},
{
"code": null,
"e": 2640,
"s": 2607,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2658,
"s": 2640,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 2693,
"s": 2658,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2711,
"s": 2693,
"text": " Packt Publishing"
},
{
"code": null,
"e": 2718,
"s": 2711,
"text": " Print"
},
{
"code": null,
"e": 2729,
"s": 2718,
"text": " Add Notes"
}
] |
Unix filename pattern matching in Python
|
Here we will see how we can get the UNIX shell style pattern matching techniques using Python. There is a module called fnmatch, which is used to do the work. This module is used to compare file name against a pattern, then returns True or False according to the matches.
To use it at first we need to import it the fnmatch standard library module.
import fnmatch
In the Unix terminal, there are some wildcards to match the patterns. These are like below −
‘*’ The asterisk is used to match everything.
‘?’ Question Mark is for matching a single character.
[seq] Sequences are used to match characters in sequence
[!seq] Not in Sequence are used to match characters which are not present in the sequence.
If we want to search asterisk or question marks as character, then we have to use them like this: [*] or [?]
The fnmatch() method takes two arguments, these are filename and pattern. This function is used to check whether the filename is matched with the given pattern or not. When the Operating System is case sensitive, then the parameters will be normalized to uppercase or lowercase letter before matching.
import fnmatch
import os
file_pattern = 'test_f*'
files = os.listdir('./unix_files')
for filename in files:
print('File: {}\t: {}'.format(filename, fnmatch.fnmatch(filename, file_pattern)))
$ python3 310.UNIX_filename.py
File: test_file5.txt : True
File: test_file2.png : True
File: test_file1.txt : True
File: another_file.txt : False
File: TEST_FILE4.txt : False
File: abc.txt : False
File: test_file3.txt : True
$
The filter() method also takes two parameters. The first one is the names, and the second one is the pattern. This pattern finds the list of matched filenames from the list of all filenames.
import fnmatch
import os
file_pattern = 'test_f*'
files = os.listdir('./unix_files')
match_file = fnmatch.filter(files, file_pattern)
print('All files:' + str(files))
print('\nMatched files:' + str(match_file))
$ python3 310.UNIX_filename.py
All files:['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'another_file.txt', 'TEST_FILE4.txt', 'abc.txt', 'test_file3.txt']
Matched files:['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'test_file3.txt']
$
The translate() method takes one parameter. The parameter is a pattern. We can use this function to convert a shell style pattern to another type of pattern to match using regular expressions in Python.
import fnmatch, re
file_pattern = 'test_f*.txt'
unix_regex = fnmatch.translate(file_pattern)
regex_object = re.compile(unix_regex)
print('Regular Expression:' + str(unix_regex))
print('Match Object:' + str(regex_object.match('test_file_abcd123.txt')))
$ python3 310.UNIX_filename.py
Regular Expression:(?s:test_f.*\.txt)\Z
Match Object:<_sre.SRE_Match object; span=(0, 21), match='test_file_abcd123.txt'>
$
|
[
{
"code": null,
"e": 1334,
"s": 1062,
"text": "Here we will see how we can get the UNIX shell style pattern matching techniques using Python. There is a module called fnmatch, which is used to do the work. This module is used to compare file name against a pattern, then returns True or False according to the matches."
},
{
"code": null,
"e": 1411,
"s": 1334,
"text": "To use it at first we need to import it the fnmatch standard library module."
},
{
"code": null,
"e": 1426,
"s": 1411,
"text": "import fnmatch"
},
{
"code": null,
"e": 1519,
"s": 1426,
"text": "In the Unix terminal, there are some wildcards to match the patterns. These are like below −"
},
{
"code": null,
"e": 1565,
"s": 1519,
"text": "‘*’ The asterisk is used to match everything."
},
{
"code": null,
"e": 1619,
"s": 1565,
"text": "‘?’ Question Mark is for matching a single character."
},
{
"code": null,
"e": 1676,
"s": 1619,
"text": "[seq] Sequences are used to match characters in sequence"
},
{
"code": null,
"e": 1767,
"s": 1676,
"text": "[!seq] Not in Sequence are used to match characters which are not present in the sequence."
},
{
"code": null,
"e": 1876,
"s": 1767,
"text": "If we want to search asterisk or question marks as character, then we have to use them like this: [*] or [?]"
},
{
"code": null,
"e": 2178,
"s": 1876,
"text": "The fnmatch() method takes two arguments, these are filename and pattern. This function is used to check whether the filename is matched with the given pattern or not. When the Operating System is case sensitive, then the parameters will be normalized to uppercase or lowercase letter before matching."
},
{
"code": null,
"e": 2371,
"s": 2178,
"text": "import fnmatch\nimport os\nfile_pattern = 'test_f*'\nfiles = os.listdir('./unix_files')\nfor filename in files:\n print('File: {}\\t: {}'.format(filename, fnmatch.fnmatch(filename, file_pattern)))"
},
{
"code": null,
"e": 2598,
"s": 2371,
"text": "$ python3 310.UNIX_filename.py\nFile: test_file5.txt : True\nFile: test_file2.png : True\nFile: test_file1.txt : True\nFile: another_file.txt : False\nFile: TEST_FILE4.txt : False\nFile: abc.txt : False\nFile: test_file3.txt : True\n$"
},
{
"code": null,
"e": 2789,
"s": 2598,
"text": "The filter() method also takes two parameters. The first one is the names, and the second one is the pattern. This pattern finds the list of matched filenames from the list of all filenames."
},
{
"code": null,
"e": 3009,
"s": 2789,
"text": "import fnmatch\nimport os\nfile_pattern = 'test_f*'\nfiles = os.listdir('./unix_files')\nmatch_file = fnmatch.filter(files, file_pattern)\n print('All files:' + str(files))\n print('\\nMatched files:' + str(match_file))"
},
{
"code": null,
"e": 3261,
"s": 3009,
"text": "$ python3 310.UNIX_filename.py\nAll files:['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'another_file.txt', 'TEST_FILE4.txt', 'abc.txt', 'test_file3.txt']\nMatched files:['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'test_file3.txt']\n$"
},
{
"code": null,
"e": 3464,
"s": 3261,
"text": "The translate() method takes one parameter. The parameter is a pattern. We can use this function to convert a shell style pattern to another type of pattern to match using regular expressions in Python."
},
{
"code": null,
"e": 3725,
"s": 3464,
"text": "import fnmatch, re\nfile_pattern = 'test_f*.txt'\nunix_regex = fnmatch.translate(file_pattern)\nregex_object = re.compile(unix_regex)\n print('Regular Expression:' + str(unix_regex))\n print('Match Object:' + str(regex_object.match('test_file_abcd123.txt')))"
},
{
"code": null,
"e": 3880,
"s": 3725,
"text": "$ python3 310.UNIX_filename.py\nRegular Expression:(?s:test_f.*\\.txt)\\Z\nMatch Object:<_sre.SRE_Match object; span=(0, 21), match='test_file_abcd123.txt'>\n$"
}
] |
Basic Operators in Shell Scripting
|
Shell is an interface using which the programmer can execute command and interact directly to the operating system. Shell scripting is giving commands that a shell can execute.
In shell also there are variables and operators that are used to manipulate these variables. There are 5 basic operators in shell scripting.
Arithmetic Operators
Relational Operators
Boolean Operators
Bitwise Operators
File Test Operators
Arithmetic operators in shell scripting are used to perform general arithmetic/ mathematical operations. There are 7 valid arithmetic operators in shell scripting −
Addition (+) is used to add two operands (variables).
Addition (+) is used to add two operands (variables).
Subtraction (-) is used to subtract two variables (operands) in shell scripting.
Subtraction (-) is used to subtract two variables (operands) in shell scripting.
Multiplication (*) is used to multiply two variables (operands) in shell scripting.
Multiplication (*) is used to multiply two variables (operands) in shell scripting.
Division (/) is used to divide two variables (operands) in shell scripting.
Division (/) is used to divide two variables (operands) in shell scripting.
Modulus (%) is used to find the remainder on division of operands in shell scripting.
Modulus (%) is used to find the remainder on division of operands in shell scripting.
Increment operator (++) is used to add one to the current value of the operator.
Increment operator (++) is used to add one to the current value of the operator.
Decrement operator (--) is used to subtract one from the current value of the operator.
Decrement operator (--) is used to subtract one from the current value of the operator.
To show implementation of arithmetic operator in shell scripting −
a = 32
b = 23
add = $((a + b))
echo sum of a and b is $add
sub = $((a - b))
echo Subtraction of a and b is $sub
mul = $((a * b))
echo product of a and b is $mul
div = $((a / b))
echo division of a and b is $div
mod = $((a % b))
echo remainder when a is divided b is $mod
((++a))
echo Increment operator when applied on "a" results into a = $a
((--b))
echo Decrement operator when applied on "b" results into b = $b
sum of a and b is 55
Subtraction of a and b is 9
product of a and b is 736
division of a and b is 1
remainder when a is divided b is 9
Increment operator when applied on a results into a = 33
Decrement operator when applied on b results into b = 24
The relational operator in shell scripting defines the relations between operands. The return value of these are either true or false depending on the operator and operands. There are 6 types of valid relational operators in shell scripting −
== operator is the operator that equates the values of two operators. It returns true if the values are equal and returns false otherwise.
== operator is the operator that equates the values of two operators. It returns true if the values are equal and returns false otherwise.
!= operator is the operator that equates the values of two operators and check for their inequality. It returns true if the values are not equal and returns false otherwise.
!= operator is the operator that equates the values of two operators and check for their inequality. It returns true if the values are not equal and returns false otherwise.
< operator is the less than operator comparing the values of two operators. If first operend’s value is smaller than seconds one then operator returns true otherwise returns false.
< operator is the less than operator comparing the values of two operators. If first operend’s value is smaller than seconds one then operator returns true otherwise returns false.
<= operator is less than or equal to operator that compares the values of two operators. If first operend’s value is smaller than or equal to seconds one then operator returns true otherwise returns false.
<= operator is less than or equal to operator that compares the values of two operators. If first operend’s value is smaller than or equal to seconds one then operator returns true otherwise returns false.
>operator is the greater than operator comparing the values of two operators. If first operend’s value is larger than seconds one then operator returns true otherwise returns false.
>operator is the greater than operator comparing the values of two operators. If first operend’s value is larger than seconds one then operator returns true otherwise returns false.
>= operator is greater than or equal to operator that compares the values of two operators. If first operend’s value is larger than or equal to seconds one then operator returns true otherwise returns false.
>= operator is greater than or equal to operator that compares the values of two operators. If first operend’s value is larger than or equal to seconds one then operator returns true otherwise returns false.
a = 32
b = 67
if(( $a==$b ))
then
echo a is equal to b.
else
echo a is not equal to b.
fi
if(( $a!=$b ))
then
echo a is not equal to b.
else
echo a is equal to b.
fi
if(( $a<$b ))
then
echo a is less than b.
else
echo a is not less than b.
fi
if(( $a<=$b ))
then
echo a is less than or equal to b.
else
echo a is not less than or equal to b.
fi
if(( $a>$b ))
then
echo a is greater than b.
else
echo a is not greater than b.
fi
if(( $a>=$b ))
then
echo a is greater than or equal to b.
else
echo a is not greater than or equal to b.
fi
a is not equal to b.
a is not equal to b.
a is less than b.
a is less than or equal to b.
a is not greater than b.
a is not greater than or equal to b.
Boolean operator also known as logical operators are used to perform logical operations in shell scripting. There are 3 types of valid logical operators in shell scripting −
Logical AND (&&) calculates the logic AND of the value that boolean. It returns true if both operands are true, otherwise false.
Logical AND (&&) calculates the logic AND of the value that boolean. It returns true if both operands are true, otherwise false.
Logical OR (||) calculates logical OR operation of boolean operands. It returns false if both operands are false otherwise true.
Logical OR (||) calculates logical OR operation of boolean operands. It returns false if both operands are false otherwise true.
Logical Not Equal to (!) calculates the negation of the single operator passed. If the value of operand is true it returns false otherwise true.
Logical Not Equal to (!) calculates the negation of the single operator passed. If the value of operand is true it returns false otherwise true.
a = true
b = false
if(($a == "true" & $b == "true" ))
then
echo Both are true.
else
echo Both are not true.
fi
if(($a == "true" || $b == "true" ))
then
echo Atleast one of them is true.
else
echo None of them is true.
fi
if(( ! $a == "true" ))
then
echo "a" was intially false.
else
echo "a" was intially true.
fi
Both are not true.
Atleast one of them is true
a was intially true.
Bitwise operator are the operators that perform bitwise operations on bit variables. There are 6 types of bitwise operators in shell scripting −
Bitwise AND (&) is the operator that does the binary AND operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator.
Bitwise AND (&) is the operator that does the binary AND operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator.
Bitwise OR (|) is the operator that does the binary OR operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator.
Bitwise OR (|) is the operator that does the binary OR operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator.
Bitwise XOR (^) is the operator that does the binary XOR operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator.
Bitwise XOR (^) is the operator that does the binary XOR operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator.
Bitwise complement (~) is the operator that does the binary NOT operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator.
Bitwise complement (~) is the operator that does the binary NOT operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator.
Bitwise Left Shift (<<) is the operator that shifts the bits of the operand to the left by n times specified at the right of the operator.
Bitwise Left Shift (<<) is the operator that shifts the bits of the operand to the left by n times specified at the right of the operator.
Bitwise Left Shift (>>) is the operator that shifts the bits of the operand to the right by n times specified at the right of the operator.
Bitwise Left Shift (>>) is the operator that shifts the bits of the operand to the right by n times specified at the right of the operator.
a = 14
b = 67
bitwiseAND=$(( a&b ))
echo Bitwise AND of a and b is $bitwiseAND
bitwiseOR=$(( a|b ))
echo Bitwise OR of a and b is $bitwiseOR
bitwiseXOR=$(( a^b ))
echo Bitwise XOR of a and b is $bitwiseXOR
bitiwiseComplement=$(( ~a ))
echo Bitwise Compliment of a is $bitiwiseComplement
leftshift=$(( a<<1 ))
echo Left Shift of a is $leftshift
rightshift=$(( b>>1 ))
echo Right Shift of b is $rightshift
Bitwise AND of a and b is 2
Bitwise OR of a and b is 79
Bitwise XOR of a and b is 77
Bitwise Compliment of a is -15
Left Shift of a is 28
Right Shift of b is 33
The file test operators are used to test particular properties of the file. Some of the file test operators are :
-b operator is used to check if the specified file is a block special file or not. If the file is a block special file then the function returns true otherwise returns false.
-b operator is used to check if the specified file is a block special file or not. If the file is a block special file then the function returns true otherwise returns false.
-s operator is the operator that is used to check the size of the given file. If the file size is greater than 0, it returns true otherwise returns false.
-s operator is the operator that is used to check the size of the given file. If the file size is greater than 0, it returns true otherwise returns false.
-r operator is the operators that check if the access to read file contents is granted or not. If read access is granted than it returns true otherwise false.
-r operator is the operators that check if the access to read file contents is granted or not. If read access is granted than it returns true otherwise false.
-w operator is the operators that check if the access to write into file is granted or not. If write access is granted than it returns true otherwise false.
-w operator is the operators that check if the access to write into file is granted or not. If write access is granted than it returns true otherwise false.
-x operator is the operators that check if the access to execute the file is granted or not. If execution access is granted than it returns true otherwise false.
-x operator is the operators that check if the access to execute the file is granted or not. If execution access is granted than it returns true otherwise false.
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "Shell is an interface using which the programmer can execute command and interact directly to the operating system. Shell scripting is giving commands that a shell can execute."
},
{
"code": null,
"e": 1380,
"s": 1239,
"text": "In shell also there are variables and operators that are used to manipulate these variables. There are 5 basic operators in shell scripting."
},
{
"code": null,
"e": 1401,
"s": 1380,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 1422,
"s": 1401,
"text": "Relational Operators"
},
{
"code": null,
"e": 1440,
"s": 1422,
"text": "Boolean Operators"
},
{
"code": null,
"e": 1458,
"s": 1440,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 1478,
"s": 1458,
"text": "File Test Operators"
},
{
"code": null,
"e": 1643,
"s": 1478,
"text": "Arithmetic operators in shell scripting are used to perform general arithmetic/ mathematical operations. There are 7 valid arithmetic operators in shell scripting −"
},
{
"code": null,
"e": 1697,
"s": 1643,
"text": "Addition (+) is used to add two operands (variables)."
},
{
"code": null,
"e": 1751,
"s": 1697,
"text": "Addition (+) is used to add two operands (variables)."
},
{
"code": null,
"e": 1832,
"s": 1751,
"text": "Subtraction (-) is used to subtract two variables (operands) in shell scripting."
},
{
"code": null,
"e": 1913,
"s": 1832,
"text": "Subtraction (-) is used to subtract two variables (operands) in shell scripting."
},
{
"code": null,
"e": 1997,
"s": 1913,
"text": "Multiplication (*) is used to multiply two variables (operands) in shell scripting."
},
{
"code": null,
"e": 2081,
"s": 1997,
"text": "Multiplication (*) is used to multiply two variables (operands) in shell scripting."
},
{
"code": null,
"e": 2157,
"s": 2081,
"text": "Division (/) is used to divide two variables (operands) in shell scripting."
},
{
"code": null,
"e": 2233,
"s": 2157,
"text": "Division (/) is used to divide two variables (operands) in shell scripting."
},
{
"code": null,
"e": 2319,
"s": 2233,
"text": "Modulus (%) is used to find the remainder on division of operands in shell scripting."
},
{
"code": null,
"e": 2405,
"s": 2319,
"text": "Modulus (%) is used to find the remainder on division of operands in shell scripting."
},
{
"code": null,
"e": 2486,
"s": 2405,
"text": "Increment operator (++) is used to add one to the current value of the operator."
},
{
"code": null,
"e": 2567,
"s": 2486,
"text": "Increment operator (++) is used to add one to the current value of the operator."
},
{
"code": null,
"e": 2655,
"s": 2567,
"text": "Decrement operator (--) is used to subtract one from the current value of the operator."
},
{
"code": null,
"e": 2743,
"s": 2655,
"text": "Decrement operator (--) is used to subtract one from the current value of the operator."
},
{
"code": null,
"e": 2810,
"s": 2743,
"text": "To show implementation of arithmetic operator in shell scripting −"
},
{
"code": null,
"e": 3255,
"s": 2810,
"text": "a = 32\nb = 23\n add = $((a + b))\n echo sum of a and b is $add\n sub = $((a - b))\n echo Subtraction of a and b is $sub\n mul = $((a * b))\n echo product of a and b is $mul\n div = $((a / b))\n echo division of a and b is $div\nmod = $((a % b))\n echo remainder when a is divided b is $mod\n((++a))\n echo Increment operator when applied on \"a\" results into a = $a\n((--b))\necho Decrement operator when applied on \"b\" results into b = $b"
},
{
"code": null,
"e": 3504,
"s": 3255,
"text": "sum of a and b is 55\nSubtraction of a and b is 9\nproduct of a and b is 736\ndivision of a and b is 1\nremainder when a is divided b is 9\nIncrement operator when applied on a results into a = 33\nDecrement operator when applied on b results into b = 24"
},
{
"code": null,
"e": 3747,
"s": 3504,
"text": "The relational operator in shell scripting defines the relations between operands. The return value of these are either true or false depending on the operator and operands. There are 6 types of valid relational operators in shell scripting −"
},
{
"code": null,
"e": 3886,
"s": 3747,
"text": "== operator is the operator that equates the values of two operators. It returns true if the values are equal and returns false otherwise."
},
{
"code": null,
"e": 4025,
"s": 3886,
"text": "== operator is the operator that equates the values of two operators. It returns true if the values are equal and returns false otherwise."
},
{
"code": null,
"e": 4199,
"s": 4025,
"text": "!= operator is the operator that equates the values of two operators and check for their inequality. It returns true if the values are not equal and returns false otherwise."
},
{
"code": null,
"e": 4373,
"s": 4199,
"text": "!= operator is the operator that equates the values of two operators and check for their inequality. It returns true if the values are not equal and returns false otherwise."
},
{
"code": null,
"e": 4554,
"s": 4373,
"text": "< operator is the less than operator comparing the values of two operators. If first operend’s value is smaller than seconds one then operator returns true otherwise returns false."
},
{
"code": null,
"e": 4735,
"s": 4554,
"text": "< operator is the less than operator comparing the values of two operators. If first operend’s value is smaller than seconds one then operator returns true otherwise returns false."
},
{
"code": null,
"e": 4941,
"s": 4735,
"text": "<= operator is less than or equal to operator that compares the values of two operators. If first operend’s value is smaller than or equal to seconds one then operator returns true otherwise returns false."
},
{
"code": null,
"e": 5147,
"s": 4941,
"text": "<= operator is less than or equal to operator that compares the values of two operators. If first operend’s value is smaller than or equal to seconds one then operator returns true otherwise returns false."
},
{
"code": null,
"e": 5329,
"s": 5147,
"text": ">operator is the greater than operator comparing the values of two operators. If first operend’s value is larger than seconds one then operator returns true otherwise returns false."
},
{
"code": null,
"e": 5511,
"s": 5329,
"text": ">operator is the greater than operator comparing the values of two operators. If first operend’s value is larger than seconds one then operator returns true otherwise returns false."
},
{
"code": null,
"e": 5719,
"s": 5511,
"text": ">= operator is greater than or equal to operator that compares the values of two operators. If first operend’s value is larger than or equal to seconds one then operator returns true otherwise returns false."
},
{
"code": null,
"e": 5927,
"s": 5719,
"text": ">= operator is greater than or equal to operator that compares the values of two operators. If first operend’s value is larger than or equal to seconds one then operator returns true otherwise returns false."
},
{
"code": null,
"e": 6500,
"s": 5927,
"text": "a = 32\nb = 67\nif(( $a==$b ))\nthen\n echo a is equal to b.\nelse\n echo a is not equal to b.\nfi\nif(( $a!=$b ))\nthen\n echo a is not equal to b.\nelse\n echo a is equal to b.\nfi\nif(( $a<$b ))\nthen\n echo a is less than b.\nelse\n echo a is not less than b.\nfi\n\nif(( $a<=$b ))\nthen\n echo a is less than or equal to b.\nelse\n echo a is not less than or equal to b.\nfi\nif(( $a>$b ))\nthen\n echo a is greater than b.\nelse\n echo a is not greater than b.\nfi\nif(( $a>=$b ))\nthen\n echo a is greater than or equal to b.\nelse\n echo a is not greater than or equal to b.\nfi"
},
{
"code": null,
"e": 6652,
"s": 6500,
"text": "a is not equal to b.\na is not equal to b.\na is less than b.\na is less than or equal to b.\na is not greater than b.\na is not greater than or equal to b."
},
{
"code": null,
"e": 6826,
"s": 6652,
"text": "Boolean operator also known as logical operators are used to perform logical operations in shell scripting. There are 3 types of valid logical operators in shell scripting −"
},
{
"code": null,
"e": 6955,
"s": 6826,
"text": "Logical AND (&&) calculates the logic AND of the value that boolean. It returns true if both operands are true, otherwise false."
},
{
"code": null,
"e": 7084,
"s": 6955,
"text": "Logical AND (&&) calculates the logic AND of the value that boolean. It returns true if both operands are true, otherwise false."
},
{
"code": null,
"e": 7213,
"s": 7084,
"text": "Logical OR (||) calculates logical OR operation of boolean operands. It returns false if both operands are false otherwise true."
},
{
"code": null,
"e": 7342,
"s": 7213,
"text": "Logical OR (||) calculates logical OR operation of boolean operands. It returns false if both operands are false otherwise true."
},
{
"code": null,
"e": 7487,
"s": 7342,
"text": "Logical Not Equal to (!) calculates the negation of the single operator passed. If the value of operand is true it returns false otherwise true."
},
{
"code": null,
"e": 7632,
"s": 7487,
"text": "Logical Not Equal to (!) calculates the negation of the single operator passed. If the value of operand is true it returns false otherwise true."
},
{
"code": null,
"e": 7964,
"s": 7632,
"text": "a = true\nb = false\nif(($a == \"true\" & $b == \"true\" ))\nthen\n echo Both are true.\nelse\n echo Both are not true.\nfi\nif(($a == \"true\" || $b == \"true\" ))\nthen\n echo Atleast one of them is true.\nelse\n echo None of them is true.\nfi\nif(( ! $a == \"true\" ))\nthen\n echo \"a\" was intially false.\nelse\n echo \"a\" was intially true.\nfi"
},
{
"code": null,
"e": 8032,
"s": 7964,
"text": "Both are not true.\nAtleast one of them is true\na was intially true."
},
{
"code": null,
"e": 8177,
"s": 8032,
"text": "Bitwise operator are the operators that perform bitwise operations on bit variables. There are 6 types of bitwise operators in shell scripting −"
},
{
"code": null,
"e": 8356,
"s": 8177,
"text": "Bitwise AND (&) is the operator that does the binary AND operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator."
},
{
"code": null,
"e": 8535,
"s": 8356,
"text": "Bitwise AND (&) is the operator that does the binary AND operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator."
},
{
"code": null,
"e": 8712,
"s": 8535,
"text": "Bitwise OR (|) is the operator that does the binary OR operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator."
},
{
"code": null,
"e": 8889,
"s": 8712,
"text": "Bitwise OR (|) is the operator that does the binary OR operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator."
},
{
"code": null,
"e": 9068,
"s": 8889,
"text": "Bitwise XOR (^) is the operator that does the binary XOR operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator."
},
{
"code": null,
"e": 9247,
"s": 9068,
"text": "Bitwise XOR (^) is the operator that does the binary XOR operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator."
},
{
"code": null,
"e": 9433,
"s": 9247,
"text": "Bitwise complement (~) is the operator that does the binary NOT operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator."
},
{
"code": null,
"e": 9619,
"s": 9433,
"text": "Bitwise complement (~) is the operator that does the binary NOT operation on the bits of the operands i.e. each bit of first variable is operated with respective bit of second operator."
},
{
"code": null,
"e": 9758,
"s": 9619,
"text": "Bitwise Left Shift (<<) is the operator that shifts the bits of the operand to the left by n times specified at the right of the operator."
},
{
"code": null,
"e": 9897,
"s": 9758,
"text": "Bitwise Left Shift (<<) is the operator that shifts the bits of the operand to the left by n times specified at the right of the operator."
},
{
"code": null,
"e": 10037,
"s": 9897,
"text": "Bitwise Left Shift (>>) is the operator that shifts the bits of the operand to the right by n times specified at the right of the operator."
},
{
"code": null,
"e": 10177,
"s": 10037,
"text": "Bitwise Left Shift (>>) is the operator that shifts the bits of the operand to the right by n times specified at the right of the operator."
},
{
"code": null,
"e": 10587,
"s": 10177,
"text": "a = 14\nb = 67\nbitwiseAND=$(( a&b ))\n\necho Bitwise AND of a and b is $bitwiseAND\nbitwiseOR=$(( a|b ))\n\necho Bitwise OR of a and b is $bitwiseOR\nbitwiseXOR=$(( a^b ))\n\necho Bitwise XOR of a and b is $bitwiseXOR\nbitiwiseComplement=$(( ~a ))\n\necho Bitwise Compliment of a is $bitiwiseComplement\nleftshift=$(( a<<1 ))\n\necho Left Shift of a is $leftshift\nrightshift=$(( b>>1 ))\n\necho Right Shift of b is $rightshift"
},
{
"code": null,
"e": 10748,
"s": 10587,
"text": "Bitwise AND of a and b is 2\nBitwise OR of a and b is 79\nBitwise XOR of a and b is 77\nBitwise Compliment of a is -15\nLeft Shift of a is 28\nRight Shift of b is 33"
},
{
"code": null,
"e": 10862,
"s": 10748,
"text": "The file test operators are used to test particular properties of the file. Some of the file test operators are :"
},
{
"code": null,
"e": 11037,
"s": 10862,
"text": "-b operator is used to check if the specified file is a block special file or not. If the file is a block special file then the function returns true otherwise returns false."
},
{
"code": null,
"e": 11212,
"s": 11037,
"text": "-b operator is used to check if the specified file is a block special file or not. If the file is a block special file then the function returns true otherwise returns false."
},
{
"code": null,
"e": 11367,
"s": 11212,
"text": "-s operator is the operator that is used to check the size of the given file. If the file size is greater than 0, it returns true otherwise returns false."
},
{
"code": null,
"e": 11522,
"s": 11367,
"text": "-s operator is the operator that is used to check the size of the given file. If the file size is greater than 0, it returns true otherwise returns false."
},
{
"code": null,
"e": 11681,
"s": 11522,
"text": "-r operator is the operators that check if the access to read file contents is granted or not. If read access is granted than it returns true otherwise false."
},
{
"code": null,
"e": 11840,
"s": 11681,
"text": "-r operator is the operators that check if the access to read file contents is granted or not. If read access is granted than it returns true otherwise false."
},
{
"code": null,
"e": 11997,
"s": 11840,
"text": "-w operator is the operators that check if the access to write into file is granted or not. If write access is granted than it returns true otherwise false."
},
{
"code": null,
"e": 12154,
"s": 11997,
"text": "-w operator is the operators that check if the access to write into file is granted or not. If write access is granted than it returns true otherwise false."
},
{
"code": null,
"e": 12316,
"s": 12154,
"text": "-x operator is the operators that check if the access to execute the file is granted or not. If execution access is granted than it returns true otherwise false."
},
{
"code": null,
"e": 12478,
"s": 12316,
"text": "-x operator is the operators that check if the access to execute the file is granted or not. If execution access is granted than it returns true otherwise false."
}
] |
Thread Synchronization in C#
|
Synchronize access to resources in multithreaded applications using Synchronization.
A mutex can be used to synchronize threads across processes. Use it to prevent the simultaneous execution of a block of code by more than one thread at a time.
C# lock statement is used to ensure that a block of code runs without interruption by other threads. A Mutual-exclusion lock is obtained for a given object for the duration of the code block.
A lock statement gets an object as an argument. The parameter given to the “lock” should be an object based on a reference type −
public class Demo {
private System.Object myLock = new System.Object();
public void Process() {
lock (myLock) {
}
}
}
The Mutex class in C# is a synchronization primitive that can also be used for interprocess synchronization.
Let us see how to create a new Mutex −
private static Mutex m = new Mutex();
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "Synchronize access to resources in multithreaded applications using Synchronization."
},
{
"code": null,
"e": 1307,
"s": 1147,
"text": "A mutex can be used to synchronize threads across processes. Use it to prevent the simultaneous execution of a block of code by more than one thread at a time."
},
{
"code": null,
"e": 1499,
"s": 1307,
"text": "C# lock statement is used to ensure that a block of code runs without interruption by other threads. A Mutual-exclusion lock is obtained for a given object for the duration of the code block."
},
{
"code": null,
"e": 1629,
"s": 1499,
"text": "A lock statement gets an object as an argument. The parameter given to the “lock” should be an object based on a reference type −"
},
{
"code": null,
"e": 1768,
"s": 1629,
"text": "public class Demo {\n private System.Object myLock = new System.Object();\n public void Process() {\n lock (myLock) {\n }\n }\n}"
},
{
"code": null,
"e": 1877,
"s": 1768,
"text": "The Mutex class in C# is a synchronization primitive that can also be used for interprocess synchronization."
},
{
"code": null,
"e": 1916,
"s": 1877,
"text": "Let us see how to create a new Mutex −"
},
{
"code": null,
"e": 1954,
"s": 1916,
"text": "private static Mutex m = new Mutex();"
}
] |
Java Program to Print matrix in snake pattern - GeeksforGeeks
|
11 Jan, 2022
Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern.
Examples :
Input :mat[][] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
Output : 10 20 30 40 45 35 25 15 27 29
37 48 50 39 33 32
Input :mat[][] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
Output : 1 2 3 6 5 4 7 8 9
We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to right else print from right to left.
Java
// Java program to print matrix in snake orderimport java.util.*;class GFG{ static void print(int [][] mat) { // Traverse through all rows for (int i = 0; i < mat.length; i++) { // If current row is even, print from // left to right if (i % 2 == 0) { for (int j = 0; j < mat[0].length; j++) System.out.print(mat[i][j] +" "); // If current row is odd, print from // right to left } else { for (int j = mat[0].length - 1; j >= 0; j--) System.out.print(mat[i][j] +" "); } } } // Driver code public static void main(String[] args) { int mat[][] = new int[][] { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 } }; print(mat); }}/* This code is contributed by Mr. Somesh Awasthi */
Output :
10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32
Please refer complete article on Print matrix in snake pattern for more details!
Java
Java Programs
Matrix
Matrix
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23946,
"s": 23918,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 24057,
"s": 23946,
"text": "Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern."
},
{
"code": null,
"e": 24069,
"s": 24057,
"text": "Examples : "
},
{
"code": null,
"e": 24419,
"s": 24069,
"text": "Input :mat[][] = { {10, 20, 30, 40},\n {15, 25, 35, 45},\n {27, 29, 37, 48},\n {32, 33, 39, 50}};\n \nOutput : 10 20 30 40 45 35 25 15 27 29\n 37 48 50 39 33 32 \n\nInput :mat[][] = { {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}};\nOutput : 1 2 3 6 5 4 7 8 9"
},
{
"code": null,
"e": 24558,
"s": 24421,
"text": "We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to right else print from right to left. "
},
{
"code": null,
"e": 24563,
"s": 24558,
"text": "Java"
},
{
"code": "// Java program to print matrix in snake orderimport java.util.*;class GFG{ static void print(int [][] mat) { // Traverse through all rows for (int i = 0; i < mat.length; i++) { // If current row is even, print from // left to right if (i % 2 == 0) { for (int j = 0; j < mat[0].length; j++) System.out.print(mat[i][j] +\" \"); // If current row is odd, print from // right to left } else { for (int j = mat[0].length - 1; j >= 0; j--) System.out.print(mat[i][j] +\" \"); } } } // Driver code public static void main(String[] args) { int mat[][] = new int[][] { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 } }; print(mat); }}/* This code is contributed by Mr. Somesh Awasthi */",
"e": 25578,
"s": 24563,
"text": null
},
{
"code": null,
"e": 25588,
"s": 25578,
"text": "Output : "
},
{
"code": null,
"e": 25637,
"s": 25588,
"text": "10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 "
},
{
"code": null,
"e": 25718,
"s": 25637,
"text": "Please refer complete article on Print matrix in snake pattern for more details!"
},
{
"code": null,
"e": 25723,
"s": 25718,
"text": "Java"
},
{
"code": null,
"e": 25737,
"s": 25723,
"text": "Java Programs"
},
{
"code": null,
"e": 25744,
"s": 25737,
"text": "Matrix"
},
{
"code": null,
"e": 25751,
"s": 25744,
"text": "Matrix"
},
{
"code": null,
"e": 25756,
"s": 25751,
"text": "Java"
},
{
"code": null,
"e": 25854,
"s": 25756,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25863,
"s": 25854,
"text": "Comments"
},
{
"code": null,
"e": 25876,
"s": 25863,
"text": "Old Comments"
},
{
"code": null,
"e": 25922,
"s": 25876,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25943,
"s": 25922,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25958,
"s": 25943,
"text": "Stream In Java"
},
{
"code": null,
"e": 25977,
"s": 25958,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25994,
"s": 25977,
"text": "Generics in Java"
},
{
"code": null,
"e": 26038,
"s": 25994,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26064,
"s": 26038,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26111,
"s": 26064,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 26145,
"s": 26111,
"text": "Convert Double to Integer in Java"
}
] |
Subarrays with equal 1s and 0s | Practice | GeeksforGeeks
|
Given an array containing 0s and 1s. Find the number of subarrays having equal number of 0s and 1s.
Example 1:
Input:
n = 7
A[] = {1,0,0,1,0,1,1}
Output: 8
Explanation: The index range for the 8
sub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4),
(4, 5) ,(2, 5), (0, 5), (1, 6)
Example 2:
Input:
n = 5
A[] = {1,1,1,1,0}
Output: 1
Explanation: The index range for the
subarray is (3,4).
Your Task:
You don't need to read input or print anything. Your task is to complete the function countSubarrWithEqualZeroAndOne() which takes the array arr[] and the size of the array as inputs and returns the number of subarrays with equal number of 0s and 1s.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n <= 106
0 <= A[i] <= 1
0
shubham211019976 hours ago
static int countSubarrWithEqualZeroAndOne(int arr[], int n)
{
/* Naive Approach
for(int i=0;i<n;i++){
if(arr[i]==0) arr[i]=-1;
}
int count=0;
for(int i=0;i<n-1;i++){
int sum=arr[i];
for(int j=i+1;j<n;j++){
sum+=arr[j];
if(sum==0)count++;
}
}
return count; */
HashMap<Integer,Integer>h =new HashMap<>();
for(int i=0;i<n;i++){
if(arr[i]==0) arr[i]=-1;
}
h.put(0,1);
int count=0;
int presum=0;
for(int i:arr){
presum+=i;
if(h.containsKey(presum)){
count+=h.get(presum);
h.put(presum,h.getOrDefault(presum,0)+1);
}else{
h.put(presum,h.getOrDefault(presum,0)+1);
}
}
return count;
}
0
csedeepak2 weeks ago
long long int countSubarrWithEqualZeroAndOne(int arr[], int n) { //Your code here for(int i=0; i<n; i++){ if(arr[i]==0) arr[i]=-1; } int sum=0; long long cnt=0; unordered_map<int,int> m; m[0]=1; for(int i=0; i<n; i++){ sum += arr[i]; if(m.find(sum) != m.end()) cnt += m[sum]; m[sum]++; } return cnt; }
0
ashish971chauhan2 weeks ago
int sum = 0;
int ans = 0;
HashMap<Integer,Integer> map = new HashMap<>();
map.put(0,1);
for(int i=0;i<n;i++){
if(arr[i]==0) sum += -1;
else sum += 1;
if(map.containsKey(sum)){
ans += map.get(sum);
map.put(sum , map.get(sum)+1);
}else{
map.put(sum,1);
}
}
return ans;
0
shresthjaiswal13 weeks ago
Simple Java solution
Test Cases Passed:
203 / 203
Total Time Taken:
1.92/3.23
static int countSubarrWithEqualZeroAndOne(int arr[], int n) { // add your code here for(int i=0;i<n;i++){ if(arr[i] == 0) arr[i]=-1; } HashMap<Integer,Integer> map = new HashMap<>(); int pre_sum=0,count=0; map.put(0,1); for(int i=0;i<n;i++){ pre_sum+=arr[i]; if(map.containsKey(pre_sum)){ count+= map.get(pre_sum); map.put(pre_sum,map.get(pre_sum)+1); } else{ map.put(pre_sum,1); } } return count; }
0
yk95994936811 month ago
map.get(sum)
0
visitant2 months ago
long long int countSubarrWithEqualZeroAndOne(int arr[], int n)
{ //Your code here unordered_map <int, int> hSumFreq; unordered_map <int, int> hSubArrs; long long int sum= 0; long long int count = 0; for(int i=0; i<n; i++) { if(arr[i] == 0) { sum = sum - 1; } else { sum = sum + 1; } hSumFreq[sum] +=1; hSubArrs[sum] = (hSumFreq[sum] * (hSumFreq[sum]-1))/2; if(sum == 0) { count ++; } } for(auto it = hSubArrs.begin(); it!= hSubArrs.end(); it++) { count = count + it->second; } return count; }
+1
visitant2 months ago
it is just number of zeroes + NC2 of the repetitions where N is the number of times the prefix sum has occured (greater than 1)
+1
bajpayeevinayak2282 months ago
hey,reader this solution vedio link is been give in chechk it out i have commented some line please read,and dry run i was trying hard to get the solution my advice is check this vedio try with code your self and then come to further solution happy coding
class Solution{ public: //Function to count subarrays with 1s and 0s. long long int countSubarrWithEqualZeroAndOne(int arr[], int n) { //Your code here unordered_map<int,int> umap; int threesum=0; long long int count=0; umap[0]++; for(int i=0;i<n;i++) { if(arr[i]==0) { threesum+=-1;//adding -1 to threesum if 0 found in array } else { threesum+=1;//adding -1 to threesum if 0 found in array } //auto it=umap.find(threesum); if(umap.find(threesum)!=umap.end()) ///chech with map if element present that means a there is subarry with equal number of 0/1 { count+=umap[threesum]; ///umap[threesum]++; } umap[threesum]++; } return count; }};
+4
tejshaik2 months ago
c++ sol:
unordered_map<int,long long>mp; for(int i=0;i<n;i++){ if(arr[i]==0){ arr[i]=-1; } } int sum=0; mp[sum]++; for(int i=0;i<n;i++){ sum=sum+arr[i]; mp[sum]++; if(mp[sum]>1){ co+=mp[sum]-1; } } return co; }
+2
kashyapjhon2 months ago
C++ Solution:
long long int countSubarrWithEqualZeroAndOne(int arr[], int n) { //Your code here long long sum=0; long long c=0; unordered_map<int,int> u; u.insert({0,1}); for(int i=0;i<n;i++){ if(arr[i]==1){ sum+=1; } else{ sum-=1; } auto it= u.find(sum); if(it!=u.end()){ c=c+it->second; } u[sum]++; } return c; }
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": 339,
"s": 238,
"text": "Given an array containing 0s and 1s. Find the number of subarrays having equal number of 0s and 1s. "
},
{
"code": null,
"e": 350,
"s": 339,
"text": "Example 1:"
},
{
"code": null,
"e": 515,
"s": 350,
"text": "Input:\nn = 7\nA[] = {1,0,0,1,0,1,1}\nOutput: 8\nExplanation: The index range for the 8 \nsub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4), \n(4, 5) ,(2, 5), (0, 5), (1, 6)"
},
{
"code": null,
"e": 526,
"s": 515,
"text": "Example 2:"
},
{
"code": null,
"e": 624,
"s": 526,
"text": "Input:\nn = 5\nA[] = {1,1,1,1,0}\nOutput: 1\nExplanation: The index range for the \nsubarray is (3,4)."
},
{
"code": null,
"e": 886,
"s": 624,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function countSubarrWithEqualZeroAndOne() which takes the array arr[] and the size of the array as inputs and returns the number of subarrays with equal number of 0s and 1s."
},
{
"code": null,
"e": 950,
"s": 886,
"text": "Expected Time Complexity: O(n).\nExpected Auxiliary Space: O(n)."
},
{
"code": null,
"e": 992,
"s": 950,
"text": "Constraints:\n1 <= n <= 106\n0 <= A[i] <= 1"
},
{
"code": null,
"e": 994,
"s": 992,
"text": "0"
},
{
"code": null,
"e": 1021,
"s": 994,
"text": "shubham211019976 hours ago"
},
{
"code": null,
"e": 1873,
"s": 1021,
"text": " static int countSubarrWithEqualZeroAndOne(int arr[], int n)\n {\n /* Naive Approach\n for(int i=0;i<n;i++){\n if(arr[i]==0) arr[i]=-1;\n }\n int count=0;\n for(int i=0;i<n-1;i++){\n int sum=arr[i];\n for(int j=i+1;j<n;j++){\n sum+=arr[j];\n if(sum==0)count++;\n }\n }\n return count; */\n HashMap<Integer,Integer>h =new HashMap<>();\n for(int i=0;i<n;i++){\n if(arr[i]==0) arr[i]=-1;\n }\n h.put(0,1);\n int count=0;\n int presum=0;\n for(int i:arr){\n presum+=i;\n if(h.containsKey(presum)){\n count+=h.get(presum);\n h.put(presum,h.getOrDefault(presum,0)+1);\n }else{\n h.put(presum,h.getOrDefault(presum,0)+1);\n }\n \n }\n return count;\n }"
},
{
"code": null,
"e": 1875,
"s": 1873,
"text": "0"
},
{
"code": null,
"e": 1896,
"s": 1875,
"text": "csedeepak2 weeks ago"
},
{
"code": null,
"e": 2333,
"s": 1896,
"text": "long long int countSubarrWithEqualZeroAndOne(int arr[], int n) { //Your code here for(int i=0; i<n; i++){ if(arr[i]==0) arr[i]=-1; } int sum=0; long long cnt=0; unordered_map<int,int> m; m[0]=1; for(int i=0; i<n; i++){ sum += arr[i]; if(m.find(sum) != m.end()) cnt += m[sum]; m[sum]++; } return cnt; }"
},
{
"code": null,
"e": 2335,
"s": 2333,
"text": "0"
},
{
"code": null,
"e": 2363,
"s": 2335,
"text": "ashish971chauhan2 weeks ago"
},
{
"code": null,
"e": 2827,
"s": 2363,
"text": " int sum = 0;\n int ans = 0;\n \n HashMap<Integer,Integer> map = new HashMap<>();\n map.put(0,1);\n \n for(int i=0;i<n;i++){\n if(arr[i]==0) sum += -1;\n else sum += 1;\n \n if(map.containsKey(sum)){\n ans += map.get(sum);\n map.put(sum , map.get(sum)+1);\n }else{\n map.put(sum,1);\n }\n }\n \n return ans;"
},
{
"code": null,
"e": 2829,
"s": 2827,
"text": "0"
},
{
"code": null,
"e": 2856,
"s": 2829,
"text": "shresthjaiswal13 weeks ago"
},
{
"code": null,
"e": 2877,
"s": 2856,
"text": "Simple Java solution"
},
{
"code": null,
"e": 2896,
"s": 2877,
"text": "Test Cases Passed:"
},
{
"code": null,
"e": 2906,
"s": 2896,
"text": "203 / 203"
},
{
"code": null,
"e": 2924,
"s": 2906,
"text": "Total Time Taken:"
},
{
"code": null,
"e": 2934,
"s": 2924,
"text": "1.92/3.23"
},
{
"code": null,
"e": 3540,
"s": 2936,
"text": " static int countSubarrWithEqualZeroAndOne(int arr[], int n) { // add your code here for(int i=0;i<n;i++){ if(arr[i] == 0) arr[i]=-1; } HashMap<Integer,Integer> map = new HashMap<>(); int pre_sum=0,count=0; map.put(0,1); for(int i=0;i<n;i++){ pre_sum+=arr[i]; if(map.containsKey(pre_sum)){ count+= map.get(pre_sum); map.put(pre_sum,map.get(pre_sum)+1); } else{ map.put(pre_sum,1); } } return count; }"
},
{
"code": null,
"e": 3542,
"s": 3540,
"text": "0"
},
{
"code": null,
"e": 3566,
"s": 3542,
"text": "yk95994936811 month ago"
},
{
"code": null,
"e": 3579,
"s": 3566,
"text": "map.get(sum)"
},
{
"code": null,
"e": 3581,
"s": 3579,
"text": "0"
},
{
"code": null,
"e": 3602,
"s": 3581,
"text": "visitant2 months ago"
},
{
"code": null,
"e": 3665,
"s": 3602,
"text": "long long int countSubarrWithEqualZeroAndOne(int arr[], int n)"
},
{
"code": null,
"e": 4363,
"s": 3665,
"text": "{ //Your code here unordered_map <int, int> hSumFreq; unordered_map <int, int> hSubArrs; long long int sum= 0; long long int count = 0; for(int i=0; i<n; i++) { if(arr[i] == 0) { sum = sum - 1; } else { sum = sum + 1; } hSumFreq[sum] +=1; hSubArrs[sum] = (hSumFreq[sum] * (hSumFreq[sum]-1))/2; if(sum == 0) { count ++; } } for(auto it = hSubArrs.begin(); it!= hSubArrs.end(); it++) { count = count + it->second; } return count; }"
},
{
"code": null,
"e": 4366,
"s": 4363,
"text": "+1"
},
{
"code": null,
"e": 4387,
"s": 4366,
"text": "visitant2 months ago"
},
{
"code": null,
"e": 4515,
"s": 4387,
"text": "it is just number of zeroes + NC2 of the repetitions where N is the number of times the prefix sum has occured (greater than 1)"
},
{
"code": null,
"e": 4518,
"s": 4515,
"text": "+1"
},
{
"code": null,
"e": 4549,
"s": 4518,
"text": "bajpayeevinayak2282 months ago"
},
{
"code": null,
"e": 4808,
"s": 4551,
"text": "hey,reader this solution vedio link is been give in chechk it out i have commented some line please read,and dry run i was trying hard to get the solution my advice is check this vedio try with code your self and then come to further solution happy coding "
},
{
"code": null,
"e": 5682,
"s": 4808,
"text": "class Solution{ public: //Function to count subarrays with 1s and 0s. long long int countSubarrWithEqualZeroAndOne(int arr[], int n) { //Your code here unordered_map<int,int> umap; int threesum=0; long long int count=0; umap[0]++; for(int i=0;i<n;i++) { if(arr[i]==0) { threesum+=-1;//adding -1 to threesum if 0 found in array } else { threesum+=1;//adding -1 to threesum if 0 found in array } //auto it=umap.find(threesum); if(umap.find(threesum)!=umap.end()) ///chech with map if element present that means a there is subarry with equal number of 0/1 { count+=umap[threesum]; ///umap[threesum]++; } umap[threesum]++; } return count; }};"
},
{
"code": null,
"e": 5685,
"s": 5682,
"text": "+4"
},
{
"code": null,
"e": 5706,
"s": 5685,
"text": "tejshaik2 months ago"
},
{
"code": null,
"e": 5715,
"s": 5706,
"text": "c++ sol:"
},
{
"code": null,
"e": 6056,
"s": 5715,
"text": "unordered_map<int,long long>mp; for(int i=0;i<n;i++){ if(arr[i]==0){ arr[i]=-1; } } int sum=0; mp[sum]++; for(int i=0;i<n;i++){ sum=sum+arr[i]; mp[sum]++; if(mp[sum]>1){ co+=mp[sum]-1; } } return co; }"
},
{
"code": null,
"e": 6059,
"s": 6056,
"text": "+2"
},
{
"code": null,
"e": 6083,
"s": 6059,
"text": "kashyapjhon2 months ago"
},
{
"code": null,
"e": 6097,
"s": 6083,
"text": "C++ Solution:"
},
{
"code": null,
"e": 6576,
"s": 6097,
"text": "long long int countSubarrWithEqualZeroAndOne(int arr[], int n) { //Your code here long long sum=0; long long c=0; unordered_map<int,int> u; u.insert({0,1}); for(int i=0;i<n;i++){ if(arr[i]==1){ sum+=1; } else{ sum-=1; } auto it= u.find(sum); if(it!=u.end()){ c=c+it->second; } u[sum]++; } return c; }"
},
{
"code": null,
"e": 6722,
"s": 6576,
"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": 6758,
"s": 6722,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6768,
"s": 6758,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6778,
"s": 6768,
"text": "\nContest\n"
},
{
"code": null,
"e": 6841,
"s": 6778,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6989,
"s": 6841,
"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": 7197,
"s": 6989,
"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": 7303,
"s": 7197,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Python - Geographical Data
|
Many open source python libraries now have been created to represent the geographical maps. They are highly customizable and offer a varierty of maps depicting areas in different shapes and colours.
One such package is Cartopy. You can download and install this package in your local environment from Cartopy.
You can find numerous examples in its gallery.
In the below example we show a portion of the world map showing parts of Asia and Australia. You can adjust the values of the parameters in the method set_extent to locate
different areas of world map.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
fig = plt.figure(figsize=(15, 10))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
# make the map global rather than have it zoom in to
# the extents of any plotted data
ax.set_extent((60, 150, 55, -25))
ax.stock_img()
ax.coastlines()
ax.tissot(facecolor='purple', alpha=0.8)
plt.show()
Its output is as follows −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2886,
"s": 2529,
"text": "Many open source python libraries now have been created to represent the geographical maps. They are highly customizable and offer a varierty of maps depicting areas in different shapes and colours.\nOne such package is Cartopy. You can download and install this package in your local environment from Cartopy.\nYou can find numerous examples in its gallery."
},
{
"code": null,
"e": 3088,
"s": 2886,
"text": "In the below example we show a portion of the world map showing parts of Asia and Australia. You can adjust the values of the parameters in the method set_extent to locate\ndifferent areas of world map."
},
{
"code": null,
"e": 3465,
"s": 3088,
"text": "import matplotlib.pyplot as plt\nimport cartopy.crs as ccrs \n\nfig = plt.figure(figsize=(15, 10))\nax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())\n\n # make the map global rather than have it zoom in to\n # the extents of any plotted data\n\nax.set_extent((60, 150, 55, -25))\n\nax.stock_img()\nax.coastlines()\n\nax.tissot(facecolor='purple', alpha=0.8)\n\nplt.show()"
},
{
"code": null,
"e": 3492,
"s": 3465,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3529,
"s": 3492,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3545,
"s": 3529,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3578,
"s": 3545,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3597,
"s": 3578,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3632,
"s": 3597,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3654,
"s": 3632,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3688,
"s": 3654,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3716,
"s": 3688,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3751,
"s": 3716,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3765,
"s": 3751,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3798,
"s": 3765,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3815,
"s": 3798,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3822,
"s": 3815,
"text": " Print"
},
{
"code": null,
"e": 3833,
"s": 3822,
"text": " Add Notes"
}
] |
Neural Network to play a snake game | by Slava Korolev | Towards Data Science
|
Today I’m going to talk about a small practical example of using neural networks — training one to play a snake game.
This article is for beginners, so if you are good at machine learning you will not find something interesting for you. It would be great if you know something about machine learning, neural networks, and TensorFlow but there is no problem otherwise.
And finally, obviously, there are better approaches to write a logic for a snake game but let’s pretend that it is a real task and we need to solve it this way.
Firstly we need to write a game itself. It will have a 20x20 field, a snake of 3 pieces at the start, one randomly generated apple at each moment in time and API to use with our network. You can find a code of the game here.
Now let’s start with a neural network.
To make the snake “smart” we need to give some knowledge to it — we need to create features to teach it. Always try to choose features which will be most useful. If you add not enough features, a network will not get enough information to be good. From the other side, if there are too many features. it will be hard for a network to decide which are more important and learning will be longer.
At the first step, we will learn the snake how to survive and will not think about apples. To choose a right direction it should know if there are any obstacles around it. Considering these obstacles and suggested direction the network will decide is it a good action or not.
So on the input of our neural network we will give an array of 4 numbers:
Is there an obstacle to the left of the snake (1 — yes, 0 — no)
Is there an obstacle in front of the snake (1 — yes, 0 — no)
Is there an obstacle to the right of the snake (1 — yes, 0 — no)
Suggested direction (-1 — left, 0 — forward, 1 — right)
And as the output we want to receive a decision. 1 — we should go in the selected direction, 0 — we should choose another one.
The neural network need some data to learn on. Input data is very important part of machine learning. If you have a huge amount of data, you can achieve great results even if an architecture of your network is not good. That’s why companies like Google are trying to gain all information they can get from their users (of course not because they have bad architectures but because really big data is precious).
So we need to generate some data. You can sit and play as many games as you can, but it is always good when you can generate data automatically (from scratch or modifying data that you have). In our case it is easy to create data just randomly choosing direction and observing if the snake is still alive after the turn.
After 100 games I’ve got 5504 training examples. It is enough for training to survive
Choosing the right architecture or your neural network is always hard. You can choose number of neurons in layers, number of layers and types of neurons. It always depends on task that you trying to solve. It’s better to try different variations and choose the one that fits more than others.
Our task is very simple therefore we will use only input and output layers. No hidden layers are needed.
In TensorFlow it will look like(I’m using TFLearn):
network = input_data(shape=[None, 4, 1], name='input')network = fully_connected(network, 1, activation='linear')network = regression(network, optimizer='adam', learning_rate=1e-2, loss='mean_square', name='target')model = tflearn.DNN(network)
You can find the full code here
Each turn we give to the network three arrays with possible actions and choose one with better output. After training the snake chose the easiest way to survive:
Now when the snake know how to survive, it’s time to think about apples. To teach the snake how to find apples we need to add a new feature. I chose the angle between snake’s movement direction and direction to an apple:
If an apple is to the left of snake the number will be positive, if it’s to the right — negative. Also it is always good to normalize your features. In this case we need to divide the angle by 180 degrees so the number will be from -1 to 1.
So the new input will be an array of 5 numbers:
Is there an obstacle to the left of the snake (1 — yes, 0 — no)
Is there an obstacle in front of the snake (1 — yes, 0 — no)
Is there an obstacle to the right of the snake (1 — yes, 0 — no)
Normalized angle between snake’s movement direction and direction to an apple (from -1 to 1)
Suggested direction (-1 — left, 0 — forward, 1 — right)
Now instead of just observing if the snake is alive after a turn or not, we need to decide was the turn successful or not. To do this we will calculate a distance between snake’s head and an apple before and after the turn.
And the new output will be:
-1 if the snake didn’t survive
0 if the snake survived but the direction is wrong
1 if the snake survived and the direction is right
After 10000 initial games I’ve got:
294078 turns with a right direction
280527 turns with a wrong direction
10000 wrong turns
Let’s see is it enough to teach the snake, but before we need to change its architecture.
Now we have more complicated input data and more options for the output. So let’s choose more sophisticated neural network architecture. Let’s add a hidden layer with 25 neurons.
Code:
network = input_data(shape=[None, 5, 1], name='input')network = fully_connected(network, 25, activation='relu')network = fully_connected(network, 1, activation='linear')network = regression(network, optimizer='adam', learning_rate=1e-2, loss='mean_square', name='target')model = tflearn.DNN(network)
You can find the full code here
After learning the snake shows follows results in 1000 test games:
Average number of steps —166.61
Average number of points — 12.171
How it looks:
Not bad. But we can do better. Let’s look at some inputs when the snake was wrong:
[ 1, 1, 1, 0.36420025]
[ 1, 1, 0, 0.04516724]
[ 1, 0, 1, 0.2912856]
where numbers are: [obstacle to the left, obstacle in the front, obstacle to the right, angle to an apple]
In the first example there was nothing to do for the snake considering the input data, but in the next examples there were a chance to survive and the snake chose the wrong action. What can we do with it?
There are different things you can change tuning you network — an architecture, features, learning rate, and number of input samples. If you can get more input data it’s always worth trying to use it. In our case it is very easy to generate more games. Let’s try 100000 games.
Average number of steps — 398.959
Average number of points — 25.333
And all inputs when the snake dies looks like [1, 1, 1, x]. That means that the snake dies only when there is no any way to survive.
I chose features for a neural network, an architecture and got some input data. In the result, the network calculates the best result for a given features.
Next time I’ll show you how to make it better and how to use Convolutional Neural Networks.
|
[
{
"code": null,
"e": 290,
"s": 172,
"text": "Today I’m going to talk about a small practical example of using neural networks — training one to play a snake game."
},
{
"code": null,
"e": 540,
"s": 290,
"text": "This article is for beginners, so if you are good at machine learning you will not find something interesting for you. It would be great if you know something about machine learning, neural networks, and TensorFlow but there is no problem otherwise."
},
{
"code": null,
"e": 701,
"s": 540,
"text": "And finally, obviously, there are better approaches to write a logic for a snake game but let’s pretend that it is a real task and we need to solve it this way."
},
{
"code": null,
"e": 926,
"s": 701,
"text": "Firstly we need to write a game itself. It will have a 20x20 field, a snake of 3 pieces at the start, one randomly generated apple at each moment in time and API to use with our network. You can find a code of the game here."
},
{
"code": null,
"e": 965,
"s": 926,
"text": "Now let’s start with a neural network."
},
{
"code": null,
"e": 1360,
"s": 965,
"text": "To make the snake “smart” we need to give some knowledge to it — we need to create features to teach it. Always try to choose features which will be most useful. If you add not enough features, a network will not get enough information to be good. From the other side, if there are too many features. it will be hard for a network to decide which are more important and learning will be longer."
},
{
"code": null,
"e": 1636,
"s": 1360,
"text": "At the first step, we will learn the snake how to survive and will not think about apples. To choose a right direction it should know if there are any obstacles around it. Considering these obstacles and suggested direction the network will decide is it a good action or not."
},
{
"code": null,
"e": 1710,
"s": 1636,
"text": "So on the input of our neural network we will give an array of 4 numbers:"
},
{
"code": null,
"e": 1774,
"s": 1710,
"text": "Is there an obstacle to the left of the snake (1 — yes, 0 — no)"
},
{
"code": null,
"e": 1835,
"s": 1774,
"text": "Is there an obstacle in front of the snake (1 — yes, 0 — no)"
},
{
"code": null,
"e": 1900,
"s": 1835,
"text": "Is there an obstacle to the right of the snake (1 — yes, 0 — no)"
},
{
"code": null,
"e": 1956,
"s": 1900,
"text": "Suggested direction (-1 — left, 0 — forward, 1 — right)"
},
{
"code": null,
"e": 2083,
"s": 1956,
"text": "And as the output we want to receive a decision. 1 — we should go in the selected direction, 0 — we should choose another one."
},
{
"code": null,
"e": 2494,
"s": 2083,
"text": "The neural network need some data to learn on. Input data is very important part of machine learning. If you have a huge amount of data, you can achieve great results even if an architecture of your network is not good. That’s why companies like Google are trying to gain all information they can get from their users (of course not because they have bad architectures but because really big data is precious)."
},
{
"code": null,
"e": 2815,
"s": 2494,
"text": "So we need to generate some data. You can sit and play as many games as you can, but it is always good when you can generate data automatically (from scratch or modifying data that you have). In our case it is easy to create data just randomly choosing direction and observing if the snake is still alive after the turn."
},
{
"code": null,
"e": 2901,
"s": 2815,
"text": "After 100 games I’ve got 5504 training examples. It is enough for training to survive"
},
{
"code": null,
"e": 3194,
"s": 2901,
"text": "Choosing the right architecture or your neural network is always hard. You can choose number of neurons in layers, number of layers and types of neurons. It always depends on task that you trying to solve. It’s better to try different variations and choose the one that fits more than others."
},
{
"code": null,
"e": 3299,
"s": 3194,
"text": "Our task is very simple therefore we will use only input and output layers. No hidden layers are needed."
},
{
"code": null,
"e": 3351,
"s": 3299,
"text": "In TensorFlow it will look like(I’m using TFLearn):"
},
{
"code": null,
"e": 3594,
"s": 3351,
"text": "network = input_data(shape=[None, 4, 1], name='input')network = fully_connected(network, 1, activation='linear')network = regression(network, optimizer='adam', learning_rate=1e-2, loss='mean_square', name='target')model = tflearn.DNN(network)"
},
{
"code": null,
"e": 3626,
"s": 3594,
"text": "You can find the full code here"
},
{
"code": null,
"e": 3788,
"s": 3626,
"text": "Each turn we give to the network three arrays with possible actions and choose one with better output. After training the snake chose the easiest way to survive:"
},
{
"code": null,
"e": 4009,
"s": 3788,
"text": "Now when the snake know how to survive, it’s time to think about apples. To teach the snake how to find apples we need to add a new feature. I chose the angle between snake’s movement direction and direction to an apple:"
},
{
"code": null,
"e": 4250,
"s": 4009,
"text": "If an apple is to the left of snake the number will be positive, if it’s to the right — negative. Also it is always good to normalize your features. In this case we need to divide the angle by 180 degrees so the number will be from -1 to 1."
},
{
"code": null,
"e": 4298,
"s": 4250,
"text": "So the new input will be an array of 5 numbers:"
},
{
"code": null,
"e": 4362,
"s": 4298,
"text": "Is there an obstacle to the left of the snake (1 — yes, 0 — no)"
},
{
"code": null,
"e": 4423,
"s": 4362,
"text": "Is there an obstacle in front of the snake (1 — yes, 0 — no)"
},
{
"code": null,
"e": 4488,
"s": 4423,
"text": "Is there an obstacle to the right of the snake (1 — yes, 0 — no)"
},
{
"code": null,
"e": 4581,
"s": 4488,
"text": "Normalized angle between snake’s movement direction and direction to an apple (from -1 to 1)"
},
{
"code": null,
"e": 4637,
"s": 4581,
"text": "Suggested direction (-1 — left, 0 — forward, 1 — right)"
},
{
"code": null,
"e": 4861,
"s": 4637,
"text": "Now instead of just observing if the snake is alive after a turn or not, we need to decide was the turn successful or not. To do this we will calculate a distance between snake’s head and an apple before and after the turn."
},
{
"code": null,
"e": 4889,
"s": 4861,
"text": "And the new output will be:"
},
{
"code": null,
"e": 4920,
"s": 4889,
"text": "-1 if the snake didn’t survive"
},
{
"code": null,
"e": 4971,
"s": 4920,
"text": "0 if the snake survived but the direction is wrong"
},
{
"code": null,
"e": 5022,
"s": 4971,
"text": "1 if the snake survived and the direction is right"
},
{
"code": null,
"e": 5058,
"s": 5022,
"text": "After 10000 initial games I’ve got:"
},
{
"code": null,
"e": 5094,
"s": 5058,
"text": "294078 turns with a right direction"
},
{
"code": null,
"e": 5130,
"s": 5094,
"text": "280527 turns with a wrong direction"
},
{
"code": null,
"e": 5148,
"s": 5130,
"text": "10000 wrong turns"
},
{
"code": null,
"e": 5238,
"s": 5148,
"text": "Let’s see is it enough to teach the snake, but before we need to change its architecture."
},
{
"code": null,
"e": 5417,
"s": 5238,
"text": "Now we have more complicated input data and more options for the output. So let’s choose more sophisticated neural network architecture. Let’s add a hidden layer with 25 neurons."
},
{
"code": null,
"e": 5423,
"s": 5417,
"text": "Code:"
},
{
"code": null,
"e": 5723,
"s": 5423,
"text": "network = input_data(shape=[None, 5, 1], name='input')network = fully_connected(network, 25, activation='relu')network = fully_connected(network, 1, activation='linear')network = regression(network, optimizer='adam', learning_rate=1e-2, loss='mean_square', name='target')model = tflearn.DNN(network)"
},
{
"code": null,
"e": 5755,
"s": 5723,
"text": "You can find the full code here"
},
{
"code": null,
"e": 5822,
"s": 5755,
"text": "After learning the snake shows follows results in 1000 test games:"
},
{
"code": null,
"e": 5854,
"s": 5822,
"text": "Average number of steps —166.61"
},
{
"code": null,
"e": 5888,
"s": 5854,
"text": "Average number of points — 12.171"
},
{
"code": null,
"e": 5902,
"s": 5888,
"text": "How it looks:"
},
{
"code": null,
"e": 5985,
"s": 5902,
"text": "Not bad. But we can do better. Let’s look at some inputs when the snake was wrong:"
},
{
"code": null,
"e": 6008,
"s": 5985,
"text": "[ 1, 1, 1, 0.36420025]"
},
{
"code": null,
"e": 6031,
"s": 6008,
"text": "[ 1, 1, 0, 0.04516724]"
},
{
"code": null,
"e": 6053,
"s": 6031,
"text": "[ 1, 0, 1, 0.2912856]"
},
{
"code": null,
"e": 6160,
"s": 6053,
"text": "where numbers are: [obstacle to the left, obstacle in the front, obstacle to the right, angle to an apple]"
},
{
"code": null,
"e": 6365,
"s": 6160,
"text": "In the first example there was nothing to do for the snake considering the input data, but in the next examples there were a chance to survive and the snake chose the wrong action. What can we do with it?"
},
{
"code": null,
"e": 6642,
"s": 6365,
"text": "There are different things you can change tuning you network — an architecture, features, learning rate, and number of input samples. If you can get more input data it’s always worth trying to use it. In our case it is very easy to generate more games. Let’s try 100000 games."
},
{
"code": null,
"e": 6676,
"s": 6642,
"text": "Average number of steps — 398.959"
},
{
"code": null,
"e": 6710,
"s": 6676,
"text": "Average number of points — 25.333"
},
{
"code": null,
"e": 6843,
"s": 6710,
"text": "And all inputs when the snake dies looks like [1, 1, 1, x]. That means that the snake dies only when there is no any way to survive."
},
{
"code": null,
"e": 6999,
"s": 6843,
"text": "I chose features for a neural network, an architecture and got some input data. In the result, the network calculates the best result for a given features."
}
] |
PHP - GET & POST Methods
|
There are two ways the browser client can send information to the web server.
The GET Method
The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server logs, in the browser's Location: box.
The GET method produces a long string that appears in your server logs, in the browser's Location: box.
The GET method is restricted to send upto 1024 characters only.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to the server.
Never use GET method if you have password or other sensitive information to be sent to the server.
GET can't be used to send binary data, like images or word documents, to the server.
GET can't be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment variable.
The data sent by GET method can be accessed using QUERY_STRING environment variable.
The PHP provides $_GET associative array to access all the sent information using GET method.
The PHP provides $_GET associative array to access all the sent information using GET method.
Try out following example by putting the source code in test.php script.
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
It will produce the following result −
The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
The PHP provides $_POST associative array to access all the sent information using POST method.
The PHP provides $_POST associative array to access all the sent information using POST method.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
It will produce the following result −
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
It will produce the following result −
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2835,
"s": 2757,
"text": "There are two ways the browser client can send information to the web server."
},
{
"code": null,
"e": 2850,
"s": 2835,
"text": "The GET Method"
},
{
"code": null,
"e": 2866,
"s": 2850,
"text": "The POST Method"
},
{
"code": null,
"e": 3071,
"s": 2866,
"text": "Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand."
},
{
"code": null,
"e": 3111,
"s": 3071,
"text": "name1=value1&name2=value2&name3=value3\n"
},
{
"code": null,
"e": 3304,
"s": 3111,
"text": "Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server."
},
{
"code": null,
"e": 3455,
"s": 3304,
"text": "The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character."
},
{
"code": null,
"e": 3512,
"s": 3455,
"text": "http://www.test.com/index.htm?name1=value1&name2=value2\n"
},
{
"code": null,
"e": 3616,
"s": 3512,
"text": "The GET method produces a long string that appears in your server logs, in the browser's Location: box."
},
{
"code": null,
"e": 3720,
"s": 3616,
"text": "The GET method produces a long string that appears in your server logs, in the browser's Location: box."
},
{
"code": null,
"e": 3784,
"s": 3720,
"text": "The GET method is restricted to send upto 1024 characters only."
},
{
"code": null,
"e": 3848,
"s": 3784,
"text": "The GET method is restricted to send upto 1024 characters only."
},
{
"code": null,
"e": 3947,
"s": 3848,
"text": "Never use GET method if you have password or other sensitive information to be sent to the server."
},
{
"code": null,
"e": 4046,
"s": 3947,
"text": "Never use GET method if you have password or other sensitive information to be sent to the server."
},
{
"code": null,
"e": 4131,
"s": 4046,
"text": "GET can't be used to send binary data, like images or word documents, to the server."
},
{
"code": null,
"e": 4216,
"s": 4131,
"text": "GET can't be used to send binary data, like images or word documents, to the server."
},
{
"code": null,
"e": 4301,
"s": 4216,
"text": "The data sent by GET method can be accessed using QUERY_STRING environment variable."
},
{
"code": null,
"e": 4386,
"s": 4301,
"text": "The data sent by GET method can be accessed using QUERY_STRING environment variable."
},
{
"code": null,
"e": 4480,
"s": 4386,
"text": "The PHP provides $_GET associative array to access all the sent information using GET method."
},
{
"code": null,
"e": 4574,
"s": 4480,
"text": "The PHP provides $_GET associative array to access all the sent information using GET method."
},
{
"code": null,
"e": 4647,
"s": 4574,
"text": "Try out following example by putting the source code in test.php script."
},
{
"code": null,
"e": 5082,
"s": 4647,
"text": "<?php\n if( $_GET[\"name\"] || $_GET[\"age\"] ) {\n echo \"Welcome \". $_GET['name']. \"<br />\";\n echo \"You are \". $_GET['age']. \" years old.\";\n \n exit();\n }\n?>\n<html>\n <body>\n \n <form action = \"<?php $_PHP_SELF ?>\" method = \"GET\">\n Name: <input type = \"text\" name = \"name\" />\n Age: <input type = \"text\" name = \"age\" />\n <input type = \"submit\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 5121,
"s": 5082,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5282,
"s": 5121,
"text": "The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING."
},
{
"code": null,
"e": 5353,
"s": 5282,
"text": "The POST method does not have any restriction on data size to be sent."
},
{
"code": null,
"e": 5424,
"s": 5353,
"text": "The POST method does not have any restriction on data size to be sent."
},
{
"code": null,
"e": 5490,
"s": 5424,
"text": "The POST method can be used to send ASCII as well as binary data."
},
{
"code": null,
"e": 5556,
"s": 5490,
"text": "The POST method can be used to send ASCII as well as binary data."
},
{
"code": null,
"e": 5720,
"s": 5556,
"text": "The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure."
},
{
"code": null,
"e": 5884,
"s": 5720,
"text": "The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure."
},
{
"code": null,
"e": 5980,
"s": 5884,
"text": "The PHP provides $_POST associative array to access all the sent information using POST method."
},
{
"code": null,
"e": 6076,
"s": 5980,
"text": "The PHP provides $_POST associative array to access all the sent information using POST method."
},
{
"code": null,
"e": 6149,
"s": 6076,
"text": "Try out following example by putting the source code in test.php script."
},
{
"code": null,
"e": 6707,
"s": 6149,
"text": "<?php\n if( $_POST[\"name\"] || $_POST[\"age\"] ) {\n if (preg_match(\"/[^A-Za-z'-]/\",$_POST['name'] )) {\n die (\"invalid name and name should be alpha\");\n }\n echo \"Welcome \". $_POST['name']. \"<br />\";\n echo \"You are \". $_POST['age']. \" years old.\";\n \n exit();\n }\n?>\n<html>\n <body>\n \n <form action = \"<?php $_PHP_SELF ?>\" method = \"POST\">\n Name: <input type = \"text\" name = \"name\" />\n Age: <input type = \"text\" name = \"age\" />\n <input type = \"submit\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6746,
"s": 6707,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 6902,
"s": 6746,
"text": "The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies."
},
{
"code": null,
"e": 7015,
"s": 6902,
"text": "The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods."
},
{
"code": null,
"e": 7088,
"s": 7015,
"text": "Try out following example by putting the source code in test.php script."
},
{
"code": null,
"e": 7536,
"s": 7088,
"text": "<?php\n if( $_REQUEST[\"name\"] || $_REQUEST[\"age\"] ) {\n echo \"Welcome \". $_REQUEST['name']. \"<br />\";\n echo \"You are \". $_REQUEST['age']. \" years old.\";\n exit();\n }\n?>\n<html>\n <body>\n \n <form action = \"<?php $_PHP_SELF ?>\" method = \"POST\">\n Name: <input type = \"text\" name = \"name\" />\n Age: <input type = \"text\" name = \"age\" />\n <input type = \"submit\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7623,
"s": 7536,
"text": "Here $_PHP_SELF variable contains the name of self script in which it is being called."
},
{
"code": null,
"e": 7662,
"s": 7623,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 7695,
"s": 7662,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7711,
"s": 7695,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7744,
"s": 7711,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7755,
"s": 7744,
"text": " Syed Raza"
},
{
"code": null,
"e": 7790,
"s": 7755,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7807,
"s": 7790,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7840,
"s": 7807,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7855,
"s": 7840,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 7890,
"s": 7855,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 7902,
"s": 7890,
"text": " Azaz Patel"
},
{
"code": null,
"e": 7937,
"s": 7902,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7965,
"s": 7937,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 7972,
"s": 7965,
"text": " Print"
},
{
"code": null,
"e": 7983,
"s": 7972,
"text": " Add Notes"
}
] |
Difference Between map() And flatMap() In Java Stream - GeeksforGeeks
|
03 Mar, 2021
In Java, the Stream interface has a map() and flatmap() methods and both have intermediate stream operation and return another stream as method output. Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value.
The Syntax of the map() is represented as:
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
The Syntax of the flatMap() is represented as:-
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
Where R is the element type of the new stream. The stream is an interface and T is the type of stream elements and mapper is a stateless function that is applied to each element and the function returns the new stream.
map() can be used where we have to map the elements of a particular collection to a certain function, and then we need to return the stream which contains the updated results.
Example: Multiplying All the elements of the list by 3 and returning the updated list.
flatMap() can be used where we have to flatten or transform out the string, as we cannot flatten our string using map().
Example: Getting the 1st Character of all the String present in a List of Strings and returning the result in form of a stream.
Difference Between map() and flatmap()
Below are the Java Programs using map() function:
Java
// Java program using map() functionimport java.io.*;import java.util.*;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;class GFG { public static void main(String[] args) { // making the array list object ArrayList<String> fruit = new ArrayList<>(); fruit.add("Apple"); fruit.add("mango"); fruit.add("pineapple"); fruit.add("kiwi"); System.out.println("List of fruit-" + fruit); // lets use map() to convert list of fruit List list = fruit.stream() .map(s -> s.length()) .collect(Collectors.toList()); System.out.println("List generated by map-" + list); }}
Output:
List of fruit-[Apple, mango, pineapple, kiwi]
List generated by map-[5, 5, 9, 4]
Below is the Java Program using flatMap():
Java
// Java program using flatMap() functionimport java.io.*;import java.util.*;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;class GFG { public static void main(String[] args) { // making the arraylist object of List of Integer List<List<Integer> > number = new ArrayList<>(); // adding the elements to number arraylist number.add(Arrays.asList(1, 2)); number.add(Arrays.asList(3, 4)); number.add(Arrays.asList(5, 6)); number.add(Arrays.asList(7, 8)); System.out.println("List of list-" + number); // using flatmap() to flatten this list List<Integer> flatList = number.stream() .flatMap(list -> list.stream()) .collect(Collectors.toList()); // printing the list System.out.println("List generate by flatMap-" + flatList); }}
List of list-[[1, 2], [3, 4], [5, 6], [7, 8]]
List generate by flatMap-[1, 2, 3, 4, 5, 6, 7, 8]
java-stream
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation
Differences between JDK, JRE and JVM
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24422,
"s": 24394,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 24844,
"s": 24422,
"text": "In Java, the Stream interface has a map() and flatmap() methods and both have intermediate stream operation and return another stream as method output. Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value."
},
{
"code": null,
"e": 24887,
"s": 24844,
"text": "The Syntax of the map() is represented as:"
},
{
"code": null,
"e": 24946,
"s": 24887,
"text": "<R> Stream<R> map(Function<? super T, ? extends R> mapper)"
},
{
"code": null,
"e": 24994,
"s": 24946,
"text": "The Syntax of the flatMap() is represented as:-"
},
{
"code": null,
"e": 25075,
"s": 24994,
"text": "<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)"
},
{
"code": null,
"e": 25294,
"s": 25075,
"text": "Where R is the element type of the new stream. The stream is an interface and T is the type of stream elements and mapper is a stateless function that is applied to each element and the function returns the new stream."
},
{
"code": null,
"e": 25470,
"s": 25294,
"text": "map() can be used where we have to map the elements of a particular collection to a certain function, and then we need to return the stream which contains the updated results."
},
{
"code": null,
"e": 25557,
"s": 25470,
"text": "Example: Multiplying All the elements of the list by 3 and returning the updated list."
},
{
"code": null,
"e": 25678,
"s": 25557,
"text": "flatMap() can be used where we have to flatten or transform out the string, as we cannot flatten our string using map()."
},
{
"code": null,
"e": 25806,
"s": 25678,
"text": "Example: Getting the 1st Character of all the String present in a List of Strings and returning the result in form of a stream."
},
{
"code": null,
"e": 25845,
"s": 25806,
"text": "Difference Between map() and flatmap()"
},
{
"code": null,
"e": 25895,
"s": 25845,
"text": "Below are the Java Programs using map() function:"
},
{
"code": null,
"e": 25900,
"s": 25895,
"text": "Java"
},
{
"code": "// Java program using map() functionimport java.io.*;import java.util.*;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;class GFG { public static void main(String[] args) { // making the array list object ArrayList<String> fruit = new ArrayList<>(); fruit.add(\"Apple\"); fruit.add(\"mango\"); fruit.add(\"pineapple\"); fruit.add(\"kiwi\"); System.out.println(\"List of fruit-\" + fruit); // lets use map() to convert list of fruit List list = fruit.stream() .map(s -> s.length()) .collect(Collectors.toList()); System.out.println(\"List generated by map-\" + list); }}",
"e": 26631,
"s": 25900,
"text": null
},
{
"code": null,
"e": 26639,
"s": 26631,
"text": "Output:"
},
{
"code": null,
"e": 26720,
"s": 26639,
"text": "List of fruit-[Apple, mango, pineapple, kiwi]\nList generated by map-[5, 5, 9, 4]"
},
{
"code": null,
"e": 26763,
"s": 26720,
"text": "Below is the Java Program using flatMap():"
},
{
"code": null,
"e": 26768,
"s": 26763,
"text": "Java"
},
{
"code": "// Java program using flatMap() functionimport java.io.*;import java.util.*;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;class GFG { public static void main(String[] args) { // making the arraylist object of List of Integer List<List<Integer> > number = new ArrayList<>(); // adding the elements to number arraylist number.add(Arrays.asList(1, 2)); number.add(Arrays.asList(3, 4)); number.add(Arrays.asList(5, 6)); number.add(Arrays.asList(7, 8)); System.out.println(\"List of list-\" + number); // using flatmap() to flatten this list List<Integer> flatList = number.stream() .flatMap(list -> list.stream()) .collect(Collectors.toList()); // printing the list System.out.println(\"List generate by flatMap-\" + flatList); }}",
"e": 27725,
"s": 26768,
"text": null
},
{
"code": null,
"e": 27822,
"s": 27725,
"text": "List of list-[[1, 2], [3, 4], [5, 6], [7, 8]]\nList generate by flatMap-[1, 2, 3, 4, 5, 6, 7, 8]\n"
},
{
"code": null,
"e": 27834,
"s": 27822,
"text": "java-stream"
},
{
"code": null,
"e": 27841,
"s": 27834,
"text": "Picked"
},
{
"code": null,
"e": 27865,
"s": 27841,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27884,
"s": 27865,
"text": "Difference Between"
},
{
"code": null,
"e": 27889,
"s": 27884,
"text": "Java"
},
{
"code": null,
"e": 27908,
"s": 27889,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27913,
"s": 27908,
"text": "Java"
},
{
"code": null,
"e": 28011,
"s": 27913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28072,
"s": 28011,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28110,
"s": 28072,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 28178,
"s": 28110,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28210,
"s": 28178,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 28247,
"s": 28210,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 28262,
"s": 28247,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28306,
"s": 28262,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28328,
"s": 28306,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28353,
"s": 28328,
"text": "Reverse a string in Java"
}
] |
How to use the Magnific Popup jQuery plugin? - GeeksforGeeks
|
14 Jul, 2020
Magnific Popup is a fast, light, mobile-friendly and responsive lightbox and modal dialog jQuery plugin. It can be used to open inline HTML, ajax loaded content, image, form, iframe (YouTube video, Vimeo, Google Maps), and photo gallery. It has added animation effects using CSS3 transitions.
Installation Process: There are several ways to start using this plugin:
Download the zipped folder of the latest version of Magnific Popup from here.
Alternatively, clone the Github Repository to any desired location by executing the following command in the Git Bash.git clone https://github.com/dimsemenov/Magnific-Popup.git
git clone https://github.com/dimsemenov/Magnific-Popup.git
Since the Magnific is a plugin of the jQuery framework, it needs to reference the jQuery library. This can be done by using the Google-hosted version of jQuery or downloading and using the distribution files.
Include CSS: Add the magnific-popup.css file from the dist folder of Magnific.<link rel="stylesheet" type="text/css" href="path/magnific-popup.css">
<link rel="stylesheet" type="text/css" href="path/magnific-popup.css">
Include JavaScript: Add the jquery.magnific-popup.min.js file from the dist folder of Magnific.<script type="text/javascript" src="path/jquery.magnific-popup.min.js"></script>
<script type="text/javascript" src="path/jquery.magnific-popup.min.js"></script>
Example 1: This example shows a popup using the plugin.
html
<!DOCTYPE html><html> <head> <!-- Include CSS of Magnific Popup --> <link rel="stylesheet" type="text/css" href="css/magnific-popup.css"></head> <body style="text-align:center;"> <!-- Button to open popup --> <button> <a href="#popup-info" class="open-popup" style="text-decoration: none;"> Click to Open PopUp </a> </button> <!-- Popup to display --> <div id="popup-info" class="mfp-hide" style= "text-align:center; background:white;height:600px;"> <h1 style="color: green;"> GEEKSFORGEEKS </h1> <div style="font-size: 15px; font-weight: bold;"> WELCOME TO GEEKSFORGEEKS </div> </div> <!-- Include jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- Include the Magnific Popup JavaScript --> <script type="text/javascript" src="js/jquery.magnific-popup.min.js"> </script> <script type="text/javascript"> $(document).ready(function ($) { $('.open-popup').magnificPopup({ type: 'inline', // Fixed position will be used fixContentPos: true, // Since disabled, Magnific Popup // will not put close button // inside content of popup closeBtnInside: false, preloader: false, // Delay in milliseconds before // popup is removed removalDelay: 160, // Class that is added to // popup wrapper and background mainClass: 'mfp-fade' }); }); </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 2: This example shows a popup with an image using the plugin. The gallery module allows us to switch the content of the popup and adds navigation arrows.
html
<!DOCTYPE html><html> <head> <!--Bootstrap CSS--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <!--Magnific Popup CSS--> <link rel="stylesheet" type="text/css" href="css/magnific-popup.css"></head> <body style="text-align:center;"> <h1 style="color: blue;"> :GALLERY: </h1> <!--Gallery--> <div class="container "> <div class="row no-gutters gallery" style="padding:0;"> <!--Image 1--> <div class="col-lg-6 col-md-6 col-sm-6 col-12"> <a href="images/gfg-logo.png"> <img src="images/gfg-logo.png" style="height:300px; width:100%;"> </a> </div> <!--Image 2--> <div class="col-lg-6 col-md-6 col-sm-6 col-12"> <a href="images/gfg-logo2.png"> <img src="images/gfg-logo2.png" style="height:300px; width:100%;"> </a> </div> <!--Image 3--> <div class="col-lg-6 col-md-6 col-sm-6 col-12"> <a href="images/gfg-promo.jpg"> <img src="images/gfg-promo.jpg" style="height:300px; width:100%;"> </a> </div> <!--Image 4--> <div class="col-lg-6 col-md-6 col-sm-6 col-12"> <a href="images/gfg-promo2.jpg"> <img src="images/gfg-promo2.jpg" style="height:300px; width:100%;"> </a> </div> </div> </div> <!-- Optional JavaScript --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script> <!-- Magnific Popup JavaScript--> <script type="text/javascript" src="js/jquery.magnific-popup.min.js"> </script> <script type="text/javascript"> $(document).ready(function ($) { $('.gallery').magnificPopup({ type: 'image', // To invoke the popup // using the 'a' tag delegate: 'a', // Enable the gallery gallery: { enabled: true } }); }); </script></body> </html>
Output:
Before clicking on an image:
Before clicking on an image:
After clicking on any image:
After clicking on any image:
Reference: Magnific Popup Documentation
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
jQuery-Misc
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
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)
|
[
{
"code": null,
"e": 24521,
"s": 24493,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 24814,
"s": 24521,
"text": "Magnific Popup is a fast, light, mobile-friendly and responsive lightbox and modal dialog jQuery plugin. It can be used to open inline HTML, ajax loaded content, image, form, iframe (YouTube video, Vimeo, Google Maps), and photo gallery. It has added animation effects using CSS3 transitions."
},
{
"code": null,
"e": 24887,
"s": 24814,
"text": "Installation Process: There are several ways to start using this plugin:"
},
{
"code": null,
"e": 24965,
"s": 24887,
"text": "Download the zipped folder of the latest version of Magnific Popup from here."
},
{
"code": null,
"e": 25142,
"s": 24965,
"text": "Alternatively, clone the Github Repository to any desired location by executing the following command in the Git Bash.git clone https://github.com/dimsemenov/Magnific-Popup.git"
},
{
"code": null,
"e": 25201,
"s": 25142,
"text": "git clone https://github.com/dimsemenov/Magnific-Popup.git"
},
{
"code": null,
"e": 25410,
"s": 25201,
"text": "Since the Magnific is a plugin of the jQuery framework, it needs to reference the jQuery library. This can be done by using the Google-hosted version of jQuery or downloading and using the distribution files."
},
{
"code": null,
"e": 25559,
"s": 25410,
"text": "Include CSS: Add the magnific-popup.css file from the dist folder of Magnific.<link rel=\"stylesheet\" type=\"text/css\" href=\"path/magnific-popup.css\">"
},
{
"code": "<link rel=\"stylesheet\" type=\"text/css\" href=\"path/magnific-popup.css\">",
"e": 25630,
"s": 25559,
"text": null
},
{
"code": null,
"e": 25806,
"s": 25630,
"text": "Include JavaScript: Add the jquery.magnific-popup.min.js file from the dist folder of Magnific.<script type=\"text/javascript\" src=\"path/jquery.magnific-popup.min.js\"></script>"
},
{
"code": "<script type=\"text/javascript\" src=\"path/jquery.magnific-popup.min.js\"></script>",
"e": 25887,
"s": 25806,
"text": null
},
{
"code": null,
"e": 25943,
"s": 25887,
"text": "Example 1: This example shows a popup using the plugin."
},
{
"code": null,
"e": 25948,
"s": 25943,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Include CSS of Magnific Popup --> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/magnific-popup.css\"></head> <body style=\"text-align:center;\"> <!-- Button to open popup --> <button> <a href=\"#popup-info\" class=\"open-popup\" style=\"text-decoration: none;\"> Click to Open PopUp </a> </button> <!-- Popup to display --> <div id=\"popup-info\" class=\"mfp-hide\" style= \"text-align:center; background:white;height:600px;\"> <h1 style=\"color: green;\"> GEEKSFORGEEKS </h1> <div style=\"font-size: 15px; font-weight: bold;\"> WELCOME TO GEEKSFORGEEKS </div> </div> <!-- Include jQuery --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!-- Include the Magnific Popup JavaScript --> <script type=\"text/javascript\" src=\"js/jquery.magnific-popup.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function ($) { $('.open-popup').magnificPopup({ type: 'inline', // Fixed position will be used fixContentPos: true, // Since disabled, Magnific Popup // will not put close button // inside content of popup closeBtnInside: false, preloader: false, // Delay in milliseconds before // popup is removed removalDelay: 160, // Class that is added to // popup wrapper and background mainClass: 'mfp-fade' }); }); </script></body> </html>",
"e": 27706,
"s": 25948,
"text": null
},
{
"code": null,
"e": 27715,
"s": 27706,
"text": "Output: "
},
{
"code": null,
"e": 27743,
"s": 27715,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 27770,
"s": 27743,
"text": "After clicking the button:"
},
{
"code": null,
"e": 27932,
"s": 27770,
"text": "Example 2: This example shows a popup with an image using the plugin. The gallery module allows us to switch the content of the popup and adds navigation arrows."
},
{
"code": null,
"e": 27937,
"s": 27932,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <!--Bootstrap CSS--> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\"> <!--Magnific Popup CSS--> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/magnific-popup.css\"></head> <body style=\"text-align:center;\"> <h1 style=\"color: blue;\"> :GALLERY: </h1> <!--Gallery--> <div class=\"container \"> <div class=\"row no-gutters gallery\" style=\"padding:0;\"> <!--Image 1--> <div class=\"col-lg-6 col-md-6 col-sm-6 col-12\"> <a href=\"images/gfg-logo.png\"> <img src=\"images/gfg-logo.png\" style=\"height:300px; width:100%;\"> </a> </div> <!--Image 2--> <div class=\"col-lg-6 col-md-6 col-sm-6 col-12\"> <a href=\"images/gfg-logo2.png\"> <img src=\"images/gfg-logo2.png\" style=\"height:300px; width:100%;\"> </a> </div> <!--Image 3--> <div class=\"col-lg-6 col-md-6 col-sm-6 col-12\"> <a href=\"images/gfg-promo.jpg\"> <img src=\"images/gfg-promo.jpg\" style=\"height:300px; width:100%;\"> </a> </div> <!--Image 4--> <div class=\"col-lg-6 col-md-6 col-sm-6 col-12\"> <a href=\"images/gfg-promo2.jpg\"> <img src=\"images/gfg-promo2.jpg\" style=\"height:300px; width:100%;\"> </a> </div> </div> </div> <!-- Optional JavaScript --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\"> </script> <!-- Magnific Popup JavaScript--> <script type=\"text/javascript\" src=\"js/jquery.magnific-popup.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function ($) { $('.gallery').magnificPopup({ type: 'image', // To invoke the popup // using the 'a' tag delegate: 'a', // Enable the gallery gallery: { enabled: true } }); }); </script></body> </html>",
"e": 30441,
"s": 27937,
"text": null
},
{
"code": null,
"e": 30450,
"s": 30441,
"text": "Output: "
},
{
"code": null,
"e": 30479,
"s": 30450,
"text": "Before clicking on an image:"
},
{
"code": null,
"e": 30508,
"s": 30479,
"text": "Before clicking on an image:"
},
{
"code": null,
"e": 30537,
"s": 30508,
"text": "After clicking on any image:"
},
{
"code": null,
"e": 30566,
"s": 30537,
"text": "After clicking on any image:"
},
{
"code": null,
"e": 30606,
"s": 30566,
"text": "Reference: Magnific Popup Documentation"
},
{
"code": null,
"e": 30743,
"s": 30606,
"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": 30752,
"s": 30743,
"text": "CSS-Misc"
},
{
"code": null,
"e": 30762,
"s": 30752,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30774,
"s": 30762,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 30778,
"s": 30774,
"text": "CSS"
},
{
"code": null,
"e": 30783,
"s": 30778,
"text": "HTML"
},
{
"code": null,
"e": 30790,
"s": 30783,
"text": "JQuery"
},
{
"code": null,
"e": 30807,
"s": 30790,
"text": "Web Technologies"
},
{
"code": null,
"e": 30834,
"s": 30807,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30839,
"s": 30834,
"text": "HTML"
},
{
"code": null,
"e": 30937,
"s": 30839,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30995,
"s": 30937,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31032,
"s": 30995,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31096,
"s": 31032,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 31137,
"s": 31096,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 31174,
"s": 31137,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 31234,
"s": 31174,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31295,
"s": 31234,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31348,
"s": 31295,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 31398,
"s": 31348,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
How to remove li elements on button click in JavaScript?
|
Let’s say the following is our Unordered List (ul) −
<ul>
<li class="subjectName">JavaScript <button>Remove</button></li>
<br>
<li class="subjectName">MySQL <button>Remove</button></li>
<br>
<li class="subjectName">MongoDB <button>Remove</button></li>
<br>
<li class="subjectName">Java <button>Remove</button></li>
</ul>
Above, you can see the “Remove” button with every li element. On clicking this button, you can
remove any li element.
Following is the code to remove li elements on button click;
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.
css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<h1>Remove the subjects</h1>
<h2>The Subjects are as follows:</h2>
<ul>
<li class="subjectName">JavaScript <button>Remove</button></li>
<br>
<li class="subjectName">MySQL <button>Remove</button></li>
<br>
<li class="subjectName">MongoDB <button>Remove</button></li>
<br>
<li class="subjectName">Java <button>Remove</button></li>
</ul>
<script>
var allSubjectName = document.querySelectorAll(".subjectName");
for (var index = 0; index <allSubjectName.length; index++){
allSubjectName[index].addEventListener("click", function(){
this.classList.toggle("active");
});
allSubjectName[index].querySelector("button").addEventListener("click",
function(){
this.closest(".subjectName").remove();
});
}
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Now, I am going to remove subject name “MySQL” and “MongoDB” from the list of subjects.
This will produce the following output after clicking the “Remove” button for subjects “MySQL”
and “MongoDB” −
|
[
{
"code": null,
"e": 1115,
"s": 1062,
"text": "Let’s say the following is our Unordered List (ul) −"
},
{
"code": null,
"e": 1404,
"s": 1115,
"text": "<ul>\n <li class=\"subjectName\">JavaScript <button>Remove</button></li>\n <br>\n <li class=\"subjectName\">MySQL <button>Remove</button></li>\n <br>\n <li class=\"subjectName\">MongoDB <button>Remove</button></li>\n <br>\n <li class=\"subjectName\">Java <button>Remove</button></li>\n</ul>"
},
{
"code": null,
"e": 1522,
"s": 1404,
"text": "Above, you can see the “Remove” button with every li element. On clicking this button, you can\nremove any li element."
},
{
"code": null,
"e": 1583,
"s": 1522,
"text": "Following is the code to remove li elements on button click;"
},
{
"code": null,
"e": 1594,
"s": 1583,
"text": " Live Demo"
},
{
"code": null,
"e": 3065,
"s": 1594,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.\ncss\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\"\ncrossorigin=\"anonymous\">\n</head>\n<body>\n<h1>Remove the subjects</h1>\n<h2>The Subjects are as follows:</h2>\n<ul>\n<li class=\"subjectName\">JavaScript <button>Remove</button></li>\n<br>\n<li class=\"subjectName\">MySQL <button>Remove</button></li>\n<br>\n<li class=\"subjectName\">MongoDB <button>Remove</button></li>\n<br>\n<li class=\"subjectName\">Java <button>Remove</button></li>\n</ul>\n<script>\n var allSubjectName = document.querySelectorAll(\".subjectName\");\n for (var index = 0; index <allSubjectName.length; index++){\n allSubjectName[index].addEventListener(\"click\", function(){\n this.classList.toggle(\"active\");\n });\n allSubjectName[index].querySelector(\"button\").addEventListener(\"click\",\n function(){\n this.closest(\".subjectName\").remove();\n });\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3227,
"s": 3065,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 3268,
"s": 3227,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3356,
"s": 3268,
"text": "Now, I am going to remove subject name “MySQL” and “MongoDB” from the list of subjects."
},
{
"code": null,
"e": 3467,
"s": 3356,
"text": "This will produce the following output after clicking the “Remove” button for subjects “MySQL”\nand “MongoDB” −"
}
] |
AVL Tree | Set 2 (Deletion) - GeeksforGeeks
|
11 Apr, 2022
We have discussed AVL insertion in the previous post. In this post, we will follow a similar approach for deletion.
Steps to follow for deletion. To make sure that the given tree remains AVL after every deletion, we must augment the standard BST delete operation to perform some re-balancing. Following are two basic operations that can be performed to re-balance a BST without violating the BST property (keys(left) < key(root) < keys(right)). 1) Left Rotation 2) Right Rotation
T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
or x (on right side)
y x
/ \ Right Rotation / \
x T3 – - – - – - – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3
Keys in both of the above trees follow the following order
keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)
So BST property is not violated anywhere.
Let w be the node to be deleted 1) Perform standard BST delete for w. 2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced node, y be the larger height child of z, and x be the larger height child of y. Note that the definitions of x and y are different from insertion here. 3) Re-balance the tree by performing appropriate rotations on the subtree rooted with z. There can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways. Following are the possible 4 arrangements: a) y is left child of z and x is left child of y (Left Left Case) b) y is left child of z and x is right child of y (Left Right Case) c) y is right child of z and x is right child of y (Right Right Case) d) y is right child of z and x is left child of y (Right Left Case)Like insertion, following are the operations to be performed in above mentioned 4 cases. Note that, unlike insertion, fixing the node z won’t fix the complete AVL tree. After fixing z, we may have to fix ancestors of z as well (See this video lecture for proof)
a) Left Left Case
T1, T2, T3 and T4 are subtrees.
z y
/ \ / \
y T4 Right Rotate (z) x z
/ \ - - - - - - - - -> / \ / \
x T3 T1 T2 T3 T4
/ \
T1 T2
b) Left Right Case
z z x
/ \ / \ / \
y T4 Left Rotate (y) x T4 Right Rotate(z) y z
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
T1 x y T3 T1 T2 T3 T4
/ \ / \
T2 T3 T1 T2
c) Right Right Case
z y
/ \ / \
T1 y Left Rotate(z) z x
/ \ - - - - - - - -> / \ / \
T2 x T1 T2 T3 T4
/ \
T3 T4
d) Right Left Case
z z x
/ \ / \ / \
T1 y Right Rotate (y) T1 x Left Rotate(z) z y
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
x T4 T2 y T1 T2 T3 T4
/ \ / \
T2 T3 T3 T4
Unlike insertion, in deletion, after we perform a rotation at z, we may have to perform a rotation at ancestors of z. Thus, we must continue to trace the path until we reach the root.
Example:
A node with value 32 is being deleted. After deleting 32, we travel up and find the first unbalanced node which is 44. We mark it as z, its higher height child as y which is 62, and y’s higher height child as x which could be either 78 or 50 as both are of same height. We have considered 78. Now the case is Right Right, so we perform left rotation.
C implementation Following is the C implementation for AVL Tree Deletion. The following C implementation uses the recursive BST delete as basis. In the recursive BST delete, after deletion, we get pointers to all ancestors one by one in bottom up manner. So we don’t need parent pointer to travel up. The recursive code itself travels up and visits all the ancestors of the deleted node. 1) Perform the normal BST deletion. 2) The current node must be one of the ancestors of the deleted node. Update the height of the current node. 3) Get the balance factor (left subtree height – right subtree height) of the current node. 4) If balance factor is greater than 1, then the current node is unbalanced and we are either in Left Left case or Left Right case. To check whether it is Left Left case or Left Right case, get the balance factor of left subtree. If balance factor of the left subtree is greater than or equal to 0, then it is Left Left case, else Left Right case. 5) If balance factor is less than -1, then the current node is unbalanced and we are either in Right Right case or Right Left case. To check whether it is Right Right case or Right Left case, get the balance factor of right subtree. If the balance factor of the right subtree is smaller than or equal to 0, then it is Right Right case, else Right Left case.
C++
C
Java
Python3
C#
Javascript
// C++ program to delete a node from AVL Tree#include<bits/stdc++.h>using namespace std; // An AVL tree nodeclass Node{ public: int key; Node *left; Node *right; int height;}; // A utility function to get maximum// of two integersint max(int a, int b); // A utility function to get height// of the treeint height(Node *N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum// of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */Node* newNode(int key){ Node* node = new Node(); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially // added at leaf return(node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.Node *rightRotate(Node *y){ Node *x = y->left; Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.Node *leftRotate(Node *x){ Node *y = x->right; Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} Node* insert(Node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree,return the node with minimum key valuefound in that tree. Note that the entiretree does not need to be searched. */Node * minValueNode(Node* node){ Node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} // Recursive function to delete a node// with given key from subtree with// given root. It returns root of the// modified subtree.Node* deleteNode(Node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller // than the root's key, then it lies // in left subtree if ( key < root->key ) root->left = deleteNode(root->left, key); // If the key to be deleted is greater // than the root's key, then it lies // in right subtree else if( key > root->key ) root->right = deleteNode(root->right, key); // if key is same as root's key, then // This is the node to be deleted else { // node with only one child or no child if( (root->left == NULL) || (root->right == NULL) ) { Node *temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of // the non-empty child free(temp); } else { // node with two children: Get the inorder // successor (smallest in the right subtree) Node* temp = minValueNode(root->right); // Copy the inorder successor's // data to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node // then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = 1 + max(height(root->left), height(root->right)); // STEP 3: GET THE BALANCE FACTOR OF // THIS NODE (to check whether this // node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder// traversal of the tree.// The function also prints height// of every nodevoid preOrder(Node *root){ if(root != NULL) { cout << root->key << " "; preOrder(root->left); preOrder(root->right); }} // Driver Codeint main(){Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 0); root = insert(root, 6); root = insert(root, 11); root = insert(root, -1); root = insert(root, 1); root = insert(root, 2); /* The constructed AVL Tree would be 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 */ cout << "Preorder traversal of the " "constructed AVL tree is \n"; preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \ 0 9 / / \ -1 5 11 / \ 2 6 */ cout << "\nPreorder traversal after" << " deletion of 10 \n"; preOrder(root); return 0;} // This code is contributed by rathbhupendra
// C program to delete a node from AVL Tree#include<stdio.h>#include<stdlib.h> // An AVL tree nodestruct Node{ int key; struct Node *left; struct Node *right; int height;}; // A utility function to get maximum of two integersint max(int a, int b); // A utility function to get height of the treeint height(struct Node *N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct Node* newNode(int key){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially added at leaf return(node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right))+1; x->height = max(height(x->left), height(x->right))+1; // Return new root return x;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right))+1; y->height = max(height(y->left), height(y->right))+1; // Return new root return y;} // Get Balance factor of node Nint getBalance(struct Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} struct Node* insert(struct Node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct Node * minValueNode(struct Node* node){ struct Node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} // Recursive function to delete a node with given key// from subtree with given root. It returns root of// the modified subtree.struct Node* deleteNode(struct Node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if ( key < root->key ) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the // root's key, then it lies in right subtree else if( key > root->key ) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is // the node to be deleted else { // node with only one child or no child if( (root->left == NULL) || (root->right == NULL) ) { struct Node *temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of // the non-empty child free(temp); } else { // node with two children: Get the inorder // successor (smallest in the right subtree) struct Node* temp = minValueNode(root->right); // Copy the inorder successor's data to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = 1 + max(height(root->left), height(root->right)); // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to // check whether this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder traversal of// the tree.// The function also prints height of every nodevoid preOrder(struct Node *root){ if(root != NULL) { printf("%d ", root->key); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 0); root = insert(root, 6); root = insert(root, 11); root = insert(root, -1); root = insert(root, 1); root = insert(root, 2); /* The constructed AVL Tree would be 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 */ printf("Preorder traversal of the constructed AVL " "tree is \n"); preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \ 0 9 / / \ -1 5 11 / \ 2 6 */ printf("\nPreorder traversal after deletion of 10 \n"); preOrder(root); return 0;}
// Java program for deletion in AVL Tree class Node{ int key, height; Node left, right; Node(int d) { key = d; height = 1; }} class AVLTree{ Node root; // A utility function to get height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST rotation */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became Wunbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ Node minValueNode(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } Node deleteNode(Node root, int key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than // the root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the // root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then this is the node // to be deleted else { // node with only one child or no child if ((root.left == null) || (root.right == null)) { Node temp = null; if (temp == root.left) temp = root.right; else temp = root.left; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of // the non-empty child } else { // node with two children: Get the inorder // successor (smallest in the right subtree) Node temp = minValueNode(root.right); // Copy the inorder successor's data to this node root.key = temp.key; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of // the tree. The function also prints height of every // node void preOrder(Node node) { if (node != null) { System.out.print(node.key + " "); preOrder(node.left); preOrder(node.right); } } public static void main(String[] args) { AVLTree tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 9); tree.root = tree.insert(tree.root, 5); tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 0); tree.root = tree.insert(tree.root, 6); tree.root = tree.insert(tree.root, 11); tree.root = tree.insert(tree.root, -1); tree.root = tree.insert(tree.root, 1); tree.root = tree.insert(tree.root, 2); /* The constructed AVL Tree would be 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 */ System.out.println("Preorder traversal of "+ "constructed tree is : "); tree.preOrder(tree.root); tree.root = tree.deleteNode(tree.root, 10); /* The AVL Tree after deletion of 10 1 / \ 0 9 / / \ -1 5 11 / \ 2 6 */ System.out.println(""); System.out.println("Preorder traversal after "+ "deletion of 10 :"); tree.preOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal
# Python code to delete a node in AVL tree# Generic tree node classclass TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None self.height = 1 # AVL tree class which supports insertion,# deletion operationsclass AVL_Tree(object): def insert(self, root, key): # Step 1 - Perform normal BST if not root: return TreeNode(key) elif key < root.val: root.left = self.insert(root.left, key) else: root.right = self.insert(root.right, key) # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and key < root.left.val: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and key > root.right.val: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and key > root.left.val: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and key < root.right.val: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root # Recursive function to delete a node with # given key from subtree with given root. # It returns root of the modified subtree. def delete(self, root, key): # Step 1 - Perform standard BST delete if not root: return root elif key < root.val: root.left = self.delete(root.left, key) elif key > root.val: root.right = self.delete(root.right, key) else: if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp temp = self.getMinValueNode(root.right) root.val = temp.val root.right = self.delete(root.right, temp.val) # If the tree has only one node, # simply return it if root is None: return root # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and self.getBalance(root.left) >= 0: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and self.getBalance(root.right) <= 0: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and self.getBalance(root.left) < 0: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and self.getBalance(root.right) > 0: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def leftRotate(self, z): y = z.right T2 = y.left # Perform rotation y.left = z z.right = T2 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def rightRotate(self, z): y = z.left T3 = y.right # Perform rotation y.right = z z.left = T3 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def getHeight(self, root): if not root: return 0 return root.height def getBalance(self, root): if not root: return 0 return self.getHeight(root.left) - self.getHeight(root.right) def getMinValueNode(self, root): if root is None or root.left is None: return root return self.getMinValueNode(root.left) def preOrder(self, root): if not root: return print("{0} ".format(root.val), end="") self.preOrder(root.left) self.preOrder(root.right) myTree = AVL_Tree()root = Nonenums = [9, 5, 10, 0, 6, 11, -1, 1, 2] for num in nums: root = myTree.insert(root, num) # Preorder Traversalprint("Preorder Traversal after insertion -")myTree.preOrder(root)print() # Deletekey = 10root = myTree.delete(root, key) # Preorder Traversalprint("Preorder Traversal after deletion -")myTree.preOrder(root)print() # This code is contributed by Ajitesh Pathak
// C# program for deletion in AVL Treeusing System; public class Node{ public int key, height; public Node left, right; public Node(int d) { key = d; height = 1; }} public class AVLTree{ Node root; // A utility function to get height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to // get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right // rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST rotation */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became Wunbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ Node minValueNode(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } Node deleteNode(Node root, int key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than // the root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the // root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then this is the node // to be deleted else { // node with only one child or no child if ((root.left == null) || (root.right == null)) { Node temp = null; if (temp == root.left) temp = root.right; else temp = root.left; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of // the non-empty child } else { // node with two children: Get the inorder // successor (smallest in the right subtree) Node temp = minValueNode(root.right); // Copy the inorder successor's data to this node root.key = temp.key; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR // OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of // the tree. The function also prints height of every // node void preOrder(Node node) { if (node != null) { Console.Write(node.key + " "); preOrder(node.left); preOrder(node.right); } } // Driver code public static void Main() { AVLTree tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 9); tree.root = tree.insert(tree.root, 5); tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 0); tree.root = tree.insert(tree.root, 6); tree.root = tree.insert(tree.root, 11); tree.root = tree.insert(tree.root, -1); tree.root = tree.insert(tree.root, 1); tree.root = tree.insert(tree.root, 2); /* The constructed AVL Tree would be 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 */ Console.WriteLine("Preorder traversal of "+ "constructed tree is : "); tree.preOrder(tree.root); tree.root = tree.deleteNode(tree.root, 10); /* The AVL Tree after deletion of 10 1 / \ 0 9 / / \ -1 5 11 / \ 2 6 */ Console.WriteLine(""); Console.WriteLine("Preorder traversal after "+ "deletion of 10 :"); tree.preOrder(tree.root); }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript program for deletion in AVL Tree class Node { constructor(d) { this.left = null; this.right = null; this.key = d; this.height = 1; } } let root; // A utility function to get height of the tree function height(N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers function max(a, b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. function rightRotate(y) { let x = y.left; let T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. function leftRotate(x) { let y = x.right; let T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N function getBalance(N) { if (N == null) return 0; return height(N.left) - height(N.right); } function insert(node, key) { /* 1. Perform the normal BST rotation */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became Wunbalanced */ let balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ function minValueNode(node) { let current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } function deleteNode(root, key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than // the root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the // root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then this is the node // to be deleted else { // node with only one child or no child if ((root.left == null) || (root.right == null)) { let temp = null; if (temp == root.left) temp = root.right; else temp = root.left; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of // the non-empty child } else { // node with two children: Get the inorder // successor (smallest in the right subtree) let temp = minValueNode(root.right); // Copy the inorder successor's data to this node root.key = temp.key; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) let balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of // the tree. The function also prints height of every // node function preOrder(node) { if (node != null) { document.write(node.key + " "); preOrder(node.left); preOrder(node.right); } } /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 0); root = insert(root, 6); root = insert(root, 11); root = insert(root, -1); root = insert(root, 1); root = insert(root, 2); /* The constructed AVL Tree would be 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 */ document.write( "Preorder traversal of the constructed AVL tree is : " + "</br>"); preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \ 0 9 / / \ -1 5 11 / \ 2 6 */ document.write("</br>"); document.write("Preorder traversal after "+ "deletion of 10 :" + "</br>"); preOrder(root); </script>
Output:
Preorder traversal of the constructed AVL tree is
9 1 0 -1 5 2 6 10 11
Preorder traversal after deletion of 10
1 0 -1 9 5 2 6 11
Time Complexity: The rotation operations (left and right rotate) take constant time as only few pointers are being changed there. Updating the height and getting the balance factor also take constant time. So the time complexity of AVL delete remains same as BST delete which is O(h) where h is height of the tree. Since AVL tree is balanced, the height is O(Logn). So time complexity of AVL delete is O(Log n).
Advantages Of AVL Trees
It is always height balanced
Height Never Goes Beyond LogN, where N is the number of nodes
It give better search than compared to binary search tree
It has self balancing capabilities
Summary of AVL Trees
These are self-balancing binary search trees.
Balancing Factor ranges -1, 0, and +1.
When balancing factor goes beyond the range require rotations to be performed
Insert, delete, and search time is O(log N).
AVL tree are mostly used where search is more frequent compared to insert and delete operations.
YouTubeGeeksforGeeks502K subscribersAVL Tree - Deletion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4zQV3j2X9mU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
&t=7s
References: https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap7b.pdf IITD Video Lecture on AVL Tree Insertion and DeletionPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AnkushRodewad
KP1975
princiraj1992
rathbhupendra
KickSam
arijitroy003
decode2207
krishnanand3
guptavivek0503
Amazon
AVL-Tree
MakeMyTrip
Morgan Stanley
Oracle
Oxigen Wallet
Self-Balancing-BST
Snapdeal
Advanced Data Structure
Tree
Morgan Stanley
Amazon
Snapdeal
MakeMyTrip
Oracle
Oxigen Wallet
Tree
AVL-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
Disjoint Set Data Structures
Insert Operation in B-Tree
Segment Tree | Set 1 (Sum of given range)
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Inorder Tree Traversal without Recursion
Write a Program to Find the Maximum Depth or Height of a Tree
|
[
{
"code": null,
"e": 24788,
"s": 24760,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 24904,
"s": 24788,
"text": "We have discussed AVL insertion in the previous post. In this post, we will follow a similar approach for deletion."
},
{
"code": null,
"e": 25269,
"s": 24904,
"text": "Steps to follow for deletion. To make sure that the given tree remains AVL after every deletion, we must augment the standard BST delete operation to perform some re-balancing. Following are two basic operations that can be performed to re-balance a BST without violating the BST property (keys(left) < key(root) < keys(right)). 1) Left Rotation 2) Right Rotation "
},
{
"code": null,
"e": 25778,
"s": 25269,
"text": "T1, T2 and T3 are subtrees of the tree rooted with y (on left side)\nor x (on right side)\n y x\n / \\ Right Rotation / \\\n x T3 – - – - – - – > T1 y\n / \\ < - - - - - - - / \\\n T1 T2 Left Rotation T2 T3\nKeys in both of the above trees follow the following order\n keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)\nSo BST property is not violated anywhere."
},
{
"code": null,
"e": 26857,
"s": 25778,
"text": "Let w be the node to be deleted 1) Perform standard BST delete for w. 2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced node, y be the larger height child of z, and x be the larger height child of y. Note that the definitions of x and y are different from insertion here. 3) Re-balance the tree by performing appropriate rotations on the subtree rooted with z. There can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways. Following are the possible 4 arrangements: a) y is left child of z and x is left child of y (Left Left Case) b) y is left child of z and x is right child of y (Left Right Case) c) y is right child of z and x is right child of y (Right Right Case) d) y is right child of z and x is left child of y (Right Left Case)Like insertion, following are the operations to be performed in above mentioned 4 cases. Note that, unlike insertion, fixing the node z won’t fix the complete AVL tree. After fixing z, we may have to fix ancestors of z as well (See this video lecture for proof)"
},
{
"code": null,
"e": 26876,
"s": 26857,
"text": "a) Left Left Case "
},
{
"code": null,
"e": 27197,
"s": 26876,
"text": "T1, T2, T3 and T4 are subtrees.\n z y \n / \\ / \\\n y T4 Right Rotate (z) x z\n / \\ - - - - - - - - -> / \\ / \\ \n x T3 T1 T2 T3 T4\n / \\\n T1 T2"
},
{
"code": null,
"e": 27217,
"s": 27197,
"text": "b) Left Right Case "
},
{
"code": null,
"e": 27642,
"s": 27217,
"text": " z z x\n / \\ / \\ / \\ \n y T4 Left Rotate (y) x T4 Right Rotate(z) y z\n / \\ - - - - - - - - -> / \\ - - - - - - - -> / \\ / \\\nT1 x y T3 T1 T2 T3 T4\n / \\ / \\\n T2 T3 T1 T2"
},
{
"code": null,
"e": 27663,
"s": 27642,
"text": "c) Right Right Case "
},
{
"code": null,
"e": 27890,
"s": 27663,
"text": " z y\n / \\ / \\ \nT1 y Left Rotate(z) z x\n / \\ - - - - - - - -> / \\ / \\\n T2 x T1 T2 T3 T4\n / \\\n T3 T4"
},
{
"code": null,
"e": 27910,
"s": 27890,
"text": "d) Right Left Case "
},
{
"code": null,
"e": 28326,
"s": 27910,
"text": " z z x\n / \\ / \\ / \\ \nT1 y Right Rotate (y) T1 x Left Rotate(z) z y\n / \\ - - - - - - - - -> / \\ - - - - - - - -> / \\ / \\\n x T4 T2 y T1 T2 T3 T4\n / \\ / \\\nT2 T3 T3 T4"
},
{
"code": null,
"e": 28510,
"s": 28326,
"text": "Unlike insertion, in deletion, after we perform a rotation at z, we may have to perform a rotation at ancestors of z. Thus, we must continue to trace the path until we reach the root."
},
{
"code": null,
"e": 28521,
"s": 28510,
"text": "Example: "
},
{
"code": null,
"e": 28872,
"s": 28521,
"text": "A node with value 32 is being deleted. After deleting 32, we travel up and find the first unbalanced node which is 44. We mark it as z, its higher height child as y which is 62, and y’s higher height child as x which could be either 78 or 50 as both are of same height. We have considered 78. Now the case is Right Right, so we perform left rotation."
},
{
"code": null,
"e": 30203,
"s": 28872,
"text": "C implementation Following is the C implementation for AVL Tree Deletion. The following C implementation uses the recursive BST delete as basis. In the recursive BST delete, after deletion, we get pointers to all ancestors one by one in bottom up manner. So we don’t need parent pointer to travel up. The recursive code itself travels up and visits all the ancestors of the deleted node. 1) Perform the normal BST deletion. 2) The current node must be one of the ancestors of the deleted node. Update the height of the current node. 3) Get the balance factor (left subtree height – right subtree height) of the current node. 4) If balance factor is greater than 1, then the current node is unbalanced and we are either in Left Left case or Left Right case. To check whether it is Left Left case or Left Right case, get the balance factor of left subtree. If balance factor of the left subtree is greater than or equal to 0, then it is Left Left case, else Left Right case. 5) If balance factor is less than -1, then the current node is unbalanced and we are either in Right Right case or Right Left case. To check whether it is Right Right case or Right Left case, get the balance factor of right subtree. If the balance factor of the right subtree is smaller than or equal to 0, then it is Right Right case, else Right Left case."
},
{
"code": null,
"e": 30207,
"s": 30203,
"text": "C++"
},
{
"code": null,
"e": 30209,
"s": 30207,
"text": "C"
},
{
"code": null,
"e": 30214,
"s": 30209,
"text": "Java"
},
{
"code": null,
"e": 30222,
"s": 30214,
"text": "Python3"
},
{
"code": null,
"e": 30225,
"s": 30222,
"text": "C#"
},
{
"code": null,
"e": 30236,
"s": 30225,
"text": "Javascript"
},
{
"code": "// C++ program to delete a node from AVL Tree#include<bits/stdc++.h>using namespace std; // An AVL tree nodeclass Node{ public: int key; Node *left; Node *right; int height;}; // A utility function to get maximum// of two integersint max(int a, int b); // A utility function to get height// of the treeint height(Node *N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum// of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */Node* newNode(int key){ Node* node = new Node(); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially // added at leaf return(node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.Node *rightRotate(Node *y){ Node *x = y->left; Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.Node *leftRotate(Node *x){ Node *y = x->right; Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} Node* insert(Node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree,return the node with minimum key valuefound in that tree. Note that the entiretree does not need to be searched. */Node * minValueNode(Node* node){ Node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} // Recursive function to delete a node// with given key from subtree with// given root. It returns root of the// modified subtree.Node* deleteNode(Node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller // than the root's key, then it lies // in left subtree if ( key < root->key ) root->left = deleteNode(root->left, key); // If the key to be deleted is greater // than the root's key, then it lies // in right subtree else if( key > root->key ) root->right = deleteNode(root->right, key); // if key is same as root's key, then // This is the node to be deleted else { // node with only one child or no child if( (root->left == NULL) || (root->right == NULL) ) { Node *temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of // the non-empty child free(temp); } else { // node with two children: Get the inorder // successor (smallest in the right subtree) Node* temp = minValueNode(root->right); // Copy the inorder successor's // data to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node // then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = 1 + max(height(root->left), height(root->right)); // STEP 3: GET THE BALANCE FACTOR OF // THIS NODE (to check whether this // node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder// traversal of the tree.// The function also prints height// of every nodevoid preOrder(Node *root){ if(root != NULL) { cout << root->key << \" \"; preOrder(root->left); preOrder(root->right); }} // Driver Codeint main(){Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 0); root = insert(root, 6); root = insert(root, 11); root = insert(root, -1); root = insert(root, 1); root = insert(root, 2); /* The constructed AVL Tree would be 9 / \\ 1 10 / \\ \\ 0 5 11 / / \\ -1 2 6 */ cout << \"Preorder traversal of the \" \"constructed AVL tree is \\n\"; preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \\ 0 9 / / \\ -1 5 11 / \\ 2 6 */ cout << \"\\nPreorder traversal after\" << \" deletion of 10 \\n\"; preOrder(root); return 0;} // This code is contributed by rathbhupendra",
"e": 37594,
"s": 30236,
"text": null
},
{
"code": "// C program to delete a node from AVL Tree#include<stdio.h>#include<stdlib.h> // An AVL tree nodestruct Node{ int key; struct Node *left; struct Node *right; int height;}; // A utility function to get maximum of two integersint max(int a, int b); // A utility function to get height of the treeint height(struct Node *N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct Node* newNode(int key){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially added at leaf return(node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right))+1; x->height = max(height(x->left), height(x->right))+1; // Return new root return x;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right))+1; y->height = max(height(y->left), height(y->right))+1; // Return new root return y;} // Get Balance factor of node Nint getBalance(struct Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} struct Node* insert(struct Node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct Node * minValueNode(struct Node* node){ struct Node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} // Recursive function to delete a node with given key// from subtree with given root. It returns root of// the modified subtree.struct Node* deleteNode(struct Node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if ( key < root->key ) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the // root's key, then it lies in right subtree else if( key > root->key ) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is // the node to be deleted else { // node with only one child or no child if( (root->left == NULL) || (root->right == NULL) ) { struct Node *temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of // the non-empty child free(temp); } else { // node with two children: Get the inorder // successor (smallest in the right subtree) struct Node* temp = minValueNode(root->right); // Copy the inorder successor's data to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = 1 + max(height(root->left), height(root->right)); // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to // check whether this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder traversal of// the tree.// The function also prints height of every nodevoid preOrder(struct Node *root){ if(root != NULL) { printf(\"%d \", root->key); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 0); root = insert(root, 6); root = insert(root, 11); root = insert(root, -1); root = insert(root, 1); root = insert(root, 2); /* The constructed AVL Tree would be 9 / \\ 1 10 / \\ \\ 0 5 11 / / \\ -1 2 6 */ printf(\"Preorder traversal of the constructed AVL \" \"tree is \\n\"); preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \\ 0 9 / / \\ -1 5 11 / \\ 2 6 */ printf(\"\\nPreorder traversal after deletion of 10 \\n\"); preOrder(root); return 0;}",
"e": 44954,
"s": 37594,
"text": null
},
{
"code": "// Java program for deletion in AVL Tree class Node{ int key, height; Node left, right; Node(int d) { key = d; height = 1; }} class AVLTree{ Node root; // A utility function to get height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST rotation */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became Wunbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ Node minValueNode(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } Node deleteNode(Node root, int key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than // the root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the // root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then this is the node // to be deleted else { // node with only one child or no child if ((root.left == null) || (root.right == null)) { Node temp = null; if (temp == root.left) temp = root.right; else temp = root.left; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of // the non-empty child } else { // node with two children: Get the inorder // successor (smallest in the right subtree) Node temp = minValueNode(root.right); // Copy the inorder successor's data to this node root.key = temp.key; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of // the tree. The function also prints height of every // node void preOrder(Node node) { if (node != null) { System.out.print(node.key + \" \"); preOrder(node.left); preOrder(node.right); } } public static void main(String[] args) { AVLTree tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 9); tree.root = tree.insert(tree.root, 5); tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 0); tree.root = tree.insert(tree.root, 6); tree.root = tree.insert(tree.root, 11); tree.root = tree.insert(tree.root, -1); tree.root = tree.insert(tree.root, 1); tree.root = tree.insert(tree.root, 2); /* The constructed AVL Tree would be 9 / \\ 1 10 / \\ \\ 0 5 11 / / \\ -1 2 6 */ System.out.println(\"Preorder traversal of \"+ \"constructed tree is : \"); tree.preOrder(tree.root); tree.root = tree.deleteNode(tree.root, 10); /* The AVL Tree after deletion of 10 1 / \\ 0 9 / / \\ -1 5 11 / \\ 2 6 */ System.out.println(\"\"); System.out.println(\"Preorder traversal after \"+ \"deletion of 10 :\"); tree.preOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal",
"e": 52558,
"s": 44954,
"text": null
},
{
"code": "# Python code to delete a node in AVL tree# Generic tree node classclass TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None self.height = 1 # AVL tree class which supports insertion,# deletion operationsclass AVL_Tree(object): def insert(self, root, key): # Step 1 - Perform normal BST if not root: return TreeNode(key) elif key < root.val: root.left = self.insert(root.left, key) else: root.right = self.insert(root.right, key) # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and key < root.left.val: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and key > root.right.val: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and key > root.left.val: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and key < root.right.val: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root # Recursive function to delete a node with # given key from subtree with given root. # It returns root of the modified subtree. def delete(self, root, key): # Step 1 - Perform standard BST delete if not root: return root elif key < root.val: root.left = self.delete(root.left, key) elif key > root.val: root.right = self.delete(root.right, key) else: if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp temp = self.getMinValueNode(root.right) root.val = temp.val root.right = self.delete(root.right, temp.val) # If the tree has only one node, # simply return it if root is None: return root # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and self.getBalance(root.left) >= 0: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and self.getBalance(root.right) <= 0: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and self.getBalance(root.left) < 0: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and self.getBalance(root.right) > 0: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def leftRotate(self, z): y = z.right T2 = y.left # Perform rotation y.left = z z.right = T2 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def rightRotate(self, z): y = z.left T3 = y.right # Perform rotation y.right = z z.left = T3 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def getHeight(self, root): if not root: return 0 return root.height def getBalance(self, root): if not root: return 0 return self.getHeight(root.left) - self.getHeight(root.right) def getMinValueNode(self, root): if root is None or root.left is None: return root return self.getMinValueNode(root.left) def preOrder(self, root): if not root: return print(\"{0} \".format(root.val), end=\"\") self.preOrder(root.left) self.preOrder(root.right) myTree = AVL_Tree()root = Nonenums = [9, 5, 10, 0, 6, 11, -1, 1, 2] for num in nums: root = myTree.insert(root, num) # Preorder Traversalprint(\"Preorder Traversal after insertion -\")myTree.preOrder(root)print() # Deletekey = 10root = myTree.delete(root, key) # Preorder Traversalprint(\"Preorder Traversal after deletion -\")myTree.preOrder(root)print() # This code is contributed by Ajitesh Pathak",
"e": 57800,
"s": 52558,
"text": null
},
{
"code": "// C# program for deletion in AVL Treeusing System; public class Node{ public int key, height; public Node left, right; public Node(int d) { key = d; height = 1; }} public class AVLTree{ Node root; // A utility function to get height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to // get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right // rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST rotation */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became Wunbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ Node minValueNode(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } Node deleteNode(Node root, int key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than // the root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the // root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then this is the node // to be deleted else { // node with only one child or no child if ((root.left == null) || (root.right == null)) { Node temp = null; if (temp == root.left) temp = root.right; else temp = root.left; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of // the non-empty child } else { // node with two children: Get the inorder // successor (smallest in the right subtree) Node temp = minValueNode(root.right); // Copy the inorder successor's data to this node root.key = temp.key; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR // OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of // the tree. The function also prints height of every // node void preOrder(Node node) { if (node != null) { Console.Write(node.key + \" \"); preOrder(node.left); preOrder(node.right); } } // Driver code public static void Main() { AVLTree tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 9); tree.root = tree.insert(tree.root, 5); tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 0); tree.root = tree.insert(tree.root, 6); tree.root = tree.insert(tree.root, 11); tree.root = tree.insert(tree.root, -1); tree.root = tree.insert(tree.root, 1); tree.root = tree.insert(tree.root, 2); /* The constructed AVL Tree would be 9 / \\ 1 10 / \\ \\ 0 5 11 / / \\ -1 2 6 */ Console.WriteLine(\"Preorder traversal of \"+ \"constructed tree is : \"); tree.preOrder(tree.root); tree.root = tree.deleteNode(tree.root, 10); /* The AVL Tree after deletion of 10 1 / \\ 0 9 / / \\ -1 5 11 / \\ 2 6 */ Console.WriteLine(\"\"); Console.WriteLine(\"Preorder traversal after \"+ \"deletion of 10 :\"); tree.preOrder(tree.root); }} /* This code contributed by PrinciRaj1992 */",
"e": 65499,
"s": 57800,
"text": null
},
{
"code": "<script> // JavaScript program for deletion in AVL Tree class Node { constructor(d) { this.left = null; this.right = null; this.key = d; this.height = 1; } } let root; // A utility function to get height of the tree function height(N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers function max(a, b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. function rightRotate(y) { let x = y.left; let T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. function leftRotate(x) { let y = x.right; let T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N function getBalance(N) { if (N == null) return 0; return height(N.left) - height(N.right); } function insert(node, key) { /* 1. Perform the normal BST rotation */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became Wunbalanced */ let balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ function minValueNode(node) { let current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } function deleteNode(root, key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than // the root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the // root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then this is the node // to be deleted else { // node with only one child or no child if ((root.left == null) || (root.right == null)) { let temp = null; if (temp == root.left) temp = root.right; else temp = root.left; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of // the non-empty child } else { // node with two children: Get the inorder // successor (smallest in the right subtree) let temp = minValueNode(root.right); // Copy the inorder successor's data to this node root.key = temp.key; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) let balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of // the tree. The function also prints height of every // node function preOrder(node) { if (node != null) { document.write(node.key + \" \"); preOrder(node.left); preOrder(node.right); } } /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 0); root = insert(root, 6); root = insert(root, 11); root = insert(root, -1); root = insert(root, 1); root = insert(root, 2); /* The constructed AVL Tree would be 9 / \\ 1 10 / \\ \\ 0 5 11 / / \\ -1 2 6 */ document.write( \"Preorder traversal of the constructed AVL tree is : \" + \"</br>\"); preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \\ 0 9 / / \\ -1 5 11 / \\ 2 6 */ document.write(\"</br>\"); document.write(\"Preorder traversal after \"+ \"deletion of 10 :\" + \"</br>\"); preOrder(root); </script>",
"e": 72889,
"s": 65499,
"text": null
},
{
"code": null,
"e": 72899,
"s": 72889,
"text": "Output: "
},
{
"code": null,
"e": 73032,
"s": 72899,
"text": "Preorder traversal of the constructed AVL tree is \n9 1 0 -1 5 2 6 10 11 \nPreorder traversal after deletion of 10 \n1 0 -1 9 5 2 6 11 "
},
{
"code": null,
"e": 73445,
"s": 73032,
"text": "Time Complexity: The rotation operations (left and right rotate) take constant time as only few pointers are being changed there. Updating the height and getting the balance factor also take constant time. So the time complexity of AVL delete remains same as BST delete which is O(h) where h is height of the tree. Since AVL tree is balanced, the height is O(Logn). So time complexity of AVL delete is O(Log n). "
},
{
"code": null,
"e": 73469,
"s": 73445,
"text": "Advantages Of AVL Trees"
},
{
"code": null,
"e": 73498,
"s": 73469,
"text": "It is always height balanced"
},
{
"code": null,
"e": 73560,
"s": 73498,
"text": "Height Never Goes Beyond LogN, where N is the number of nodes"
},
{
"code": null,
"e": 73618,
"s": 73560,
"text": "It give better search than compared to binary search tree"
},
{
"code": null,
"e": 73653,
"s": 73618,
"text": "It has self balancing capabilities"
},
{
"code": null,
"e": 73674,
"s": 73653,
"text": "Summary of AVL Trees"
},
{
"code": null,
"e": 73720,
"s": 73674,
"text": "These are self-balancing binary search trees."
},
{
"code": null,
"e": 73759,
"s": 73720,
"text": "Balancing Factor ranges -1, 0, and +1."
},
{
"code": null,
"e": 73837,
"s": 73759,
"text": "When balancing factor goes beyond the range require rotations to be performed"
},
{
"code": null,
"e": 73882,
"s": 73837,
"text": "Insert, delete, and search time is O(log N)."
},
{
"code": null,
"e": 73979,
"s": 73882,
"text": "AVL tree are mostly used where search is more frequent compared to insert and delete operations."
},
{
"code": null,
"e": 74797,
"s": 73979,
"text": "YouTubeGeeksforGeeks502K subscribersAVL Tree - Deletion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4zQV3j2X9mU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 74804,
"s": 74797,
"text": "&t=7s "
},
{
"code": null,
"e": 75055,
"s": 74804,
"text": "References: https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap7b.pdf IITD Video Lecture on AVL Tree Insertion and DeletionPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 75071,
"s": 75057,
"text": "AnkushRodewad"
},
{
"code": null,
"e": 75078,
"s": 75071,
"text": "KP1975"
},
{
"code": null,
"e": 75092,
"s": 75078,
"text": "princiraj1992"
},
{
"code": null,
"e": 75106,
"s": 75092,
"text": "rathbhupendra"
},
{
"code": null,
"e": 75114,
"s": 75106,
"text": "KickSam"
},
{
"code": null,
"e": 75127,
"s": 75114,
"text": "arijitroy003"
},
{
"code": null,
"e": 75138,
"s": 75127,
"text": "decode2207"
},
{
"code": null,
"e": 75151,
"s": 75138,
"text": "krishnanand3"
},
{
"code": null,
"e": 75166,
"s": 75151,
"text": "guptavivek0503"
},
{
"code": null,
"e": 75173,
"s": 75166,
"text": "Amazon"
},
{
"code": null,
"e": 75182,
"s": 75173,
"text": "AVL-Tree"
},
{
"code": null,
"e": 75193,
"s": 75182,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 75208,
"s": 75193,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 75215,
"s": 75208,
"text": "Oracle"
},
{
"code": null,
"e": 75229,
"s": 75215,
"text": "Oxigen Wallet"
},
{
"code": null,
"e": 75248,
"s": 75229,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 75257,
"s": 75248,
"text": "Snapdeal"
},
{
"code": null,
"e": 75281,
"s": 75257,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 75286,
"s": 75281,
"text": "Tree"
},
{
"code": null,
"e": 75301,
"s": 75286,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 75308,
"s": 75301,
"text": "Amazon"
},
{
"code": null,
"e": 75317,
"s": 75308,
"text": "Snapdeal"
},
{
"code": null,
"e": 75328,
"s": 75317,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 75335,
"s": 75328,
"text": "Oracle"
},
{
"code": null,
"e": 75349,
"s": 75335,
"text": "Oxigen Wallet"
},
{
"code": null,
"e": 75354,
"s": 75349,
"text": "Tree"
},
{
"code": null,
"e": 75363,
"s": 75354,
"text": "AVL-Tree"
},
{
"code": null,
"e": 75461,
"s": 75363,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 75495,
"s": 75461,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 75535,
"s": 75495,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 75564,
"s": 75535,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 75591,
"s": 75564,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 75633,
"s": 75591,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 75683,
"s": 75633,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 75718,
"s": 75683,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 75752,
"s": 75718,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 75793,
"s": 75752,
"text": "Inorder Tree Traversal without Recursion"
}
] |
What are immediate functions in JavaScript?
|
The immediate function executes as soon as it is defined. To understand the role of immediate function, let’s see the difference between a function and an immediate function −
Here’s immediate function −
(function() {
var str = "display";
}());
function display() {
// this returns undefined
alert(str);
}
Here’s a function −
var str = "display";
function display() {
// This returns "display"
alert(str);
}
Let’s see another example of immediate functions −
var name = 'Amit';
(function(sName) {
alert( 'Student name = ' + sName );
}(sName))
|
[
{
"code": null,
"e": 1238,
"s": 1062,
"text": "The immediate function executes as soon as it is defined. To understand the role of immediate function, let’s see the difference between a function and an immediate function −"
},
{
"code": null,
"e": 1266,
"s": 1238,
"text": "Here’s immediate function −"
},
{
"code": null,
"e": 1377,
"s": 1266,
"text": "(function() {\n var str = \"display\";\n}());\nfunction display() {\n // this returns undefined\n alert(str);\n}"
},
{
"code": null,
"e": 1397,
"s": 1377,
"text": "Here’s a function −"
},
{
"code": null,
"e": 1485,
"s": 1397,
"text": "var str = \"display\";\nfunction display() {\n // This returns \"display\"\n alert(str);\n}"
},
{
"code": null,
"e": 1536,
"s": 1485,
"text": "Let’s see another example of immediate functions −"
},
{
"code": null,
"e": 1623,
"s": 1536,
"text": "var name = 'Amit';\n(function(sName) {\n alert( 'Student name = ' + sName );\n}(sName))"
}
] |
JQuery deferred.resolve() method - GeeksforGeeks
|
14 Jul, 2020
This deferred.resolve() method in JQuery is used to resolve a Deferred object and call any doneCallbacks with the given arguments.Syntax:
deferred.resolve([args])
Parameters:
args: This is optional parameters and is arguments which are passed to the doneCallbacks.
Return Value: This method returns the deferred object.
There are two examples discussed below:
Example: In this example, The resolve() is called with the arguments.<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.resolve() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery | deferred.resolve() method"; function Func(val, div){ $(div).append(val); } function Geeks() { var def = $.Deferred(); def.done(Func); def.resolve('resolve() method is called with arguments and Deferred object is resolved', '#GFG_DOWN') } </script> </body> </html>
<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.resolve() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery | deferred.resolve() method"; function Func(val, div){ $(div).append(val); } function Geeks() { var def = $.Deferred(); def.done(Func); def.resolve('resolve() method is called with arguments and Deferred object is resolved', '#GFG_DOWN') } </script> </body> </html>
Output:
Example: In this example, The resolve() is called without arguments.<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.resolve() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery | deferred.resolve() method"; function Func(){ $('#GFG_DOWN').append("resolve() method is called without arguments and Deferred object is resolved"); } function Geeks() { var def = $.Deferred(); def.done(Func); def.resolve() } </script> </body> </html>
Example: In this example, The resolve() is called without arguments.
<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.resolve() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery | deferred.resolve() method"; function Func(){ $('#GFG_DOWN').append("resolve() method is called without arguments and Deferred object is resolved"); } function Geeks() { var def = $.Deferred(); def.done(Func); def.resolve() } </script> </body> </html>
Output:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference Between JavaScript and jQuery
How to use Anchor tag as submit button ?
jQuery | ajax() Method
How to scroll to specific element using jQuery ?
How to get form data using JavaScript/jQuery?
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
|
[
{
"code": null,
"e": 25364,
"s": 25336,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 25502,
"s": 25364,
"text": "This deferred.resolve() method in JQuery is used to resolve a Deferred object and call any doneCallbacks with the given arguments.Syntax:"
},
{
"code": null,
"e": 25528,
"s": 25502,
"text": "deferred.resolve([args])\n"
},
{
"code": null,
"e": 25540,
"s": 25528,
"text": "Parameters:"
},
{
"code": null,
"e": 25630,
"s": 25540,
"text": "args: This is optional parameters and is arguments which are passed to the doneCallbacks."
},
{
"code": null,
"e": 25685,
"s": 25630,
"text": "Return Value: This method returns the deferred object."
},
{
"code": null,
"e": 25725,
"s": 25685,
"text": "There are two examples discussed below:"
},
{
"code": null,
"e": 26653,
"s": 25725,
"text": "Example: In this example, The resolve() is called with the arguments.<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.resolve() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery | deferred.resolve() method\"; function Func(val, div){ $(div).append(val); } function Geeks() { var def = $.Deferred(); def.done(Func); def.resolve('resolve() method is called with arguments and Deferred object is resolved', '#GFG_DOWN') } </script> </body> </html> "
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.resolve() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery | deferred.resolve() method\"; function Func(val, div){ $(div).append(val); } function Geeks() { var def = $.Deferred(); def.done(Func); def.resolve('resolve() method is called with arguments and Deferred object is resolved', '#GFG_DOWN') } </script> </body> </html> ",
"e": 27512,
"s": 26653,
"text": null
},
{
"code": null,
"e": 27520,
"s": 27512,
"text": "Output:"
},
{
"code": null,
"e": 28419,
"s": 27520,
"text": "Example: In this example, The resolve() is called without arguments.<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.resolve() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery | deferred.resolve() method\"; function Func(){ $('#GFG_DOWN').append(\"resolve() method is called without arguments and Deferred object is resolved\"); } function Geeks() { var def = $.Deferred(); def.done(Func); def.resolve() } </script> </body> </html>"
},
{
"code": null,
"e": 28488,
"s": 28419,
"text": "Example: In this example, The resolve() is called without arguments."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.resolve() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery | deferred.resolve() method\"; function Func(){ $('#GFG_DOWN').append(\"resolve() method is called without arguments and Deferred object is resolved\"); } function Geeks() { var def = $.Deferred(); def.done(Func); def.resolve() } </script> </body> </html>",
"e": 29319,
"s": 28488,
"text": null
},
{
"code": null,
"e": 29327,
"s": 29319,
"text": "Output:"
},
{
"code": null,
"e": 29342,
"s": 29327,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 29349,
"s": 29342,
"text": "JQuery"
},
{
"code": null,
"e": 29366,
"s": 29349,
"text": "Web Technologies"
},
{
"code": null,
"e": 29464,
"s": 29366,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29473,
"s": 29464,
"text": "Comments"
},
{
"code": null,
"e": 29486,
"s": 29473,
"text": "Old Comments"
},
{
"code": null,
"e": 29527,
"s": 29486,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 29568,
"s": 29527,
"text": "How to use Anchor tag as submit button ?"
},
{
"code": null,
"e": 29591,
"s": 29568,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 29640,
"s": 29591,
"text": "How to scroll to specific element using jQuery ?"
},
{
"code": null,
"e": 29686,
"s": 29640,
"text": "How to get form data using JavaScript/jQuery?"
},
{
"code": null,
"e": 29723,
"s": 29686,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 29756,
"s": 29723,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29817,
"s": 29756,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29889,
"s": 29817,
"text": "Differences between Functional Components and Class Components in React"
}
] |
log4j - Logging in Database
|
The log4j API provides the org.apache.log4j.jdbc.JDBCAppender object, which can put logging information in a specified database.
Before you start using JDBC based logging, you should create a table to maintain all the log information. Following is the SQL Statement for creating the LOGS table −
CREATE TABLE LOGS
(USER_ID VARCHAR(20) NOT NULL,
DATED DATE NOT NULL,
LOGGER VARCHAR(50) NOT NULL,
LEVEL VARCHAR(10) NOT NULL,
MESSAGE VARCHAR(1000) NOT NULL
);
Following is a sample configuration file log4j.properties for JDBCAppender which will is be used to log messages to a LOGS table.
# Define the root logger with appender file
log4j.rootLogger = DEBUG, DB
# Define the DB appender
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
# Set JDBC URL
log4j.appender.DB.URL=jdbc:mysql://localhost/DBNAME
# Set Database Driver
log4j.appender.DB.driver=com.mysql.jdbc.Driver
# Set database user name and password
log4j.appender.DB.user=user_name
log4j.appender.DB.password=password
# Set the SQL statement to be executed.
log4j.appender.DB.sql=INSERT INTO LOGS VALUES('%x','%d','%C','%p','%m')
# Define the layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
For MySQL database, you would have to use the actual DBNAME, user ID and password, where you have created LOGS table. The SQL statement is to execute an INSERT statement with the table name LOGS and the values to be entered into the table.
JDBCAppender does not need a layout to be defined explicitly. Instead, the SQL statement passed to it uses a PatternLayout.
If you wish to have an XML configuration file equivalent to the above log4j.properties file, then here is the content −
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
<appender name="DB" class="org.apache.log4j.jdbc.JDBCAppender">
<param name="url" value="jdbc:mysql://localhost/DBNAME"/>
<param name="driver" value="com.mysql.jdbc.Driver"/>
<param name="user" value="user_id"/>
<param name="password" value="password"/>
<param name="sql" value="INSERT INTO LOGS VALUES('%x','%d','%C','%p','%m')"/>
<layout class="org.apache.log4j.PatternLayout">
</layout>
</appender>
<logger name="log4j.rootLogger" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="DB"/>
</logger>
</log4j:configuration>
The following Java class is a very simple example that initializes and then uses the Log4J logging library for Java applications.
import org.apache.log4j.Logger;
import java.sql.*;
import java.io.*;
import java.util.*;
public class log4jExample{
/* Get actual class name to be printed on */
static Logger log = Logger.getLogger(log4jExample.class.getName());
public static void main(String[] args)throws IOException,SQLException{
log.debug("Debug");
log.info("Info");
}
}
Here are the steps to compile and run the above-mentioned program. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. Follow the given steps −
Create log4j.properties as shown above.
Create log4jExample.java as shown above and compile it.
Execute log4jExample binary to run the program.
Now check your LOGS table inside DBNAME database and you would find the following entries −
mysql > select * from LOGS;
+---------+------------+--------------+-------+---------+
| USER_ID | DATED | LOGGER | LEVEL | MESSAGE |
+---------+------------+--------------+-------+---------+
| | 2010-05-13 | log4jExample | DEBUG | Debug |
| | 2010-05-13 | log4jExample | INFO | Info |
+---------+------------+--------------+-------+---------+
2 rows in set (0.00 sec)
Note − Here x is used to output the Nested diagnostic Context (NDC) associated with the thread that generated the logging event. We use NDC to distinguish clients in server-side components handling multiple clients. Check Log4J Manual for more information on this.
|
[
{
"code": null,
"e": 2089,
"s": 1960,
"text": "The log4j API provides the org.apache.log4j.jdbc.JDBCAppender object, which can put logging information in a specified database."
},
{
"code": null,
"e": 2256,
"s": 2089,
"text": "Before you start using JDBC based logging, you should create a table to maintain all the log information. Following is the SQL Statement for creating the LOGS table −"
},
{
"code": null,
"e": 2464,
"s": 2256,
"text": "CREATE TABLE LOGS\n (USER_ID VARCHAR(20) NOT NULL,\n DATED DATE NOT NULL,\n LOGGER VARCHAR(50) NOT NULL,\n LEVEL VARCHAR(10) NOT NULL,\n MESSAGE VARCHAR(1000) NOT NULL\n );"
},
{
"code": null,
"e": 2594,
"s": 2464,
"text": "Following is a sample configuration file log4j.properties for JDBCAppender which will is be used to log messages to a LOGS table."
},
{
"code": null,
"e": 3201,
"s": 2594,
"text": "# Define the root logger with appender file\nlog4j.rootLogger = DEBUG, DB\n\n# Define the DB appender\nlog4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender\n\n# Set JDBC URL\nlog4j.appender.DB.URL=jdbc:mysql://localhost/DBNAME\n\n# Set Database Driver\nlog4j.appender.DB.driver=com.mysql.jdbc.Driver\n\n# Set database user name and password\nlog4j.appender.DB.user=user_name\nlog4j.appender.DB.password=password\n\n# Set the SQL statement to be executed.\nlog4j.appender.DB.sql=INSERT INTO LOGS VALUES('%x','%d','%C','%p','%m')\n\n# Define the layout for file appender\nlog4j.appender.DB.layout=org.apache.log4j.PatternLayout\n"
},
{
"code": null,
"e": 3441,
"s": 3201,
"text": "For MySQL database, you would have to use the actual DBNAME, user ID and password, where you have created LOGS table. The SQL statement is to execute an INSERT statement with the table name LOGS and the values to be entered into the table."
},
{
"code": null,
"e": 3565,
"s": 3441,
"text": "JDBCAppender does not need a layout to be defined explicitly. Instead, the SQL statement passed to it uses a PatternLayout."
},
{
"code": null,
"e": 3685,
"s": 3565,
"text": "If you wish to have an XML configuration file equivalent to the above log4j.properties file, then here is the content −"
},
{
"code": null,
"e": 4366,
"s": 3685,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n<log4j:configuration>\n\n<appender name=\"DB\" class=\"org.apache.log4j.jdbc.JDBCAppender\">\n <param name=\"url\" value=\"jdbc:mysql://localhost/DBNAME\"/>\n <param name=\"driver\" value=\"com.mysql.jdbc.Driver\"/>\n <param name=\"user\" value=\"user_id\"/>\n <param name=\"password\" value=\"password\"/>\n <param name=\"sql\" value=\"INSERT INTO LOGS VALUES('%x','%d','%C','%p','%m')\"/>\n \n <layout class=\"org.apache.log4j.PatternLayout\">\n </layout>\n</appender>\n\n<logger name=\"log4j.rootLogger\" additivity=\"false\">\n <level value=\"DEBUG\"/>\n <appender-ref ref=\"DB\"/>\n</logger>\n\n</log4j:configuration>"
},
{
"code": null,
"e": 4496,
"s": 4366,
"text": "The following Java class is a very simple example that initializes and then uses the Log4J logging library for Java applications."
},
{
"code": null,
"e": 4867,
"s": 4496,
"text": "import org.apache.log4j.Logger;\nimport java.sql.*;\nimport java.io.*;\nimport java.util.*;\n\npublic class log4jExample{\n /* Get actual class name to be printed on */\n static Logger log = Logger.getLogger(log4jExample.class.getName());\n \n public static void main(String[] args)throws IOException,SQLException{\n log.debug(\"Debug\");\n log.info(\"Info\");\n }\n}"
},
{
"code": null,
"e": 5039,
"s": 4867,
"text": "Here are the steps to compile and run the above-mentioned program. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 5175,
"s": 5039,
"text": "All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. Follow the given steps −"
},
{
"code": null,
"e": 5215,
"s": 5175,
"text": "Create log4j.properties as shown above."
},
{
"code": null,
"e": 5271,
"s": 5215,
"text": "Create log4jExample.java as shown above and compile it."
},
{
"code": null,
"e": 5319,
"s": 5271,
"text": "Execute log4jExample binary to run the program."
},
{
"code": null,
"e": 5411,
"s": 5319,
"text": "Now check your LOGS table inside DBNAME database and you would find the following entries −"
},
{
"code": null,
"e": 5814,
"s": 5411,
"text": "mysql > select * from LOGS;\n+---------+------------+--------------+-------+---------+\n| USER_ID | DATED | LOGGER | LEVEL | MESSAGE |\n+---------+------------+--------------+-------+---------+\n| | 2010-05-13 | log4jExample | DEBUG | Debug |\n| | 2010-05-13 | log4jExample | INFO | Info |\n+---------+------------+--------------+-------+---------+\n2 rows in set (0.00 sec)\n"
}
] |
Design a Webpage like Technical Documentation using HTML & CSS
|
12 Apr, 2021
Introduction – Technical documentation is any document that explains the features of the respective product. In this project, we are going to create a technical documentation of C++ using HTML and CSS. The webpage has a menu sections that helps to navigate to different sections of the webpage.
Approach – We are going to divide the whole webpage into two sections. The left side has a menu called Documentation Menu with all the topics listed inside a navigation bar. It contains anchor tags which has links to IDs of all the sections(like inheritance, polymorphism etc.). In the right side, we have description for each of the topics. The idea behind this is once user clicks on one of the topics in the left section, respective topic details will load the content on the right. In the CSS file we are just beautifying the texts like its alignment, padding margin etc.
Implementation –
HTML Code
<!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="style.css"></head> <body> <div class="main-body"> <nav id="navbar"> <header>Documentation Menu</header> <a href="#Intro" class="nav-link"> What is C++</a> <a href="#Object" class="nav-link"> Objects and Classes</a> <a href="#Inheritance" class="nav-link"> Inheritance</a> <a href="#Polymorphism" class="nav-link"> Polymorphism</a> <a href="#Abstraction" class="nav-link"> Abstraction</a> <a href="#Encapsulation" class="nav-link"> Encapsulation</a> </nav> <main id="main-doc"> <section class="main-section" id="Intro"> <header> What is C++? </header> <p> C++ is a general purpose programming language and widely used now a days ' for competitive programming. It has imperative, object-oriented and generic programming features. C++ runs on lots of platform like Windows, Linux, Unix, Mac etc. C++ is an efficient and powerful language and finds wide use in various GUI platforms, 3D graphics and real-time simulations. Because of the inclusion of rich function libraries, working in C++ becomes simpler and convenient than C. Being object-oriented programming like Java, C++ provides the support of inheritance, polymorphism, encapsulation, etc. Unlike C, C++ allows exception handling and function overloading. </p> <p>he “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. All you have to do is display the message “Hello World” on the screen. <br><br>Let us now look at the program :<br> </p> <code> #include<iostream> <br> using namespace std; <br> int main() <br> { <br> cout〈〈"Hello World"; <br> return 0; <br> } </code> <br> <p>C++ is an Object Oriented Programming Language. <br> The main pillars of Object Oriented Programming are : </p> <ul> <li>Objects and Classes</li> <li>Inheritance</li> <li>Polymorphism</li> <li>Abstraction</li> <li>Encapsulation</li> </ul> </section> <section class="main-section" id="Object"> <header> Objects and Classes </header> <p> Object-oriented programming – As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. </p> <p><b>Object : </b>An Object is an identifiable entity with some characteristics and behavior. An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. <br> <b>Class : </b>The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed & used by creating an instance of that class. A class is like a blueprint for an object. For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties. </p> </section> <section class="main-section" id="Inheritance"> <header> Inheritance </header> <p> The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important feature of Object Oriented Programming. Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. Super Class: The class whose properties are inherited by sub class is called Base Class or Super class. Using inheritance, we have to write the functions only one time instead of three times as we have inherited rest of the three classes from base class(Vehicle). </p> <p> <b>Mode of Inheritance : </b><br><br> <b>Public Mode : </b>If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. <br><br> <b>Protected Mode : </b>If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class. <br><br> <b>Private Mode : </b>If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class. <br><br> <b>Types of Inheritance in C++ : </b> <br><br><br> <b>Single Inheritance :</b> In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only. <br><br> <b>Multiple Inheritance :</b> Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes. <br><br> <b>Multilevel Inheritance :</b> In this type of inheritance, a derived class is created from another derived class. <br><br> <b>Hieratical Inheritance :</b> In this type of inheritance, more than one sub class is inherited from a single base class i.e. more than one derived class is created from a single base class. <br><br> <b>Hybrid (Virtual) Inheritance :</b> Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. </p> </section> <section class="main-section" id="Polymorphism"> <header> Polymorphism </header> <p> The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism. Polymorphism is considered as one of the important features of Object Oriented Programming. <br> <b>In C++ polymorphism is mainly divided into two types:</b> <br> 1. Compile time Polymorphism<br> 2. Runtime Polymorphism </p> <p>Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading. <br> Runtime polymorphism: This type of polymorphism is achieved by Function Overriding. </p> </section> <section class="main-section" id="Abstraction"> <header> Abstraction </header> <p> Data abstraction is one of the most essential and important feature of object oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation. <br> Consider a real life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is. </p> <p> <b>Abstraction using Classes:</b> We can implement Abstraction in C++ using classes. Class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to outside world and which is not. <br> <b>Abstraction in Header files:</b> One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating power of numbers. <br><br><b>Advantages of Data Abstraction: </b><br> 1. Helps the user to avoid writing the low level code.<br> 2. Avoids code duplication and increases reusability.<br> 3. Can change internal implementation of class independently without affecting the user.<br> 4. Helps to increase security of an application or program as only important details are provided to the user. </p> </section> <section class="main-section" id="Encapsulation"> <header> Encapsulation </header> <p> In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulates them. Consider a real life example of encapsulation, in a company there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keep records of all the data related to finance. Similarly the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of sales section and the employees that can manipulate them are wrapped under a single name “sales section”. </p> <p> Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data. In the above example the data of any of the section like sales, finance or accounts is hidden from any other section.<br> In C++ encapsulation can be implemented using Class and access modifiers. </p> </section> </main> </div></body> </html>
CSS Code
div.main-body { display: grid; grid-template-columns: minmax(300px , auto)1fr; grid-template-areas: "navbar mainContent"; grid-gap: 20px;} nav#navbar { grid-area: navbar; position: fixed; } nav#navbar a { display: block; border: 1px solid black; padding: 5px; margin: 10px 0; text-decoration: none; color: black;} main#main-doc { grid-area: mainContent;} header { font-size: 1.5rem; font-weight: bold;} code { background-color: #CCC; display: block; padding: 20px;}
Outputs:
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 323,
"s": 28,
"text": "Introduction – Technical documentation is any document that explains the features of the respective product. In this project, we are going to create a technical documentation of C++ using HTML and CSS. The webpage has a menu sections that helps to navigate to different sections of the webpage."
},
{
"code": null,
"e": 899,
"s": 323,
"text": "Approach – We are going to divide the whole webpage into two sections. The left side has a menu called Documentation Menu with all the topics listed inside a navigation bar. It contains anchor tags which has links to IDs of all the sections(like inheritance, polymorphism etc.). In the right side, we have description for each of the topics. The idea behind this is once user clicks on one of the topics in the left section, respective topic details will load the content on the right. In the CSS file we are just beautifying the texts like its alignment, padding margin etc."
},
{
"code": null,
"e": 916,
"s": 899,
"text": "Implementation –"
},
{
"code": null,
"e": 926,
"s": 916,
"text": "HTML Code"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <div class=\"main-body\"> <nav id=\"navbar\"> <header>Documentation Menu</header> <a href=\"#Intro\" class=\"nav-link\"> What is C++</a> <a href=\"#Object\" class=\"nav-link\"> Objects and Classes</a> <a href=\"#Inheritance\" class=\"nav-link\"> Inheritance</a> <a href=\"#Polymorphism\" class=\"nav-link\"> Polymorphism</a> <a href=\"#Abstraction\" class=\"nav-link\"> Abstraction</a> <a href=\"#Encapsulation\" class=\"nav-link\"> Encapsulation</a> </nav> <main id=\"main-doc\"> <section class=\"main-section\" id=\"Intro\"> <header> What is C++? </header> <p> C++ is a general purpose programming language and widely used now a days ' for competitive programming. It has imperative, object-oriented and generic programming features. C++ runs on lots of platform like Windows, Linux, Unix, Mac etc. C++ is an efficient and powerful language and finds wide use in various GUI platforms, 3D graphics and real-time simulations. Because of the inclusion of rich function libraries, working in C++ becomes simpler and convenient than C. Being object-oriented programming like Java, C++ provides the support of inheritance, polymorphism, encapsulation, etc. Unlike C, C++ allows exception handling and function overloading. </p> <p>he “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. All you have to do is display the message “Hello World” on the screen. <br><br>Let us now look at the program :<br> </p> <code> #include<iostream> <br> using namespace std; <br> int main() <br> { <br> cout〈〈\"Hello World\"; <br> return 0; <br> } </code> <br> <p>C++ is an Object Oriented Programming Language. <br> The main pillars of Object Oriented Programming are : </p> <ul> <li>Objects and Classes</li> <li>Inheritance</li> <li>Polymorphism</li> <li>Abstraction</li> <li>Encapsulation</li> </ul> </section> <section class=\"main-section\" id=\"Object\"> <header> Objects and Classes </header> <p> Object-oriented programming – As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. </p> <p><b>Object : </b>An Object is an identifiable entity with some characteristics and behavior. An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. <br> <b>Class : </b>The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed & used by creating an instance of that class. A class is like a blueprint for an object. For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties. </p> </section> <section class=\"main-section\" id=\"Inheritance\"> <header> Inheritance </header> <p> The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important feature of Object Oriented Programming. Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. Super Class: The class whose properties are inherited by sub class is called Base Class or Super class. Using inheritance, we have to write the functions only one time instead of three times as we have inherited rest of the three classes from base class(Vehicle). </p> <p> <b>Mode of Inheritance : </b><br><br> <b>Public Mode : </b>If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. <br><br> <b>Protected Mode : </b>If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class. <br><br> <b>Private Mode : </b>If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class. <br><br> <b>Types of Inheritance in C++ : </b> <br><br><br> <b>Single Inheritance :</b> In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only. <br><br> <b>Multiple Inheritance :</b> Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes. <br><br> <b>Multilevel Inheritance :</b> In this type of inheritance, a derived class is created from another derived class. <br><br> <b>Hieratical Inheritance :</b> In this type of inheritance, more than one sub class is inherited from a single base class i.e. more than one derived class is created from a single base class. <br><br> <b>Hybrid (Virtual) Inheritance :</b> Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. </p> </section> <section class=\"main-section\" id=\"Polymorphism\"> <header> Polymorphism </header> <p> The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism. Polymorphism is considered as one of the important features of Object Oriented Programming. <br> <b>In C++ polymorphism is mainly divided into two types:</b> <br> 1. Compile time Polymorphism<br> 2. Runtime Polymorphism </p> <p>Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading. <br> Runtime polymorphism: This type of polymorphism is achieved by Function Overriding. </p> </section> <section class=\"main-section\" id=\"Abstraction\"> <header> Abstraction </header> <p> Data abstraction is one of the most essential and important feature of object oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation. <br> Consider a real life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is. </p> <p> <b>Abstraction using Classes:</b> We can implement Abstraction in C++ using classes. Class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to outside world and which is not. <br> <b>Abstraction in Header files:</b> One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating power of numbers. <br><br><b>Advantages of Data Abstraction: </b><br> 1. Helps the user to avoid writing the low level code.<br> 2. Avoids code duplication and increases reusability.<br> 3. Can change internal implementation of class independently without affecting the user.<br> 4. Helps to increase security of an application or program as only important details are provided to the user. </p> </section> <section class=\"main-section\" id=\"Encapsulation\"> <header> Encapsulation </header> <p> In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulates them. Consider a real life example of encapsulation, in a company there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keep records of all the data related to finance. Similarly the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of sales section and the employees that can manipulate them are wrapped under a single name “sales section”. </p> <p> Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data. In the above example the data of any of the section like sales, finance or accounts is hidden from any other section.<br> In C++ encapsulation can be implemented using Class and access modifiers. </p> </section> </main> </div></body> </html>",
"e": 16656,
"s": 926,
"text": null
},
{
"code": null,
"e": 16667,
"s": 16658,
"text": "CSS Code"
},
{
"code": "div.main-body { display: grid; grid-template-columns: minmax(300px , auto)1fr; grid-template-areas: \"navbar mainContent\"; grid-gap: 20px;} nav#navbar { grid-area: navbar; position: fixed; } nav#navbar a { display: block; border: 1px solid black; padding: 5px; margin: 10px 0; text-decoration: none; color: black;} main#main-doc { grid-area: mainContent;} header { font-size: 1.5rem; font-weight: bold;} code { background-color: #CCC; display: block; padding: 20px;}",
"e": 17202,
"s": 16667,
"text": null
},
{
"code": null,
"e": 17211,
"s": 17202,
"text": "Outputs:"
},
{
"code": null,
"e": 17226,
"s": 17211,
"text": "CSS-Properties"
},
{
"code": null,
"e": 17240,
"s": 17226,
"text": "CSS-Questions"
},
{
"code": null,
"e": 17255,
"s": 17240,
"text": "HTML-Questions"
},
{
"code": null,
"e": 17265,
"s": 17255,
"text": "HTML-Tags"
},
{
"code": null,
"e": 17269,
"s": 17265,
"text": "CSS"
},
{
"code": null,
"e": 17274,
"s": 17269,
"text": "HTML"
},
{
"code": null,
"e": 17291,
"s": 17274,
"text": "Web Technologies"
},
{
"code": null,
"e": 17296,
"s": 17291,
"text": "HTML"
},
{
"code": null,
"e": 17394,
"s": 17296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17433,
"s": 17394,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 17472,
"s": 17433,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 17511,
"s": 17472,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 17548,
"s": 17511,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 17577,
"s": 17548,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 17601,
"s": 17577,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 17654,
"s": 17601,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 17714,
"s": 17654,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 17775,
"s": 17714,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Spring - Injecting Inner Beans
|
As you know Java inner classes are defined within the scope of other classes, similarly, inner beans are beans that are defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or <constructor-arg/> elements is called inner bean and it is shown below.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "outerBean" class = "...">
<property name = "target">
<bean id = "innerBean" class = "..."/>
</property>
</bean>
</beans>
Let us have working Eclipse IDE in place and follow the following steps to create a Spring application −
Here is the content of TextEditor.java file −
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
// a setter method to inject the dependency.
public void setSpellChecker(SpellChecker spellChecker) {
System.out.println("Inside setSpellChecker." );
this.spellChecker = spellChecker;
}
// a getter method to return spellChecker
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
Following is the content of another dependent class file SpellChecker.java −
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling(){
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file −
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
Following is the configuration file Beans.xml which has configuration for the setter-based injection but using inner beans −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean using inner bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
<property name = "spellChecker">
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"/>
</property>
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −
Inside SpellChecker constructor.
|
[
{
"code": null,
"e": 2710,
"s": 2426,
"text": "As you know Java inner classes are defined within the scope of other classes, similarly, inner beans are beans that are defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or <constructor-arg/> elements is called inner bean and it is shown below."
},
{
"code": null,
"e": 3175,
"s": 2710,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"outerBean\" class = \"...\">\n <property name = \"target\">\n <bean id = \"innerBean\" class = \"...\"/>\n </property>\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 3280,
"s": 3175,
"text": "Let us have working Eclipse IDE in place and follow the following steps to create a Spring application −"
},
{
"code": null,
"e": 3326,
"s": 3280,
"text": "Here is the content of TextEditor.java file −"
},
{
"code": null,
"e": 3827,
"s": 3326,
"text": "package com.tutorialspoint;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n \n // a setter method to inject the dependency.\n public void setSpellChecker(SpellChecker spellChecker) {\n System.out.println(\"Inside setSpellChecker.\" );\n this.spellChecker = spellChecker;\n }\n \n // a getter method to return spellChecker\n public SpellChecker getSpellChecker() {\n return spellChecker;\n }\n public void spellCheck() {\n spellChecker.checkSpelling();\n }\n}"
},
{
"code": null,
"e": 3904,
"s": 3827,
"text": "Following is the content of another dependent class file SpellChecker.java −"
},
{
"code": null,
"e": 4146,
"s": 3904,
"text": "package com.tutorialspoint;\n\npublic class SpellChecker {\n public SpellChecker(){\n System.out.println(\"Inside SpellChecker constructor.\" );\n }\n public void checkSpelling(){\n System.out.println(\"Inside checkSpelling.\" );\n }\n}"
},
{
"code": null,
"e": 4198,
"s": 4146,
"text": "Following is the content of the MainApp.java file −"
},
{
"code": null,
"e": 4605,
"s": 4198,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n TextEditor te = (TextEditor) context.getBean(\"textEditor\");\n te.spellCheck();\n }\n}"
},
{
"code": null,
"e": 4730,
"s": 4605,
"text": "Following is the configuration file Beans.xml which has configuration for the setter-based injection but using inner beans −"
},
{
"code": null,
"e": 5319,
"s": 4730,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Definition for textEditor bean using inner bean -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\">\n <property name = \"spellChecker\">\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\"/>\n </property>\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 5498,
"s": 5319,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −"
}
] |
D3.js brush.move() Function
|
24 Aug, 2020
The brush.move() Function in D3.js is used to set the active selection of the brush on the specified group.
Syntax:
brush.move(group, selection);
Parameters: This function accepts a single parameter as mentioned above and described below
group: This parameter is the specified group on which brush is implemented.
selection: This parameter is an array of numbers.
Return Value: This function returns the array that defines the brush selection for that element.
Below programs illustrate the brush.move() function in D3.js
Example 1:
<!DOCTYPE html> <html> <head> <script src= "https://d3js.org/d3.v5.min.js"> </script> </head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h3>D3.js | brush.move() Function </h3> <button>Click</button> <br> <br> <svg style="background-color: lightgreen;" width="500" height="100"> </svg> <script> // Selecting SVG element const svg = d3.select("svg"); const g = svg.append("g"); // Creating a brush using the // d3.brush function g.call(d3.brush()); // Use of brush.move() function d3.select("button").on("click", function() { g.call(d3.brush().move, [ [100, 0], [400, 100] ]) }); </script> </center></body> </html>
Output:
Media error: Format(s) not supported or source(s) not found
Example 2:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src= "https://d3js.org/d3.v4.min.js"> </script> <style> circle { fill-opacity: 0.2; } circle.active { fill-opacity: 0.8; stroke: red; fill: green; } </style></head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h3>D3.js | brush.move() Function </h3> <svg width="600" height="300"></svg> <script> var data = d3.range(100).map(Math.random); var svg = d3.select("svg"), margin = {top: 50, right: 50, bottom: 50, left: 50}, width = +svg.attr("width") - margin.left - margin.right, height = +svg.attr("height") - margin.top - margin.bottom, g = svg.append("g") .attr("transform", "translate(" + margin.left + ", " + margin.top + ")" ); var x = d3.scaleLinear().range([0, width]), y = d3.randomNormal(height / 2, height / 8); var brush = d3.brushX() .extent([[0, 0], [width, height]]) .on("start brush end", brushmoved); g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0, 0)") .call(d3.axisTop(x)); var circle = g.append("g") .attr("class", "circle") .selectAll("circle") .data(data) .enter().append("circle") .attr("transform", function (d) { return "translate(" + x(d) + ", " + y() + ")"; }) .attr("r", 10); var gBrush = g.append("g") .attr("class", "brush") .call(brush); gBrush.call(brush.move, [0.3, 0.5].map(x)); var bs = ""; function brushmoved() { var s = d3.event.selection; if (d3.event.type === "start"){ bs = d3.event.selection; } else if (d3.event.type === "end"){ if (bs[0] !== s[0] && bs[1] !== s[1]) { console.log('moved both'); } else if (bs[0] !== s[0]) { console.log('moved left'); } else { console.log('moved right'); } } if (s == null) { handle.attr("display", "none"); circle.classed("active", false); } else { var sx = s.map(x.invert); circle.classed("active", function (d) { return sx[0] <= d && d <= sx[1]; }); handle.attr("display", null) .attr("transform", function (d, i) { return "translate(" + s[i] + ", " + height / 2 + ")"; }); } } </script> </center></body> </html>
Output:
Media error: Format(s) not supported or source(s) not found
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Aug, 2020"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "The brush.move() Function in D3.js is used to set the active selection of the brush on the specified group."
},
{
"code": null,
"e": 144,
"s": 136,
"text": "Syntax:"
},
{
"code": null,
"e": 174,
"s": 144,
"text": "brush.move(group, selection);"
},
{
"code": null,
"e": 266,
"s": 174,
"text": "Parameters: This function accepts a single parameter as mentioned above and described below"
},
{
"code": null,
"e": 342,
"s": 266,
"text": "group: This parameter is the specified group on which brush is implemented."
},
{
"code": null,
"e": 392,
"s": 342,
"text": "selection: This parameter is an array of numbers."
},
{
"code": null,
"e": 489,
"s": 392,
"text": "Return Value: This function returns the array that defines the brush selection for that element."
},
{
"code": null,
"e": 550,
"s": 489,
"text": "Below programs illustrate the brush.move() function in D3.js"
},
{
"code": null,
"e": 561,
"s": 550,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html> <html> <head> <script src= \"https://d3js.org/d3.v5.min.js\"> </script> </head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h3>D3.js | brush.move() Function </h3> <button>Click</button> <br> <br> <svg style=\"background-color: lightgreen;\" width=\"500\" height=\"100\"> </svg> <script> // Selecting SVG element const svg = d3.select(\"svg\"); const g = svg.append(\"g\"); // Creating a brush using the // d3.brush function g.call(d3.brush()); // Use of brush.move() function d3.select(\"button\").on(\"click\", function() { g.call(d3.brush().move, [ [100, 0], [400, 100] ]) }); </script> </center></body> </html>",
"e": 1599,
"s": 561,
"text": null
},
{
"code": null,
"e": 1607,
"s": 1599,
"text": "Output:"
},
{
"code": null,
"e": 1667,
"s": 1607,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 1678,
"s": 1667,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src= \"https://d3js.org/d3.v4.min.js\"> </script> <style> circle { fill-opacity: 0.2; } circle.active { fill-opacity: 0.8; stroke: red; fill: green; } </style></head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h3>D3.js | brush.move() Function </h3> <svg width=\"600\" height=\"300\"></svg> <script> var data = d3.range(100).map(Math.random); var svg = d3.select(\"svg\"), margin = {top: 50, right: 50, bottom: 50, left: 50}, width = +svg.attr(\"width\") - margin.left - margin.right, height = +svg.attr(\"height\") - margin.top - margin.bottom, g = svg.append(\"g\") .attr(\"transform\", \"translate(\" + margin.left + \", \" + margin.top + \")\" ); var x = d3.scaleLinear().range([0, width]), y = d3.randomNormal(height / 2, height / 8); var brush = d3.brushX() .extent([[0, 0], [width, height]]) .on(\"start brush end\", brushmoved); g.append(\"g\") .attr(\"class\", \"axis axis--x\") .attr(\"transform\", \"translate(0, 0)\") .call(d3.axisTop(x)); var circle = g.append(\"g\") .attr(\"class\", \"circle\") .selectAll(\"circle\") .data(data) .enter().append(\"circle\") .attr(\"transform\", function (d) { return \"translate(\" + x(d) + \", \" + y() + \")\"; }) .attr(\"r\", 10); var gBrush = g.append(\"g\") .attr(\"class\", \"brush\") .call(brush); gBrush.call(brush.move, [0.3, 0.5].map(x)); var bs = \"\"; function brushmoved() { var s = d3.event.selection; if (d3.event.type === \"start\"){ bs = d3.event.selection; } else if (d3.event.type === \"end\"){ if (bs[0] !== s[0] && bs[1] !== s[1]) { console.log('moved both'); } else if (bs[0] !== s[0]) { console.log('moved left'); } else { console.log('moved right'); } } if (s == null) { handle.attr(\"display\", \"none\"); circle.classed(\"active\", false); } else { var sx = s.map(x.invert); circle.classed(\"active\", function (d) { return sx[0] <= d && d <= sx[1]; }); handle.attr(\"display\", null) .attr(\"transform\", function (d, i) { return \"translate(\" + s[i] + \", \" + height / 2 + \")\"; }); } } </script> </center></body> </html> ",
"e": 4851,
"s": 1678,
"text": null
},
{
"code": null,
"e": 4859,
"s": 4851,
"text": "Output:"
},
{
"code": null,
"e": 4919,
"s": 4859,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 4925,
"s": 4919,
"text": "D3.js"
},
{
"code": null,
"e": 4936,
"s": 4925,
"text": "JavaScript"
},
{
"code": null,
"e": 4953,
"s": 4936,
"text": "Web Technologies"
},
{
"code": null,
"e": 5051,
"s": 4953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5112,
"s": 5051,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5184,
"s": 5112,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5224,
"s": 5184,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5276,
"s": 5224,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 5317,
"s": 5276,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5379,
"s": 5317,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5412,
"s": 5379,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5473,
"s": 5412,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5523,
"s": 5473,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Program for Fahrenheit to Celsius conversion in C
|
Given with temperature ‘n’ in Fahrenheit and the challenge is to convert the given temperature to Celsius and display it.
Input 1-: 132.00
Output -: after converting fahrenheit 132.00 to celsius 55.56
Input 2-: 456.10
Output -: after converting fahrenheit 456.10 to celsius 235.61
For converting the temperature from Fahrenheit to Celsius, there is a formula which is given below
T(°C) = (T(°F) - 32) × 5/9
Where, T(°C) is temperature in Celsius and T(°F) is temperature in Fahrenheit
Approach used below is as follows −
Input temperature in a float variable let’s say Fahrenheit
Apply the formula to convert the temperature into Celsius
Print celsius
Start
Step 1-> Declare function to convert Fahrenheit to Celsius
float convert(float fahrenheit)
declare float Celsius
Set celsius = (fahrenheit - 32) * 5 / 9
return Celsius
step 2-> In main()
declare and set float fahrenheit = 132.00
Call convert(fahrenheit)
Stop
Live Demo
#include <stdio.h>
//convert fahrenheit to celsius
float convert(float fahrenheit) {
float celsius;
celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
int main() {
float fahrenheit = 132.00;
printf("after converting fahrenheit %.2f to celsius %.2f ",fahrenheit,convert(fahrenheit));
return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
after converting fahrenheit 132.00 to celsius 55.56
|
[
{
"code": null,
"e": 1309,
"s": 1187,
"text": "Given with temperature ‘n’ in Fahrenheit and the challenge is to convert the given temperature to Celsius and display it."
},
{
"code": null,
"e": 1468,
"s": 1309,
"text": "Input 1-: 132.00\nOutput -: after converting fahrenheit 132.00 to celsius 55.56\nInput 2-: 456.10\nOutput -: after converting fahrenheit 456.10 to celsius 235.61"
},
{
"code": null,
"e": 1567,
"s": 1468,
"text": "For converting the temperature from Fahrenheit to Celsius, there is a formula which is given below"
},
{
"code": null,
"e": 1594,
"s": 1567,
"text": "T(°C) = (T(°F) - 32) × 5/9"
},
{
"code": null,
"e": 1672,
"s": 1594,
"text": "Where, T(°C) is temperature in Celsius and T(°F) is temperature in Fahrenheit"
},
{
"code": null,
"e": 1708,
"s": 1672,
"text": "Approach used below is as follows −"
},
{
"code": null,
"e": 1767,
"s": 1708,
"text": "Input temperature in a float variable let’s say Fahrenheit"
},
{
"code": null,
"e": 1825,
"s": 1767,
"text": "Apply the formula to convert the temperature into Celsius"
},
{
"code": null,
"e": 1839,
"s": 1825,
"text": "Print celsius"
},
{
"code": null,
"e": 2131,
"s": 1839,
"text": "Start\nStep 1-> Declare function to convert Fahrenheit to Celsius\n float convert(float fahrenheit)\n declare float Celsius\n Set celsius = (fahrenheit - 32) * 5 / 9\n return Celsius\nstep 2-> In main()\n declare and set float fahrenheit = 132.00\n Call convert(fahrenheit)\nStop"
},
{
"code": null,
"e": 2142,
"s": 2131,
"text": " Live Demo"
},
{
"code": null,
"e": 2459,
"s": 2142,
"text": "#include <stdio.h>\n//convert fahrenheit to celsius\nfloat convert(float fahrenheit) {\n float celsius;\n celsius = (fahrenheit - 32) * 5 / 9;\n return celsius;\n}\nint main() {\n float fahrenheit = 132.00;\n printf(\"after converting fahrenheit %.2f to celsius %.2f \",fahrenheit,convert(fahrenheit));\n return 0;\n}"
},
{
"code": null,
"e": 2518,
"s": 2459,
"text": "IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT"
},
{
"code": null,
"e": 2570,
"s": 2518,
"text": "after converting fahrenheit 132.00 to celsius 55.56"
}
] |
Python | Pandas Series.nunique()
|
17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier.
While analyzing the data, many times the user wants to see the unique values in a particular column. Pandas nunique() is used to get a count of unique values.
To download the CSV file used, Click Here.
Syntax: Series.nunique(dropna=True)
Parameters:dropna: Exclude NULL value if True
Return Type: Integer – Number of unique values in a column.
Example #1: Using nunique()In this example, nunique() method is used to get number of all unique values in Team column.
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # storing unique value in a variableunique_value = data["Team"].nunique() # printing valueprint(unique_value)
Output:The output of number of unique values is returned.
10
Example #2: NULL value HandlingIn this example, length of array returned by unique() method is compared to integer returned by nunique() method.
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # storing unique value in a variablearr = data["Team"].unique() # storing unique value in a variableunique_value = data["Team"].nunique(dropna = True) # printing valuesprint(len(arr), unique_value)
Output:The output is not same in both of the cases as dropna parameter is set to True and hence NULL values were excluded while counting unique values.
11 10
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2018"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 402,
"s": 243,
"text": "While analyzing the data, many times the user wants to see the unique values in a particular column. Pandas nunique() is used to get a count of unique values."
},
{
"code": null,
"e": 445,
"s": 402,
"text": "To download the CSV file used, Click Here."
},
{
"code": null,
"e": 481,
"s": 445,
"text": "Syntax: Series.nunique(dropna=True)"
},
{
"code": null,
"e": 527,
"s": 481,
"text": "Parameters:dropna: Exclude NULL value if True"
},
{
"code": null,
"e": 587,
"s": 527,
"text": "Return Type: Integer – Number of unique values in a column."
},
{
"code": null,
"e": 707,
"s": 587,
"text": "Example #1: Using nunique()In this example, nunique() method is used to get number of all unique values in Team column."
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # storing unique value in a variableunique_value = data[\"Team\"].nunique() # printing valueprint(unique_value)",
"e": 935,
"s": 707,
"text": null
},
{
"code": null,
"e": 993,
"s": 935,
"text": "Output:The output of number of unique values is returned."
},
{
"code": null,
"e": 996,
"s": 993,
"text": "10"
},
{
"code": null,
"e": 1142,
"s": 996,
"text": " Example #2: NULL value HandlingIn this example, length of array returned by unique() method is compared to integer returned by nunique() method."
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # storing unique value in a variablearr = data[\"Team\"].unique() # storing unique value in a variableunique_value = data[\"Team\"].nunique(dropna = True) # printing valuesprint(len(arr), unique_value)",
"e": 1459,
"s": 1142,
"text": null
},
{
"code": null,
"e": 1611,
"s": 1459,
"text": "Output:The output is not same in both of the cases as dropna parameter is set to True and hence NULL values were excluded while counting unique values."
},
{
"code": null,
"e": 1617,
"s": 1611,
"text": "11 10"
},
{
"code": null,
"e": 1638,
"s": 1617,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1667,
"s": 1638,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 1681,
"s": 1667,
"text": "Python-pandas"
},
{
"code": null,
"e": 1688,
"s": 1681,
"text": "Python"
},
{
"code": null,
"e": 1786,
"s": 1688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1804,
"s": 1786,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1846,
"s": 1804,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1868,
"s": 1846,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1903,
"s": 1868,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1929,
"s": 1903,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1961,
"s": 1929,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1990,
"s": 1961,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2020,
"s": 1990,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2047,
"s": 2020,
"text": "Python Classes and Objects"
}
] |
Python MongoDB – Query
|
01 Apr, 2022
MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs.
MongoDB query is used to specify the selection filter using query operators while retrieving the data from the collection by db.find() method. We can easily filter the documents using the query object. To apply the filter on the collection, we can pass the query specifying the condition for the required documents as a parameter to this method, which is an optional parameter for db.find() method. Query Selectors: Following is the list of some operators used in the queries in MongoDB.
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }
The Database or Collection on which we operate: Example 1:
Python3
# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient("mongodb://localhost:27017/") # databasedb = myclient["mydatabase"] # Created or Switched to collection# names: GeeksForGeeksCollection = db["GeeksForGeeks"] # Filtering the Quantities greater# than 40 using query.cursor = Collection.find({"Quantity":{"$gt":40}}) # Printing the filtered data.print("The data having Quantity greater than 40 is:")for record in cursor: print(record) # Filtering the Quantities less# than 40 using query.cursor = Collection.find({"Quantity":{"$lt":40}}) # Printing the filtered data.print("\nThe data having Quantity less than 40 is:")for record in cursor: print(record)
Output: Example 2:
Python3
# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient("mongodb://localhost:27017/") # databasedb = myclient["mydatabase"] # Created or Switched to collection# names: GeeksForGeeksCollection = db["GeeksForGeeks"] # Filtering the (Quantities greater than# 40 AND greater than 40) using AND query.cursor = Collection.find({"$and":[{"Quantity":{"$gt":40}}, {"Quantity":{"$gt":50}}]}) # Printing the filtered data.print("Quantities greater than 40 AND\Quantities greater than 40 :")for record in cursor: print(record) # Filtering the (Quantities greater than# 40 OR greater than 40) using OR query.cursor = Collection.find({"$or":[{"Quantity":{"$gt":40}}, {"Quantity":{"$gt":50}}]}) # Printing the filtered data.print()print("Quantities greater than 40 OR\Quantities greater than 40 :")for record in cursor: print(record)
Output:
rkbhola5
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2022"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs."
},
{
"code": null,
"e": 707,
"s": 218,
"text": "MongoDB query is used to specify the selection filter using query operators while retrieving the data from the collection by db.find() method. We can easily filter the documents using the query object. To apply the filter on the collection, we can pass the query specifying the condition for the required documents as a parameter to this method, which is an optional parameter for db.find() method. Query Selectors: Following is the list of some operators used in the queries in MongoDB. "
},
{
"code": null,
"e": 1046,
"s": 707,
"text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } "
},
{
"code": null,
"e": 1107,
"s": 1046,
"text": "The Database or Collection on which we operate: Example 1: "
},
{
"code": null,
"e": 1115,
"s": 1107,
"text": "Python3"
},
{
"code": "# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient(\"mongodb://localhost:27017/\") # databasedb = myclient[\"mydatabase\"] # Created or Switched to collection# names: GeeksForGeeksCollection = db[\"GeeksForGeeks\"] # Filtering the Quantities greater# than 40 using query.cursor = Collection.find({\"Quantity\":{\"$gt\":40}}) # Printing the filtered data.print(\"The data having Quantity greater than 40 is:\")for record in cursor: print(record) # Filtering the Quantities less# than 40 using query.cursor = Collection.find({\"Quantity\":{\"$lt\":40}}) # Printing the filtered data.print(\"\\nThe data having Quantity less than 40 is:\")for record in cursor: print(record)",
"e": 1840,
"s": 1115,
"text": null
},
{
"code": null,
"e": 1861,
"s": 1840,
"text": "Output: Example 2: "
},
{
"code": null,
"e": 1869,
"s": 1861,
"text": "Python3"
},
{
"code": "# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient(\"mongodb://localhost:27017/\") # databasedb = myclient[\"mydatabase\"] # Created or Switched to collection# names: GeeksForGeeksCollection = db[\"GeeksForGeeks\"] # Filtering the (Quantities greater than# 40 AND greater than 40) using AND query.cursor = Collection.find({\"$and\":[{\"Quantity\":{\"$gt\":40}}, {\"Quantity\":{\"$gt\":50}}]}) # Printing the filtered data.print(\"Quantities greater than 40 AND\\Quantities greater than 40 :\")for record in cursor: print(record) # Filtering the (Quantities greater than# 40 OR greater than 40) using OR query.cursor = Collection.find({\"$or\":[{\"Quantity\":{\"$gt\":40}}, {\"Quantity\":{\"$gt\":50}}]}) # Printing the filtered data.print()print(\"Quantities greater than 40 OR\\Quantities greater than 40 :\")for record in cursor: print(record)",
"e": 2816,
"s": 1869,
"text": null
},
{
"code": null,
"e": 2825,
"s": 2816,
"text": "Output: "
},
{
"code": null,
"e": 2834,
"s": 2825,
"text": "rkbhola5"
},
{
"code": null,
"e": 2849,
"s": 2834,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 2856,
"s": 2849,
"text": "Python"
},
{
"code": null,
"e": 2954,
"s": 2856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2982,
"s": 2954,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3032,
"s": 2982,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3054,
"s": 3032,
"text": "Python map() function"
},
{
"code": null,
"e": 3098,
"s": 3054,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3140,
"s": 3098,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3162,
"s": 3140,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3197,
"s": 3162,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3223,
"s": 3197,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3255,
"s": 3223,
"text": "How to Install PIP on Windows ?"
}
] |
Python - Extract Key's Value, if Key Present in List and Dictionary - GeeksforGeeks
|
30 Aug, 2020
Given a list, dictionary and a Key K, print value of K from dictionary if key present in both, list and dictionary.
Input : test_list = [“Gfg”, “is”, “Good”, “for”, “Geeks”], test_dict = {“Gfg” : 5, “Best” : 6}, K = “Gfg”Output : 5Explanation : “Gfg” is present in list and has value 5 in dictionary.
Input : test_list = [“Good”, “for”, “Geeks”], test_dict = {“Gfg” : 5, “Best” : 6}, K = “Gfg”Output : NoneExplanation : “Gfg” not present in List.
Method #1 : Using all() + generator expression
The combination of above functions offer one of the ways in which this problem can be solved. In this we use all() to check for occurrence in both dictionary and list. If result is true value is extracted to result.
Python3
# Python3 code to demonstrate working of # Extract Key's Value, if Key Present in List and Dictionary# Using all() + list comprehension # initializing listtest_list = ["Gfg", "is", "Good", "for", "Geeks"] # initializing Dictionarytest_dict = {"Gfg" : 2, "is" : 4, "Best" : 6} # initializing K K = "Gfg" # printing original list and Dictionaryprint("The original list : " + str(test_list))print("The original Dictionary : " + str(test_dict)) # using all() to check for occurrence in list and dict# encapsulating list and dictionary keys in list res = None if all(K in sub for sub in [test_dict, test_list]): res = test_dict[K] # printing result print("Extracted Value : " + str(res))
The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2
Method #2 : Using set() + intersection()
This is one another way to check for key’s presence in both the containers. In this, we compute intersection of all values of list and dict keys, and test for Key’s occurrence in that.
Python3
# Python3 code to demonstrate working of # Extract Key's Value, if Key Present in List and Dictionary# Using set() + intersection() # initializing listtest_list = ["Gfg", "is", "Good", "for", "Geeks"] # initializing Dictionarytest_dict = {"Gfg" : 2, "is" : 4, "Best" : 6} # initializing K K = "Gfg" # printing original list and Dictionaryprint("The original list : " + str(test_list))print("The original Dictionary : " + str(test_dict)) # conversion of lists to set and intersection with keys # using intersectionres = None if K in set(test_list).intersection(test_dict): res = test_dict[K] # printing result print("Extracted Value : " + str(res))
The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24087,
"s": 24059,
"text": "\n30 Aug, 2020"
},
{
"code": null,
"e": 24203,
"s": 24087,
"text": "Given a list, dictionary and a Key K, print value of K from dictionary if key present in both, list and dictionary."
},
{
"code": null,
"e": 24388,
"s": 24203,
"text": "Input : test_list = [“Gfg”, “is”, “Good”, “for”, “Geeks”], test_dict = {“Gfg” : 5, “Best” : 6}, K = “Gfg”Output : 5Explanation : “Gfg” is present in list and has value 5 in dictionary."
},
{
"code": null,
"e": 24534,
"s": 24388,
"text": "Input : test_list = [“Good”, “for”, “Geeks”], test_dict = {“Gfg” : 5, “Best” : 6}, K = “Gfg”Output : NoneExplanation : “Gfg” not present in List."
},
{
"code": null,
"e": 24581,
"s": 24534,
"text": "Method #1 : Using all() + generator expression"
},
{
"code": null,
"e": 24798,
"s": 24581,
"text": " The combination of above functions offer one of the ways in which this problem can be solved. In this we use all() to check for occurrence in both dictionary and list. If result is true value is extracted to result."
},
{
"code": null,
"e": 24806,
"s": 24798,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract Key's Value, if Key Present in List and Dictionary# Using all() + list comprehension # initializing listtest_list = [\"Gfg\", \"is\", \"Good\", \"for\", \"Geeks\"] # initializing Dictionarytest_dict = {\"Gfg\" : 2, \"is\" : 4, \"Best\" : 6} # initializing K K = \"Gfg\" # printing original list and Dictionaryprint(\"The original list : \" + str(test_list))print(\"The original Dictionary : \" + str(test_dict)) # using all() to check for occurrence in list and dict# encapsulating list and dictionary keys in list res = None if all(K in sub for sub in [test_dict, test_list]): res = test_dict[K] # printing result print(\"Extracted Value : \" + str(res))",
"e": 25498,
"s": 24806,
"text": null
},
{
"code": null,
"e": 25634,
"s": 25498,
"text": "The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']\nThe original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}\nExtracted Value : 2\n"
},
{
"code": null,
"e": 25675,
"s": 25634,
"text": "Method #2 : Using set() + intersection()"
},
{
"code": null,
"e": 25860,
"s": 25675,
"text": "This is one another way to check for key’s presence in both the containers. In this, we compute intersection of all values of list and dict keys, and test for Key’s occurrence in that."
},
{
"code": null,
"e": 25868,
"s": 25860,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract Key's Value, if Key Present in List and Dictionary# Using set() + intersection() # initializing listtest_list = [\"Gfg\", \"is\", \"Good\", \"for\", \"Geeks\"] # initializing Dictionarytest_dict = {\"Gfg\" : 2, \"is\" : 4, \"Best\" : 6} # initializing K K = \"Gfg\" # printing original list and Dictionaryprint(\"The original list : \" + str(test_list))print(\"The original Dictionary : \" + str(test_dict)) # conversion of lists to set and intersection with keys # using intersectionres = None if K in set(test_list).intersection(test_dict): res = test_dict[K] # printing result print(\"Extracted Value : \" + str(res))",
"e": 26525,
"s": 25868,
"text": null
},
{
"code": null,
"e": 26661,
"s": 26525,
"text": "The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']\nThe original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}\nExtracted Value : 2\n"
},
{
"code": null,
"e": 26688,
"s": 26661,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 26709,
"s": 26688,
"text": "Python list-programs"
},
{
"code": null,
"e": 26716,
"s": 26709,
"text": "Python"
},
{
"code": null,
"e": 26732,
"s": 26716,
"text": "Python Programs"
},
{
"code": null,
"e": 26830,
"s": 26732,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26839,
"s": 26830,
"text": "Comments"
},
{
"code": null,
"e": 26852,
"s": 26839,
"text": "Old Comments"
},
{
"code": null,
"e": 26870,
"s": 26852,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26905,
"s": 26870,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26927,
"s": 26905,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26959,
"s": 26927,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26989,
"s": 26959,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27032,
"s": 26989,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27054,
"s": 27032,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27100,
"s": 27054,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27157,
"s": 27100,
"text": "Python program to check whether a number is Prime or not"
}
] |
When to use virtual destructors in C++?
|
Scott Meyers in Effective C++ says −
If a class has any virtual function, it should have a virtual destructor, and that classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.
So you should declare destructors virtual in polymorphic base classes. This is because if you create an object of base class using a derived constructor −
Base *b = new Derived();
// use b
delete b;
If Base's destructor is not virtual then delete b has undefined behavior in this case. The call to the destructor will be resolved like any non-virtual code. So the destructor of the base class will be called but not the one of the derived class, this will result in a resources leak.
|
[
{
"code": null,
"e": 1099,
"s": 1062,
"text": "Scott Meyers in Effective C++ says −"
},
{
"code": null,
"e": 1305,
"s": 1099,
"text": "If a class has any virtual function, it should have a virtual destructor, and that classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors."
},
{
"code": null,
"e": 1460,
"s": 1305,
"text": "So you should declare destructors virtual in polymorphic base classes. This is because if you create an object of base class using a derived constructor −"
},
{
"code": null,
"e": 1504,
"s": 1460,
"text": "Base *b = new Derived();\n// use b\ndelete b;"
},
{
"code": null,
"e": 1789,
"s": 1504,
"text": "If Base's destructor is not virtual then delete b has undefined behavior in this case. The call to the destructor will be resolved like any non-virtual code. So the destructor of the base class will be called but not the one of the derived class, this will result in a resources leak."
}
] |
How does Python work?. A simple explanation of how Python code... | by Dhruvil Karani | Towards Data Science
|
As a Machine Learning Engineer, I have been using Python for more than a year. Recently, I have also started learning C++, for fun. It made me realize how easy and intuitive Python is. I got more curious about how Python is different from other languages and its working. In this blog, I try to scratch Python’s inner working.
Python started as a hobby project by Guido Van Rossum and was first released in 1991. A general purpose language, Python is powering large chunk of many companies like Netflix and Instagram. In an interview, Guido compares Python to languages like Java or Swift and says that while the latter two are a great choice for software developers — people whose day job is programming, but Python was made for people whose day job has nothing to do with software development but they code mainly to handle data.
When you read about Python, quite often you come across words like — compiled vs interpreted, bytecode vs machine code, dynamic typing vs static typing, garbage collectors, etc. Wikipedia describes Python as
Python is an interpreted, high-level, general-purpose programming language. It is is dynamically typed and garbage-collected.
When you write a program in C/C++, you have to compile it. Compilation involves translating your human understandable code to machine understandable code, or Machine Code. Machine code is the base level form of instructions that can be directly executed by the CPU. Upon successful compilation, your code generates an executable file. Executing this file runs the operations in your code step by step.
For the most part, Python is an interpreted language and not a compiled one, although compilation is a step. Python code, written in .py file is first compiled to what is called bytecode (discussed in detail further) which is stored with a .pyc or .pyo format.
Instead of translating source code to machine code like C++, Python code it translated to bytecode. This bytecode is a low-level set of instructions that can be executed by an interpreter. In most PCs, Python interpreter is installed at /usr/local/bin/python3.8. Instead of executing the instructions on CPU, bytecode instructions are executed on a Virtual Machine.
One popular advantage of interpreted languages is that they are platform-independent. As long as the Python bytecode and the Virtual Machine have the same version, Python bytecode can be executed on any platform (Windows, MacOS, etc).
Dynamic typing is another advantage. In static-typed languages like C++, you have to declare the variable type and any discrepancy like adding a string and an integer is checked during compile time. In strongly typed languages like Python, it is the job of the interpreter to check the validity of the variable types and operations performed.
Dynamic typing provides a lot of freedom, but simultaneously it makes your code risky and sometimes difficult to debug.
Python is often accused of being ‘slow’. Now while the term is relative and argued a lot, the reason for being slow is because the interpreter has to do extra work to have the bytecode instruction translated into a form that can be executed on the machine. A StackOverflow post makes it easier to understand using an analogy —
If you can talk in your native language to someone, that would generally work faster than having an interpreter having to translate your language into some other language for the listener to understand.
In older programming languages, memory allocation was quite manual. Many times when you use variables that are no longer in use or referenced anywhere else in the program, they need to be cleaned from the memory. Garbage Collector does that for you. It automatically frees up space without you doing anything. The memory management works in two ways —
In a simplified way, it keeps track of the number of references to an object. When that number goes down to zero, it deletes that object. This is called reference counting. This cannot be disabled in Python.
In cases where object references itself or two objects refer each other, a process called generation garbage collection helps. This is something traditional reference counting cannot take care of.
Many times in your personal project or on GitHub, you might have seen a folder named __pycache__ being created automatically.
/folder - __pycache__ - preprocess.cpython-36.pyc - preprocess.py
As you can see, the filename is the same as the one outside __pycache__ folder. The .pyc extension tells us that the file contains bytecode for preprocess.py. The names cpython denotes the type of interpreter. CPython means that the interpreter was implemented in C language. Similarly, JPython is a Python interpreter implemented in Java.
But why is the folder created in the first place? Well, it slightly increases the speed of the Python program. Unless you change your Python code, recompilation to bytecode is avoided, thereby saving time.
I have started my personal blog and I don’t intend to write more amazing articles on Medium. Support my blog by subscribing to thenlp.space
|
[
{
"code": null,
"e": 498,
"s": 171,
"text": "As a Machine Learning Engineer, I have been using Python for more than a year. Recently, I have also started learning C++, for fun. It made me realize how easy and intuitive Python is. I got more curious about how Python is different from other languages and its working. In this blog, I try to scratch Python’s inner working."
},
{
"code": null,
"e": 1003,
"s": 498,
"text": "Python started as a hobby project by Guido Van Rossum and was first released in 1991. A general purpose language, Python is powering large chunk of many companies like Netflix and Instagram. In an interview, Guido compares Python to languages like Java or Swift and says that while the latter two are a great choice for software developers — people whose day job is programming, but Python was made for people whose day job has nothing to do with software development but they code mainly to handle data."
},
{
"code": null,
"e": 1211,
"s": 1003,
"text": "When you read about Python, quite often you come across words like — compiled vs interpreted, bytecode vs machine code, dynamic typing vs static typing, garbage collectors, etc. Wikipedia describes Python as"
},
{
"code": null,
"e": 1337,
"s": 1211,
"text": "Python is an interpreted, high-level, general-purpose programming language. It is is dynamically typed and garbage-collected."
},
{
"code": null,
"e": 1739,
"s": 1337,
"text": "When you write a program in C/C++, you have to compile it. Compilation involves translating your human understandable code to machine understandable code, or Machine Code. Machine code is the base level form of instructions that can be directly executed by the CPU. Upon successful compilation, your code generates an executable file. Executing this file runs the operations in your code step by step."
},
{
"code": null,
"e": 2000,
"s": 1739,
"text": "For the most part, Python is an interpreted language and not a compiled one, although compilation is a step. Python code, written in .py file is first compiled to what is called bytecode (discussed in detail further) which is stored with a .pyc or .pyo format."
},
{
"code": null,
"e": 2366,
"s": 2000,
"text": "Instead of translating source code to machine code like C++, Python code it translated to bytecode. This bytecode is a low-level set of instructions that can be executed by an interpreter. In most PCs, Python interpreter is installed at /usr/local/bin/python3.8. Instead of executing the instructions on CPU, bytecode instructions are executed on a Virtual Machine."
},
{
"code": null,
"e": 2601,
"s": 2366,
"text": "One popular advantage of interpreted languages is that they are platform-independent. As long as the Python bytecode and the Virtual Machine have the same version, Python bytecode can be executed on any platform (Windows, MacOS, etc)."
},
{
"code": null,
"e": 2944,
"s": 2601,
"text": "Dynamic typing is another advantage. In static-typed languages like C++, you have to declare the variable type and any discrepancy like adding a string and an integer is checked during compile time. In strongly typed languages like Python, it is the job of the interpreter to check the validity of the variable types and operations performed."
},
{
"code": null,
"e": 3064,
"s": 2944,
"text": "Dynamic typing provides a lot of freedom, but simultaneously it makes your code risky and sometimes difficult to debug."
},
{
"code": null,
"e": 3391,
"s": 3064,
"text": "Python is often accused of being ‘slow’. Now while the term is relative and argued a lot, the reason for being slow is because the interpreter has to do extra work to have the bytecode instruction translated into a form that can be executed on the machine. A StackOverflow post makes it easier to understand using an analogy —"
},
{
"code": null,
"e": 3594,
"s": 3391,
"text": "If you can talk in your native language to someone, that would generally work faster than having an interpreter having to translate your language into some other language for the listener to understand."
},
{
"code": null,
"e": 3946,
"s": 3594,
"text": "In older programming languages, memory allocation was quite manual. Many times when you use variables that are no longer in use or referenced anywhere else in the program, they need to be cleaned from the memory. Garbage Collector does that for you. It automatically frees up space without you doing anything. The memory management works in two ways —"
},
{
"code": null,
"e": 4154,
"s": 3946,
"text": "In a simplified way, it keeps track of the number of references to an object. When that number goes down to zero, it deletes that object. This is called reference counting. This cannot be disabled in Python."
},
{
"code": null,
"e": 4351,
"s": 4154,
"text": "In cases where object references itself or two objects refer each other, a process called generation garbage collection helps. This is something traditional reference counting cannot take care of."
},
{
"code": null,
"e": 4477,
"s": 4351,
"text": "Many times in your personal project or on GitHub, you might have seen a folder named __pycache__ being created automatically."
},
{
"code": null,
"e": 4553,
"s": 4477,
"text": "/folder - __pycache__ - preprocess.cpython-36.pyc - preprocess.py"
},
{
"code": null,
"e": 4893,
"s": 4553,
"text": "As you can see, the filename is the same as the one outside __pycache__ folder. The .pyc extension tells us that the file contains bytecode for preprocess.py. The names cpython denotes the type of interpreter. CPython means that the interpreter was implemented in C language. Similarly, JPython is a Python interpreter implemented in Java."
},
{
"code": null,
"e": 5099,
"s": 4893,
"text": "But why is the folder created in the first place? Well, it slightly increases the speed of the Python program. Unless you change your Python code, recompilation to bytecode is avoided, thereby saving time."
}
] |
Estimating the value of Pi using Monte Carlo - GeeksforGeeks
|
24 Nov, 2021
Monte Carlo estimation Monte Carlo methods are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results. One of the basic examples of getting started with the Monte Carlo algorithm is the estimation of Pi. Estimation of Pi The idea is to simulate random (x, y) points in a 2-D plane with domain as a square of side 1 unit. Imagine a circle inside the same domain with same diameter and inscribed into the square. We then calculate the ratio of number points that lied inside the circle and total number of generated points. Refer to the image below:
Random points are generated only few of which lie outside the imaginary circle
We know that area of the square is 1 unit sq while that of circle is . Now for a very large number of generated points,
that is,
The beauty of this algorithm is that we don’t need any graphics or simulation to display the generated points. We simply generate random (x, y) pairs and then check if . If yes, we increment the number of points that appears inside the circle. In randomized and simulation algorithms like Monte Carlo, the more the number of iterations, the more accurate the result is. Thus, the title is “Estimating the value of Pi” and not “Calculating the value of Pi”. Below is the algorithm for the method:The Algorithm 1. Initialize circle_points, square_points and interval to 0. 2. Generate random point x. 3. Generate random point y. 4. Calculate d = x*x + y*y. 5. If d <= 1, increment circle_points. 6. Increment square_points. 7. Increment interval. 8. If increment < NO_OF_ITERATIONS, repeat from 2. 9. Calculate pi = 4*(circle_points/square_points). 10. Terminate.The code doesn’t wait for any input via stdin as the macro INTERVAL could be changed as per the required number of iterations. Number of iterations are the square of INTERVAL. Also, I’ve paused the screen for first 10 iterations with getch() and outputs are displayed for every iteration with format given below. You can change or delete them as per requirement.
x y circle_points square_points - pi
Examples:
INTERVAL = 5
Output : Final Estimation of Pi = 2.56
INTERVAL = 10
Output : Final Estimation of Pi = 3.24
INTERVAL = 100
Output : Final Estimation of Pi = 3.0916
C++
Python
/* C++ program for estimation of Pi using Monte Carlo Simulation */#include <bits/stdc++.h> // Defines precision for x and y values. More the// interval, more the number of significant digits#define INTERVAL 10000using namespace std; int main(){ int interval, i; double rand_x, rand_y, origin_dist, pi; int circle_points = 0, square_points = 0; // Initializing rand() srand(time(NULL)); // Total Random numbers generated = possible x // values * possible y values for (i = 0; i < (INTERVAL * INTERVAL); i++) { // Randomly generated x and y values rand_x = double(rand() % (INTERVAL + 1)) / INTERVAL; rand_y = double(rand() % (INTERVAL + 1)) / INTERVAL; // Distance between (x, y) from the origin origin_dist = rand_x * rand_x + rand_y * rand_y; // Checking if (x, y) lies inside the define // circle with R=1 if (origin_dist <= 1) circle_points++; // Total number of points generated square_points++; // estimated pi after this iteration pi = double(4 * circle_points) / square_points; // For visual understanding (Optional) cout << rand_x << " " << rand_y << " " << circle_points << " " << square_points << " - " << pi << endl << endl; // Pausing estimation for first 10 values (Optional) if (i < 20) getchar(); } // Final Estimated Value cout << "\nFinal Estimation of Pi = " << pi; return 0;}
import random INTERVAL= 1000 circle_points= 0square_points= 0 # Total Random numbers generated= possible x# values* possible y valuesfor i in range(INTERVAL**2): # Randomly generated x and y values from a # uniform distribution # Range of x and y values is -1 to 1 rand_x= random.uniform(-1, 1) rand_y= random.uniform(-1, 1) # Distance between (x, y) from the origin origin_dist= rand_x**2 + rand_y**2 # Checking if (x, y) lies inside the circle if origin_dist<= 1: circle_points+= 1 square_points+= 1 # Estimating value of pi, # pi= 4*(no. of points generated inside the # circle)/ (no. of points generated inside the square) pi = 4* circle_points/ square_points ## print(rand_x, rand_y, circle_points, square_points, "-", pi)## print("\n") print("Final Estimation of Pi=", pi)
Output:
Final Estimation of Pi = 3.16116
YouTubeParas Lehana70 subscribersEstimation of Pi | Monte Carlo Simulation - 1 Million Points | C/C++ Code DemoWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:26•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=iu4LsqUtfh0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Paras Lehana. 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.
MohitBansal3
simmytarika5
Mathematical
Randomized
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Sieve of Eratosthenes
QuickSort using Random Pivoting
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle a given array using Fisher–Yates shuffle Algorithm
Shuffle or Randomize a list in Java
Random Walk (Implementation in Python)
|
[
{
"code": null,
"e": 24423,
"s": 24395,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25025,
"s": 24423,
"text": "Monte Carlo estimation Monte Carlo methods are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results. One of the basic examples of getting started with the Monte Carlo algorithm is the estimation of Pi. Estimation of Pi The idea is to simulate random (x, y) points in a 2-D plane with domain as a square of side 1 unit. Imagine a circle inside the same domain with same diameter and inscribed into the square. We then calculate the ratio of number points that lied inside the circle and total number of generated points. Refer to the image below: "
},
{
"code": null,
"e": 25104,
"s": 25025,
"text": "Random points are generated only few of which lie outside the imaginary circle"
},
{
"code": null,
"e": 25226,
"s": 25104,
"text": "We know that area of the square is 1 unit sq while that of circle is . Now for a very large number of generated points, "
},
{
"code": null,
"e": 25237,
"s": 25226,
"text": "\nthat is,\n"
},
{
"code": null,
"e": 26463,
"s": 25237,
"text": "The beauty of this algorithm is that we don’t need any graphics or simulation to display the generated points. We simply generate random (x, y) pairs and then check if . If yes, we increment the number of points that appears inside the circle. In randomized and simulation algorithms like Monte Carlo, the more the number of iterations, the more accurate the result is. Thus, the title is “Estimating the value of Pi” and not “Calculating the value of Pi”. Below is the algorithm for the method:The Algorithm 1. Initialize circle_points, square_points and interval to 0. 2. Generate random point x. 3. Generate random point y. 4. Calculate d = x*x + y*y. 5. If d <= 1, increment circle_points. 6. Increment square_points. 7. Increment interval. 8. If increment < NO_OF_ITERATIONS, repeat from 2. 9. Calculate pi = 4*(circle_points/square_points). 10. Terminate.The code doesn’t wait for any input via stdin as the macro INTERVAL could be changed as per the required number of iterations. Number of iterations are the square of INTERVAL. Also, I’ve paused the screen for first 10 iterations with getch() and outputs are displayed for every iteration with format given below. You can change or delete them as per requirement. "
},
{
"code": null,
"e": 26501,
"s": 26463,
"text": "x y circle_points square_points - pi "
},
{
"code": null,
"e": 26511,
"s": 26501,
"text": "Examples:"
},
{
"code": null,
"e": 26674,
"s": 26511,
"text": "INTERVAL = 5\nOutput : Final Estimation of Pi = 2.56\n\nINTERVAL = 10\nOutput : Final Estimation of Pi = 3.24\n\nINTERVAL = 100\nOutput : Final Estimation of Pi = 3.0916"
},
{
"code": null,
"e": 26678,
"s": 26674,
"text": "C++"
},
{
"code": null,
"e": 26685,
"s": 26678,
"text": "Python"
},
{
"code": "/* C++ program for estimation of Pi using Monte Carlo Simulation */#include <bits/stdc++.h> // Defines precision for x and y values. More the// interval, more the number of significant digits#define INTERVAL 10000using namespace std; int main(){ int interval, i; double rand_x, rand_y, origin_dist, pi; int circle_points = 0, square_points = 0; // Initializing rand() srand(time(NULL)); // Total Random numbers generated = possible x // values * possible y values for (i = 0; i < (INTERVAL * INTERVAL); i++) { // Randomly generated x and y values rand_x = double(rand() % (INTERVAL + 1)) / INTERVAL; rand_y = double(rand() % (INTERVAL + 1)) / INTERVAL; // Distance between (x, y) from the origin origin_dist = rand_x * rand_x + rand_y * rand_y; // Checking if (x, y) lies inside the define // circle with R=1 if (origin_dist <= 1) circle_points++; // Total number of points generated square_points++; // estimated pi after this iteration pi = double(4 * circle_points) / square_points; // For visual understanding (Optional) cout << rand_x << \" \" << rand_y << \" \" << circle_points << \" \" << square_points << \" - \" << pi << endl << endl; // Pausing estimation for first 10 values (Optional) if (i < 20) getchar(); } // Final Estimated Value cout << \"\\nFinal Estimation of Pi = \" << pi; return 0;}",
"e": 28189,
"s": 26685,
"text": null
},
{
"code": "import random INTERVAL= 1000 circle_points= 0square_points= 0 # Total Random numbers generated= possible x# values* possible y valuesfor i in range(INTERVAL**2): # Randomly generated x and y values from a # uniform distribution # Range of x and y values is -1 to 1 rand_x= random.uniform(-1, 1) rand_y= random.uniform(-1, 1) # Distance between (x, y) from the origin origin_dist= rand_x**2 + rand_y**2 # Checking if (x, y) lies inside the circle if origin_dist<= 1: circle_points+= 1 square_points+= 1 # Estimating value of pi, # pi= 4*(no. of points generated inside the # circle)/ (no. of points generated inside the square) pi = 4* circle_points/ square_points ## print(rand_x, rand_y, circle_points, square_points, \"-\", pi)## print(\"\\n\") print(\"Final Estimation of Pi=\", pi) ",
"e": 29043,
"s": 28189,
"text": null
},
{
"code": null,
"e": 29053,
"s": 29043,
"text": "Output: "
},
{
"code": null,
"e": 29086,
"s": 29053,
"text": "Final Estimation of Pi = 3.16116"
},
{
"code": null,
"e": 30364,
"s": 29086,
"text": "YouTubeParas Lehana70 subscribersEstimation of Pi | Monte Carlo Simulation - 1 Million Points | C/C++ Code DemoWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:26•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=iu4LsqUtfh0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Paras Lehana. 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": 30377,
"s": 30364,
"text": "MohitBansal3"
},
{
"code": null,
"e": 30390,
"s": 30377,
"text": "simmytarika5"
},
{
"code": null,
"e": 30403,
"s": 30390,
"text": "Mathematical"
},
{
"code": null,
"e": 30414,
"s": 30403,
"text": "Randomized"
},
{
"code": null,
"e": 30427,
"s": 30414,
"text": "Mathematical"
},
{
"code": null,
"e": 30525,
"s": 30427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30534,
"s": 30525,
"text": "Comments"
},
{
"code": null,
"e": 30547,
"s": 30534,
"text": "Old Comments"
},
{
"code": null,
"e": 30571,
"s": 30547,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30613,
"s": 30571,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 30627,
"s": 30613,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30670,
"s": 30627,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30692,
"s": 30670,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 30724,
"s": 30692,
"text": "QuickSort using Random Pivoting"
},
{
"code": null,
"e": 30803,
"s": 30724,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)"
},
{
"code": null,
"e": 30862,
"s": 30803,
"text": "Shuffle a given array using Fisher–Yates shuffle Algorithm"
},
{
"code": null,
"e": 30898,
"s": 30862,
"text": "Shuffle or Randomize a list in Java"
}
] |
Find N distinct numbers whose bitwise Or is equal to K in Python
|
Suppose we have two integers N and K; we have to find N unique values whose bit-wise OR is same as K. If there is no such result, then return -1
So, if the input is like N = 4 and K = 6, then the output will be [6,0,1,2].
To solve this, we will follow these steps −
MAX := 32
MAX := 32
visited := a list of size MAX and fill with False
visited := a list of size MAX and fill with False
res := a new list
res := a new list
Define a function add() . This will take num
Define a function add() . This will take num
point := 0
point := 0
value := 0
value := 0
for i in range 0 to MAX, doif visited[i] is non-zero, thengo for next iterationotherwise,if num AND 1 is non-zero, thenvalue := value +(2^i)num := num/2 (take only integer part)
for i in range 0 to MAX, do
if visited[i] is non-zero, thengo for next iteration
if visited[i] is non-zero, then
go for next iteration
go for next iteration
otherwise,if num AND 1 is non-zero, thenvalue := value +(2^i)num := num/2 (take only integer part)
otherwise,
if num AND 1 is non-zero, thenvalue := value +(2^i)
if num AND 1 is non-zero, then
value := value +(2^i)
value := value +(2^i)
num := num/2 (take only integer part)
num := num/2 (take only integer part)
insert value at the end of res
insert value at the end of res
From the main method, do the following −
From the main method, do the following −
pow2 := an array of power of 2 from 2^0 to 2^31
pow2 := an array of power of 2 from 2^0 to 2^31
insert k at the end of res
insert k at the end of res
cnt_k := number of bits in k
cnt_k := number of bits in k
if pow2[cnt_k] < n, thenreturn -1
if pow2[cnt_k] < n, then
return -1
return -1
count := 0
count := 0
for i in range 0 to pow2[cnt_k] - 1, doadd(i)count := count + 1if count is same as n, thencome out from the loop
for i in range 0 to pow2[cnt_k] - 1, do
add(i)
add(i)
count := count + 1
count := count + 1
if count is same as n, thencome out from the loop
if count is same as n, then
come out from the loop
come out from the loop
return res
return res
Let us see the following implementation to get better understanding −
Live Demo
MAX = 32
visited = [False for i in range(MAX)]
res = []
def set_bit_count(n):
if (n == 0):
return 0
else:
return (n & 1) + set_bit_count(n >> 1)
def add(num):
point = 0
value = 0
for i in range(MAX):
if (visited[i]):
continue
else:
if (num & 1):
value += (1 << i)
num = num//2
res.append(value)
def solve(n, k):
pow2 = [2**i for i in range(MAX)]
res.append(k)
cnt_k = set_bit_count(k)
if (pow2[cnt_k] < n):
return -1
count = 0
for i in range(pow2[cnt_k] - 1):
add(i)
count += 1
if (count == n):
break
return res
n = 4
k = 6
print(solve(n, k))
4, 6
[6, 0, 1, 2]
|
[
{
"code": null,
"e": 1207,
"s": 1062,
"text": "Suppose we have two integers N and K; we have to find N unique values whose bit-wise OR is same as K. If there is no such result, then return -1"
},
{
"code": null,
"e": 1284,
"s": 1207,
"text": "So, if the input is like N = 4 and K = 6, then the output will be [6,0,1,2]."
},
{
"code": null,
"e": 1328,
"s": 1284,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1338,
"s": 1328,
"text": "MAX := 32"
},
{
"code": null,
"e": 1348,
"s": 1338,
"text": "MAX := 32"
},
{
"code": null,
"e": 1398,
"s": 1348,
"text": "visited := a list of size MAX and fill with False"
},
{
"code": null,
"e": 1448,
"s": 1398,
"text": "visited := a list of size MAX and fill with False"
},
{
"code": null,
"e": 1466,
"s": 1448,
"text": "res := a new list"
},
{
"code": null,
"e": 1484,
"s": 1466,
"text": "res := a new list"
},
{
"code": null,
"e": 1529,
"s": 1484,
"text": "Define a function add() . This will take num"
},
{
"code": null,
"e": 1574,
"s": 1529,
"text": "Define a function add() . This will take num"
},
{
"code": null,
"e": 1585,
"s": 1574,
"text": "point := 0"
},
{
"code": null,
"e": 1596,
"s": 1585,
"text": "point := 0"
},
{
"code": null,
"e": 1607,
"s": 1596,
"text": "value := 0"
},
{
"code": null,
"e": 1618,
"s": 1607,
"text": "value := 0"
},
{
"code": null,
"e": 1796,
"s": 1618,
"text": "for i in range 0 to MAX, doif visited[i] is non-zero, thengo for next iterationotherwise,if num AND 1 is non-zero, thenvalue := value +(2^i)num := num/2 (take only integer part)"
},
{
"code": null,
"e": 1824,
"s": 1796,
"text": "for i in range 0 to MAX, do"
},
{
"code": null,
"e": 1877,
"s": 1824,
"text": "if visited[i] is non-zero, thengo for next iteration"
},
{
"code": null,
"e": 1909,
"s": 1877,
"text": "if visited[i] is non-zero, then"
},
{
"code": null,
"e": 1931,
"s": 1909,
"text": "go for next iteration"
},
{
"code": null,
"e": 1953,
"s": 1931,
"text": "go for next iteration"
},
{
"code": null,
"e": 2052,
"s": 1953,
"text": "otherwise,if num AND 1 is non-zero, thenvalue := value +(2^i)num := num/2 (take only integer part)"
},
{
"code": null,
"e": 2063,
"s": 2052,
"text": "otherwise,"
},
{
"code": null,
"e": 2115,
"s": 2063,
"text": "if num AND 1 is non-zero, thenvalue := value +(2^i)"
},
{
"code": null,
"e": 2146,
"s": 2115,
"text": "if num AND 1 is non-zero, then"
},
{
"code": null,
"e": 2168,
"s": 2146,
"text": "value := value +(2^i)"
},
{
"code": null,
"e": 2190,
"s": 2168,
"text": "value := value +(2^i)"
},
{
"code": null,
"e": 2228,
"s": 2190,
"text": "num := num/2 (take only integer part)"
},
{
"code": null,
"e": 2266,
"s": 2228,
"text": "num := num/2 (take only integer part)"
},
{
"code": null,
"e": 2297,
"s": 2266,
"text": "insert value at the end of res"
},
{
"code": null,
"e": 2328,
"s": 2297,
"text": "insert value at the end of res"
},
{
"code": null,
"e": 2369,
"s": 2328,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 2410,
"s": 2369,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 2458,
"s": 2410,
"text": "pow2 := an array of power of 2 from 2^0 to 2^31"
},
{
"code": null,
"e": 2506,
"s": 2458,
"text": "pow2 := an array of power of 2 from 2^0 to 2^31"
},
{
"code": null,
"e": 2533,
"s": 2506,
"text": "insert k at the end of res"
},
{
"code": null,
"e": 2560,
"s": 2533,
"text": "insert k at the end of res"
},
{
"code": null,
"e": 2589,
"s": 2560,
"text": "cnt_k := number of bits in k"
},
{
"code": null,
"e": 2618,
"s": 2589,
"text": "cnt_k := number of bits in k"
},
{
"code": null,
"e": 2652,
"s": 2618,
"text": "if pow2[cnt_k] < n, thenreturn -1"
},
{
"code": null,
"e": 2677,
"s": 2652,
"text": "if pow2[cnt_k] < n, then"
},
{
"code": null,
"e": 2687,
"s": 2677,
"text": "return -1"
},
{
"code": null,
"e": 2697,
"s": 2687,
"text": "return -1"
},
{
"code": null,
"e": 2708,
"s": 2697,
"text": "count := 0"
},
{
"code": null,
"e": 2719,
"s": 2708,
"text": "count := 0"
},
{
"code": null,
"e": 2832,
"s": 2719,
"text": "for i in range 0 to pow2[cnt_k] - 1, doadd(i)count := count + 1if count is same as n, thencome out from the loop"
},
{
"code": null,
"e": 2872,
"s": 2832,
"text": "for i in range 0 to pow2[cnt_k] - 1, do"
},
{
"code": null,
"e": 2879,
"s": 2872,
"text": "add(i)"
},
{
"code": null,
"e": 2886,
"s": 2879,
"text": "add(i)"
},
{
"code": null,
"e": 2905,
"s": 2886,
"text": "count := count + 1"
},
{
"code": null,
"e": 2924,
"s": 2905,
"text": "count := count + 1"
},
{
"code": null,
"e": 2974,
"s": 2924,
"text": "if count is same as n, thencome out from the loop"
},
{
"code": null,
"e": 3002,
"s": 2974,
"text": "if count is same as n, then"
},
{
"code": null,
"e": 3025,
"s": 3002,
"text": "come out from the loop"
},
{
"code": null,
"e": 3048,
"s": 3025,
"text": "come out from the loop"
},
{
"code": null,
"e": 3059,
"s": 3048,
"text": "return res"
},
{
"code": null,
"e": 3070,
"s": 3059,
"text": "return res"
},
{
"code": null,
"e": 3140,
"s": 3070,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3151,
"s": 3140,
"text": " Live Demo"
},
{
"code": null,
"e": 3830,
"s": 3151,
"text": "MAX = 32\nvisited = [False for i in range(MAX)]\nres = []\ndef set_bit_count(n):\n if (n == 0):\n return 0\n else:\n return (n & 1) + set_bit_count(n >> 1)\ndef add(num):\n point = 0\n value = 0\n for i in range(MAX):\n if (visited[i]):\n continue\n else:\n if (num & 1):\n value += (1 << i)\n num = num//2\n res.append(value)\ndef solve(n, k):\n pow2 = [2**i for i in range(MAX)]\n res.append(k)\n cnt_k = set_bit_count(k)\n if (pow2[cnt_k] < n):\n return -1\n count = 0\n for i in range(pow2[cnt_k] - 1):\n add(i)\n count += 1\n if (count == n):\n break\n return res\n\nn = 4\nk = 6\nprint(solve(n, k))"
},
{
"code": null,
"e": 3835,
"s": 3830,
"text": "4, 6"
},
{
"code": null,
"e": 3848,
"s": 3835,
"text": "[6, 0, 1, 2]"
}
] |
concat(), replace(), and trim() Strings in Java.
|
The concat() method of the String class appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
s = s.concat(" all the time");
System.out.println(s);
}
}
Strings are immutable all the time
This replace() method of the String class returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
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'));
}
}
Return Value :WelcTme tT TutTrialspTint.cTm
Return Value :WeDcome to TutoriaDspoint.com
This trim() method of the String class returns a copy of the string, with leading and trailing whitespace omitted.
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.trim() );
}
}
Return Value :Welcome to Tutorialspoint.com
|
[
{
"code": null,
"e": 1288,
"s": 1062,
"text": "The concat() method of the String class appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method."
},
{
"code": null,
"e": 1467,
"s": 1288,
"text": "public class Test {\n public static void main(String args[]) {\n String s = \"Strings are immutable\";\n s = s.concat(\" all the time\");\n System.out.println(s);\n }\n}"
},
{
"code": null,
"e": 1502,
"s": 1467,
"text": "Strings are immutable all the time"
},
{
"code": null,
"e": 1646,
"s": 1502,
"text": "This replace() method of the String class returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."
},
{
"code": null,
"e": 1965,
"s": 1646,
"text": "public class Test {\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n System.out.print(\"Return Value :\" );\n System.out.println(Str.replace('o', 'T'));\n System.out.print(\"Return Value :\" );\n System.out.println(Str.replace('l', 'D'));\n }\n}"
},
{
"code": null,
"e": 2053,
"s": 1965,
"text": "Return Value :WelcTme tT TutTrialspTint.cTm\nReturn Value :WeDcome to TutoriaDspoint.com"
},
{
"code": null,
"e": 2168,
"s": 2053,
"text": "This trim() method of the String class returns a copy of the string, with leading and trailing whitespace omitted."
},
{
"code": null,
"e": 2405,
"s": 2168,
"text": "import java.io.*;\npublic class Test {\n public static void main(String args[]) {\n String Str = new String(\" Welcome to Tutorialspoint.com \");\n System.out.print(\"Return Value :\" );\n System.out.println(Str.trim() );\n }\n}"
},
{
"code": null,
"e": 2449,
"s": 2405,
"text": "Return Value :Welcome to Tutorialspoint.com"
}
] |
Special Binary String in C++
|
Suppose we have a spatial binary string. This string has following few properties −
There are same number of 0s and 1s
There are same number of 0s and 1s
Every Prefix in the binary string has at least as many 1s as 0s
Every Prefix in the binary string has at least as many 1s as 0s
Now suppose we have special string S, a move is actually choosing two consecutive, non-empty, special substrings of S, and swapping them.
We have to find the lexicographically largest resulting string possible, at the end of any number of moves.
So, if the input is like 11011000, then the output will be 11100100, this is because: The substrings "10" and "1100" are swapped. This is the lexicographically largest string possible after few moves.
To solve this, we will follow these steps −
Define a function makeLargestSpecial(), this will take s,
Define a function makeLargestSpecial(), this will take s,
ret := empty string
ret := empty string
Define an array v of strings
Define an array v of strings
i := 0
i := 0
for initialize j := 0, cnt := 0, when j < size of s, update (increase j by 1), do −if s[j] is same as '1', then −(increase cnt by 1)Otherwise(decrease cnt by 1)if cnt is same as 0, then −insert "1" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of vi := j + 1
for initialize j := 0, cnt := 0, when j < size of s, update (increase j by 1), do −
if s[j] is same as '1', then −(increase cnt by 1)
if s[j] is same as '1', then −
(increase cnt by 1)
(increase cnt by 1)
Otherwise(decrease cnt by 1)
Otherwise
(decrease cnt by 1)
(decrease cnt by 1)
if cnt is same as 0, then −insert "1" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of vi := j + 1
if cnt is same as 0, then −
insert "1" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of v
insert "1" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of v
i := j + 1
i := j + 1
sort the array v.r
sort the array v.r
for initialize i := 0, when i < size of v, update (increase i by 1), do −ret := ret + v[i]
for initialize i := 0, when i < size of v, update (increase i by 1), do −
ret := ret + v[i]
ret := ret + v[i]
return ret
return ret
From the main method call makeLargestSpecial() with the string.
From the main method call makeLargestSpecial() with the string.
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string makeLargestSpecial(string s) {
string ret = "";
vector<string> v;
int i = 0;
for (int j = 0, cnt = 0; j < s.size(); j++) {
if (s[j] == '1') {
cnt++;
}
else
cnt--;
if (cnt == 0) {
v.push_back("1" + makeLargestSpecial(s.substr(i + 1,
j - i - 1)) + "0");
i = j + 1;
}
}
sort(v.rbegin(), v.rend());
for (int i = 0; i < v.size(); i++)
ret += v[i];
return ret;
}
};
main(){
Solution ob;
cout << (ob.makeLargestSpecial("11011000"));
}
11011000
11100100
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "Suppose we have a spatial binary string. This string has following few properties −"
},
{
"code": null,
"e": 1181,
"s": 1146,
"text": "There are same number of 0s and 1s"
},
{
"code": null,
"e": 1216,
"s": 1181,
"text": "There are same number of 0s and 1s"
},
{
"code": null,
"e": 1280,
"s": 1216,
"text": "Every Prefix in the binary string has at least as many 1s as 0s"
},
{
"code": null,
"e": 1344,
"s": 1280,
"text": "Every Prefix in the binary string has at least as many 1s as 0s"
},
{
"code": null,
"e": 1482,
"s": 1344,
"text": "Now suppose we have special string S, a move is actually choosing two consecutive, non-empty, special substrings of S, and swapping them."
},
{
"code": null,
"e": 1590,
"s": 1482,
"text": "We have to find the lexicographically largest resulting string possible, at the end of any number of moves."
},
{
"code": null,
"e": 1791,
"s": 1590,
"text": "So, if the input is like 11011000, then the output will be 11100100, this is because: The substrings \"10\" and \"1100\" are swapped. This is the lexicographically largest string possible after few moves."
},
{
"code": null,
"e": 1835,
"s": 1791,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1893,
"s": 1835,
"text": "Define a function makeLargestSpecial(), this will take s,"
},
{
"code": null,
"e": 1951,
"s": 1893,
"text": "Define a function makeLargestSpecial(), this will take s,"
},
{
"code": null,
"e": 1971,
"s": 1951,
"text": "ret := empty string"
},
{
"code": null,
"e": 1991,
"s": 1971,
"text": "ret := empty string"
},
{
"code": null,
"e": 2020,
"s": 1991,
"text": "Define an array v of strings"
},
{
"code": null,
"e": 2049,
"s": 2020,
"text": "Define an array v of strings"
},
{
"code": null,
"e": 2056,
"s": 2049,
"text": "i := 0"
},
{
"code": null,
"e": 2063,
"s": 2056,
"text": "i := 0"
},
{
"code": null,
"e": 2354,
"s": 2063,
"text": "for initialize j := 0, cnt := 0, when j < size of s, update (increase j by 1), do −if s[j] is same as '1', then −(increase cnt by 1)Otherwise(decrease cnt by 1)if cnt is same as 0, then −insert \"1\" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of vi := j + 1"
},
{
"code": null,
"e": 2438,
"s": 2354,
"text": "for initialize j := 0, cnt := 0, when j < size of s, update (increase j by 1), do −"
},
{
"code": null,
"e": 2488,
"s": 2438,
"text": "if s[j] is same as '1', then −(increase cnt by 1)"
},
{
"code": null,
"e": 2519,
"s": 2488,
"text": "if s[j] is same as '1', then −"
},
{
"code": null,
"e": 2539,
"s": 2519,
"text": "(increase cnt by 1)"
},
{
"code": null,
"e": 2559,
"s": 2539,
"text": "(increase cnt by 1)"
},
{
"code": null,
"e": 2588,
"s": 2559,
"text": "Otherwise(decrease cnt by 1)"
},
{
"code": null,
"e": 2598,
"s": 2588,
"text": "Otherwise"
},
{
"code": null,
"e": 2618,
"s": 2598,
"text": "(decrease cnt by 1)"
},
{
"code": null,
"e": 2638,
"s": 2618,
"text": "(decrease cnt by 1)"
},
{
"code": null,
"e": 2769,
"s": 2638,
"text": "if cnt is same as 0, then −insert \"1\" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of vi := j + 1"
},
{
"code": null,
"e": 2797,
"s": 2769,
"text": "if cnt is same as 0, then −"
},
{
"code": null,
"e": 2891,
"s": 2797,
"text": "insert \"1\" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of v"
},
{
"code": null,
"e": 2985,
"s": 2891,
"text": "insert \"1\" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of v"
},
{
"code": null,
"e": 2996,
"s": 2985,
"text": "i := j + 1"
},
{
"code": null,
"e": 3007,
"s": 2996,
"text": "i := j + 1"
},
{
"code": null,
"e": 3026,
"s": 3007,
"text": "sort the array v.r"
},
{
"code": null,
"e": 3045,
"s": 3026,
"text": "sort the array v.r"
},
{
"code": null,
"e": 3136,
"s": 3045,
"text": "for initialize i := 0, when i < size of v, update (increase i by 1), do −ret := ret + v[i]"
},
{
"code": null,
"e": 3210,
"s": 3136,
"text": "for initialize i := 0, when i < size of v, update (increase i by 1), do −"
},
{
"code": null,
"e": 3228,
"s": 3210,
"text": "ret := ret + v[i]"
},
{
"code": null,
"e": 3246,
"s": 3228,
"text": "ret := ret + v[i]"
},
{
"code": null,
"e": 3257,
"s": 3246,
"text": "return ret"
},
{
"code": null,
"e": 3268,
"s": 3257,
"text": "return ret"
},
{
"code": null,
"e": 3332,
"s": 3268,
"text": "From the main method call makeLargestSpecial() with the string."
},
{
"code": null,
"e": 3396,
"s": 3332,
"text": "From the main method call makeLargestSpecial() with the string."
},
{
"code": null,
"e": 3466,
"s": 3396,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3477,
"s": 3466,
"text": " Live Demo"
},
{
"code": null,
"e": 4154,
"s": 3477,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n string makeLargestSpecial(string s) {\n string ret = \"\";\n vector<string> v;\n int i = 0;\n for (int j = 0, cnt = 0; j < s.size(); j++) {\n if (s[j] == '1') {\n cnt++;\n }\n else\n cnt--;\n if (cnt == 0) {\n v.push_back(\"1\" + makeLargestSpecial(s.substr(i + 1,\n j - i - 1)) + \"0\");\n i = j + 1;\n }\n }\n sort(v.rbegin(), v.rend());\n for (int i = 0; i < v.size(); i++)\n ret += v[i];\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.makeLargestSpecial(\"11011000\"));\n}"
},
{
"code": null,
"e": 4163,
"s": 4154,
"text": "11011000"
},
{
"code": null,
"e": 4172,
"s": 4163,
"text": "11100100"
}
] |
Essential Math for Data Science: Basis and Change of Basis | by Hadrien Jean | Towards Data Science
|
In this article, you’ll learn about the concept of basis, which is an interesting way to understand matrix factorization methods like eigendecomposition or singular value decomposition (SVD).
The basis is a coordinate system used to describe vector spaces (sets of vectors). It is a reference that you use to associate numbers with geometric vectors.
To be considered as a basis, a set of vectors must:
Be linearly independent.
Span the space.
Every vector in the space is a unique combination of the basis vectors. The dimension of a space is defined to be the size of a basis set. For instance, there are two basis vectors in R2 (corresponding to the x and y-axis in the Cartesian plane), or three in R3.
As shown in section 7.4 of Essential Math for Data Science, if the number of vectors in a set is larger than the dimensions of the space, they can’t be linearly independent. If a set contains fewer vectors than the number of dimensions, these vectors can’t span the whole space.
Vectors can be represented as arrows going from the origin to a point in space. The coordinates of this point can be stored in a list. The geometric representation of a vector in the Cartesian plane implies that we take a reference: the directions given by the two axes x and y.
Basis vectors are the vectors corresponding to this reference. In the Cartesian plane, the basis vectors are orthogonal unit vectors (length of one), generally denoted as i and j.
For instance, in Figure 1, the basis vectors i and j point in the direction of the axis x and y respectively. These vectors give the standard basis. If you put these basis vectors into a matrix, you have the following identity matrix (for more details about identity matrices, see 6.4.3 in Essential Math for Data Science):
Thus, the columns of I2 span R2. In the same way, the columns of I3 span R3 and so on.
Orthogonal basis
Basis vectors can be orthogonal because orthogonal vectors are independent. However, the converse is not necessarily true: non-orthogonal vectors can be linearly independent and thus form a basis (but not a standard basis).
The basis of your vector space is very important because the values of the coordinates corresponding to the vectors depend on this basis. By the way, you can choose different basis vectors, like in the ones in Figure 2 for instance.
Keep in mind that vector coordinates depend on an implicit choice of basis vectors.
You can consider any vector in a vector space as a linear combination of the basis vectors.
For instance, take the following two-dimensional vector v:
The components of the vector v are the projections on the x-axis and on the y-axis ( v_x and v_y, as illustrated in Figure 3). The vector v corresponds to the sum of its components: v = v_x + v_y, and you can obtain these components by scaling the basis vectors: v_x = 2 i and v_y = -0.5 j. Thus, the vector v shown in Figure 3 can be considered as a linear combination of the two basis vectors i and j:
The columns of identity matrices are not the only case of linearly independent column vectors. It is possible to find other sets of n vectors linearly independent in Rn.
For instance, let’s consider the following vectors in R2:
and
From the definition above, the vectors v and w are a basis because they are linearly independent (you can’t obtain one of them from combinations of the other) and they span the space (all the space can be reached from the linear combinations of these vectors).
It is critical to keep in mind that, when you use the components of vectors (for instance v_x and v_y, the x and y components of the vector v), the values are relative to the basis you chose. If you use another basis, these values will be different.
You’ll see in Chapter 09 and 10 of Essential Math for Data Science that the ability to change the bases is fundamental in linear algebra and is key to understand eigendecomposition or Singular Value Decomposition.
You saw that to associate geometric vectors (arrows in the space) with coordinate vectors (arrays of numbers), you need a reference. This reference is the basis of your vector space. For this reason, a vector should always be defined with respect to a basis.
Let’s take the following vector:
The values of the x and y components are respectively 2 and -0.5. The standard basis is used when not specified.
You could write Iv to specify that these numbers correspond to coordinates with respect to the standard basis. In this case, I is called the change of basis matrix.
You can define vectors with respect to another basis by using another matrix than I.
Vector spaces (the set of possible vectors) are characterized in reference to a basis. The expression of a geometrical vector as an array of numbers implies that you choose a basis. With a different basis, the same vector v is associated with different numbers.
You saw that the basis is a set of linearly independent vectors that span the space. More precisely, a set of vectors is a basis if every vector from the space can be described as a finite linear combination of the components of the basis and if the set is linearly independent.
Consider the following two-dimensional vector:
In the R2 Cartesian plane, you can consider v as a linear combination of the standard basis vectors i and j, as shown in Figure 5.
But if you use another coordinate system, v is associated with new numbers. Figure 6 shows a representation of the vector v with a new coordinate system (i’ and j’).
In the new basis, v is a new set of numbers:
You can use a change of basis matrix to go from a basis to another. To find the matrix corresponding to new basis vectors, you can express these new basis vectors (i’ and j’) as coordinates in the old basis (i and j).
Let’s take again the preceding example. You have:
and
This is illustrated in Figure 7.
Since they are basis vectors, i’ and j’ can be expressed as linear combinations ofi and j.:
Let’s write these equations under the matrix form (more details about the matrix form of systems of equations in Chapter 08 of Essential Math for Data Science):
To have the basis vectors as columns, you need to transpose the matrices. You get:
This matrix is called the change of basis matrix. Let’s call it C:
As you can notice, each column of the change of basis matrix is a basis vector of the new basis. You’ll see next that you can use the change of basis matrix C to convert vectors from the output basis to the input basis.
Change of basis vs linear transformation
The difference between change of basis and linear transformation is conceptual. Sometimes it is useful to consider the effect of a matrix as a change of basis; sometimes you get more insights when you think of it as a linear transformation.
Either you move the vector or you move its reference. This is why rotating the coordinate system has an inverse effect compared to rotating the vector itself.
For eigendecomposition and SVD, both of these views are usually taken together, which can be confusing at first. Keeping this difference in mind will be useful throughout the end of the book.
The main technical difference between the two is that change of basis must be invertible, which is not required for linear transformations.
Finding the Change of Basis Matrix
A change of basis matrix maps an input basis to an output basis. Let’s call the input basis B1 with the basis vectors i and j, and the output basis B2 with the basis vectors i’ and j’. You have:
and
From the equation of the change of basis, you have:
If you want to find the change of basis matrix given B1 and B2, you need to calculate the inverse of B1 to isolate C:
In words, you can calculate the change of basis matrix by multiplying the inverse of the input basis matrix (B1^{-1}, which contains the input basis vectors as columns) by the output basis matrix (B2, which contains the output basis vectors as columns).
Be careful, this change of basis matrix allows you to convert vectors from B2 to B1 and not the opposite. Intuitively, this is because moving an object is the opposite to moving the reference. Thus, to go from B1 to B2, you must use the inverse of the change of basis matrix C^{-1}.
Note that if the input basis is the standard basis (B1=I), then the change of basis matrix is simply the output basis matrix:
Since the basis vectors are linearly independent, the columns of C are linearly independent, and thus, as stated in section 7.4 of Essential Math for Data Science, C is invertible.
Let’s change the basis of a vector v, using again the geometric vectors represented in Figure 6.
You’ll change the basis of v from the standard basis to a new basis. Let’s denote the standard basis as B1 and the new basis as B2. Remember that the basis is a matrix containing the basis vectors as columns. You have:
and
Let’s denote the vector v relative to the basis B1 as [v]B1:
The goal is to find the coordinates of v relative to the basis B2, denoted as [v]B2.
Square bracket notation
To distinguish the basis used to define a vector, you can put the basis name (like B1) in subscript after the vector name enclosed in square brackets. However, due to Medium subscript limitations, we’ll write for instance, [v]B1 in text to denote the vector v relative to the basis B1. It is also called the representation of v with respect to B1.
Let’s express the vector v as a linear combination of the input and output basis vectors:
The scalars c1 and c2 are weighting the linear combination of the input basis vectors, and the scalars d1 and d2 are weighting the linear combination of the output basis vectors. You can merge the two equations:
Now, let’s write this equation in matrix form:
The vector containing the scalars c1 and c2 corresponds to [v]B1 and the vector containing the scalars d1 and d2 corresponds to [v]B2. You have:
That’s good, this an equation with the term you want to find: [v]B2. You can isolate it by multiplying each side by B2^{-1}:
You have also:
The term B2^{-1} B1 is the inverse of B1^{-1} B2, which is the change of basis matrix C described before. This shows that C^{-1} allows you to convert vectors from an input basis B1 to an output basis B2 and C from B2 to B1.
In the context of this example, since B1 is the standard basis, it simplifies to:
This means that, applying the matrix B2 ^{-1} to [v]B_1 allows you to change its basis to B2.
Let’s code this:
array([ 0.86757991, -1.00456621])
These values are the coordinates of the vector v relative to the basis B2. This means that if you go to 0.86757991 i’ — 1.00456621 j’ you arrive to the position (2, 1) in the standard basis, as illustrated in Figure 6.
Conclusion
Understanding the concept of basis is a nice way to approach matrix decomposition (also called matrix factorization), like eigendecomposition or singular value decomposition (SVD). In these terms, you can think of matrix decomposition as finding a basis where the matrix associated with a transformation has specific properties: the factorization is a change of basis matrix, the new transformation matrix, and finally the inverse of the change of basis matrix to come back into the initial basis (more details in Chapter 09 and 10 of Essential Math for Data Science).
This post is a sample of my book Essential Math for Data Science!
Get the book here: https://bit.ly/2WVf4CR!
|
[
{
"code": null,
"e": 363,
"s": 171,
"text": "In this article, you’ll learn about the concept of basis, which is an interesting way to understand matrix factorization methods like eigendecomposition or singular value decomposition (SVD)."
},
{
"code": null,
"e": 522,
"s": 363,
"text": "The basis is a coordinate system used to describe vector spaces (sets of vectors). It is a reference that you use to associate numbers with geometric vectors."
},
{
"code": null,
"e": 574,
"s": 522,
"text": "To be considered as a basis, a set of vectors must:"
},
{
"code": null,
"e": 599,
"s": 574,
"text": "Be linearly independent."
},
{
"code": null,
"e": 615,
"s": 599,
"text": "Span the space."
},
{
"code": null,
"e": 878,
"s": 615,
"text": "Every vector in the space is a unique combination of the basis vectors. The dimension of a space is defined to be the size of a basis set. For instance, there are two basis vectors in R2 (corresponding to the x and y-axis in the Cartesian plane), or three in R3."
},
{
"code": null,
"e": 1157,
"s": 878,
"text": "As shown in section 7.4 of Essential Math for Data Science, if the number of vectors in a set is larger than the dimensions of the space, they can’t be linearly independent. If a set contains fewer vectors than the number of dimensions, these vectors can’t span the whole space."
},
{
"code": null,
"e": 1436,
"s": 1157,
"text": "Vectors can be represented as arrows going from the origin to a point in space. The coordinates of this point can be stored in a list. The geometric representation of a vector in the Cartesian plane implies that we take a reference: the directions given by the two axes x and y."
},
{
"code": null,
"e": 1616,
"s": 1436,
"text": "Basis vectors are the vectors corresponding to this reference. In the Cartesian plane, the basis vectors are orthogonal unit vectors (length of one), generally denoted as i and j."
},
{
"code": null,
"e": 1940,
"s": 1616,
"text": "For instance, in Figure 1, the basis vectors i and j point in the direction of the axis x and y respectively. These vectors give the standard basis. If you put these basis vectors into a matrix, you have the following identity matrix (for more details about identity matrices, see 6.4.3 in Essential Math for Data Science):"
},
{
"code": null,
"e": 2027,
"s": 1940,
"text": "Thus, the columns of I2 span R2. In the same way, the columns of I3 span R3 and so on."
},
{
"code": null,
"e": 2044,
"s": 2027,
"text": "Orthogonal basis"
},
{
"code": null,
"e": 2268,
"s": 2044,
"text": "Basis vectors can be orthogonal because orthogonal vectors are independent. However, the converse is not necessarily true: non-orthogonal vectors can be linearly independent and thus form a basis (but not a standard basis)."
},
{
"code": null,
"e": 2501,
"s": 2268,
"text": "The basis of your vector space is very important because the values of the coordinates corresponding to the vectors depend on this basis. By the way, you can choose different basis vectors, like in the ones in Figure 2 for instance."
},
{
"code": null,
"e": 2585,
"s": 2501,
"text": "Keep in mind that vector coordinates depend on an implicit choice of basis vectors."
},
{
"code": null,
"e": 2677,
"s": 2585,
"text": "You can consider any vector in a vector space as a linear combination of the basis vectors."
},
{
"code": null,
"e": 2736,
"s": 2677,
"text": "For instance, take the following two-dimensional vector v:"
},
{
"code": null,
"e": 3140,
"s": 2736,
"text": "The components of the vector v are the projections on the x-axis and on the y-axis ( v_x and v_y, as illustrated in Figure 3). The vector v corresponds to the sum of its components: v = v_x + v_y, and you can obtain these components by scaling the basis vectors: v_x = 2 i and v_y = -0.5 j. Thus, the vector v shown in Figure 3 can be considered as a linear combination of the two basis vectors i and j:"
},
{
"code": null,
"e": 3310,
"s": 3140,
"text": "The columns of identity matrices are not the only case of linearly independent column vectors. It is possible to find other sets of n vectors linearly independent in Rn."
},
{
"code": null,
"e": 3368,
"s": 3310,
"text": "For instance, let’s consider the following vectors in R2:"
},
{
"code": null,
"e": 3372,
"s": 3368,
"text": "and"
},
{
"code": null,
"e": 3633,
"s": 3372,
"text": "From the definition above, the vectors v and w are a basis because they are linearly independent (you can’t obtain one of them from combinations of the other) and they span the space (all the space can be reached from the linear combinations of these vectors)."
},
{
"code": null,
"e": 3883,
"s": 3633,
"text": "It is critical to keep in mind that, when you use the components of vectors (for instance v_x and v_y, the x and y components of the vector v), the values are relative to the basis you chose. If you use another basis, these values will be different."
},
{
"code": null,
"e": 4097,
"s": 3883,
"text": "You’ll see in Chapter 09 and 10 of Essential Math for Data Science that the ability to change the bases is fundamental in linear algebra and is key to understand eigendecomposition or Singular Value Decomposition."
},
{
"code": null,
"e": 4356,
"s": 4097,
"text": "You saw that to associate geometric vectors (arrows in the space) with coordinate vectors (arrays of numbers), you need a reference. This reference is the basis of your vector space. For this reason, a vector should always be defined with respect to a basis."
},
{
"code": null,
"e": 4389,
"s": 4356,
"text": "Let’s take the following vector:"
},
{
"code": null,
"e": 4502,
"s": 4389,
"text": "The values of the x and y components are respectively 2 and -0.5. The standard basis is used when not specified."
},
{
"code": null,
"e": 4667,
"s": 4502,
"text": "You could write Iv to specify that these numbers correspond to coordinates with respect to the standard basis. In this case, I is called the change of basis matrix."
},
{
"code": null,
"e": 4752,
"s": 4667,
"text": "You can define vectors with respect to another basis by using another matrix than I."
},
{
"code": null,
"e": 5014,
"s": 4752,
"text": "Vector spaces (the set of possible vectors) are characterized in reference to a basis. The expression of a geometrical vector as an array of numbers implies that you choose a basis. With a different basis, the same vector v is associated with different numbers."
},
{
"code": null,
"e": 5293,
"s": 5014,
"text": "You saw that the basis is a set of linearly independent vectors that span the space. More precisely, a set of vectors is a basis if every vector from the space can be described as a finite linear combination of the components of the basis and if the set is linearly independent."
},
{
"code": null,
"e": 5340,
"s": 5293,
"text": "Consider the following two-dimensional vector:"
},
{
"code": null,
"e": 5471,
"s": 5340,
"text": "In the R2 Cartesian plane, you can consider v as a linear combination of the standard basis vectors i and j, as shown in Figure 5."
},
{
"code": null,
"e": 5637,
"s": 5471,
"text": "But if you use another coordinate system, v is associated with new numbers. Figure 6 shows a representation of the vector v with a new coordinate system (i’ and j’)."
},
{
"code": null,
"e": 5682,
"s": 5637,
"text": "In the new basis, v is a new set of numbers:"
},
{
"code": null,
"e": 5900,
"s": 5682,
"text": "You can use a change of basis matrix to go from a basis to another. To find the matrix corresponding to new basis vectors, you can express these new basis vectors (i’ and j’) as coordinates in the old basis (i and j)."
},
{
"code": null,
"e": 5950,
"s": 5900,
"text": "Let’s take again the preceding example. You have:"
},
{
"code": null,
"e": 5954,
"s": 5950,
"text": "and"
},
{
"code": null,
"e": 5987,
"s": 5954,
"text": "This is illustrated in Figure 7."
},
{
"code": null,
"e": 6079,
"s": 5987,
"text": "Since they are basis vectors, i’ and j’ can be expressed as linear combinations ofi and j.:"
},
{
"code": null,
"e": 6240,
"s": 6079,
"text": "Let’s write these equations under the matrix form (more details about the matrix form of systems of equations in Chapter 08 of Essential Math for Data Science):"
},
{
"code": null,
"e": 6323,
"s": 6240,
"text": "To have the basis vectors as columns, you need to transpose the matrices. You get:"
},
{
"code": null,
"e": 6390,
"s": 6323,
"text": "This matrix is called the change of basis matrix. Let’s call it C:"
},
{
"code": null,
"e": 6610,
"s": 6390,
"text": "As you can notice, each column of the change of basis matrix is a basis vector of the new basis. You’ll see next that you can use the change of basis matrix C to convert vectors from the output basis to the input basis."
},
{
"code": null,
"e": 6651,
"s": 6610,
"text": "Change of basis vs linear transformation"
},
{
"code": null,
"e": 6892,
"s": 6651,
"text": "The difference between change of basis and linear transformation is conceptual. Sometimes it is useful to consider the effect of a matrix as a change of basis; sometimes you get more insights when you think of it as a linear transformation."
},
{
"code": null,
"e": 7051,
"s": 6892,
"text": "Either you move the vector or you move its reference. This is why rotating the coordinate system has an inverse effect compared to rotating the vector itself."
},
{
"code": null,
"e": 7243,
"s": 7051,
"text": "For eigendecomposition and SVD, both of these views are usually taken together, which can be confusing at first. Keeping this difference in mind will be useful throughout the end of the book."
},
{
"code": null,
"e": 7383,
"s": 7243,
"text": "The main technical difference between the two is that change of basis must be invertible, which is not required for linear transformations."
},
{
"code": null,
"e": 7418,
"s": 7383,
"text": "Finding the Change of Basis Matrix"
},
{
"code": null,
"e": 7613,
"s": 7418,
"text": "A change of basis matrix maps an input basis to an output basis. Let’s call the input basis B1 with the basis vectors i and j, and the output basis B2 with the basis vectors i’ and j’. You have:"
},
{
"code": null,
"e": 7617,
"s": 7613,
"text": "and"
},
{
"code": null,
"e": 7669,
"s": 7617,
"text": "From the equation of the change of basis, you have:"
},
{
"code": null,
"e": 7787,
"s": 7669,
"text": "If you want to find the change of basis matrix given B1 and B2, you need to calculate the inverse of B1 to isolate C:"
},
{
"code": null,
"e": 8041,
"s": 7787,
"text": "In words, you can calculate the change of basis matrix by multiplying the inverse of the input basis matrix (B1^{-1}, which contains the input basis vectors as columns) by the output basis matrix (B2, which contains the output basis vectors as columns)."
},
{
"code": null,
"e": 8324,
"s": 8041,
"text": "Be careful, this change of basis matrix allows you to convert vectors from B2 to B1 and not the opposite. Intuitively, this is because moving an object is the opposite to moving the reference. Thus, to go from B1 to B2, you must use the inverse of the change of basis matrix C^{-1}."
},
{
"code": null,
"e": 8450,
"s": 8324,
"text": "Note that if the input basis is the standard basis (B1=I), then the change of basis matrix is simply the output basis matrix:"
},
{
"code": null,
"e": 8631,
"s": 8450,
"text": "Since the basis vectors are linearly independent, the columns of C are linearly independent, and thus, as stated in section 7.4 of Essential Math for Data Science, C is invertible."
},
{
"code": null,
"e": 8728,
"s": 8631,
"text": "Let’s change the basis of a vector v, using again the geometric vectors represented in Figure 6."
},
{
"code": null,
"e": 8947,
"s": 8728,
"text": "You’ll change the basis of v from the standard basis to a new basis. Let’s denote the standard basis as B1 and the new basis as B2. Remember that the basis is a matrix containing the basis vectors as columns. You have:"
},
{
"code": null,
"e": 8951,
"s": 8947,
"text": "and"
},
{
"code": null,
"e": 9012,
"s": 8951,
"text": "Let’s denote the vector v relative to the basis B1 as [v]B1:"
},
{
"code": null,
"e": 9097,
"s": 9012,
"text": "The goal is to find the coordinates of v relative to the basis B2, denoted as [v]B2."
},
{
"code": null,
"e": 9121,
"s": 9097,
"text": "Square bracket notation"
},
{
"code": null,
"e": 9469,
"s": 9121,
"text": "To distinguish the basis used to define a vector, you can put the basis name (like B1) in subscript after the vector name enclosed in square brackets. However, due to Medium subscript limitations, we’ll write for instance, [v]B1 in text to denote the vector v relative to the basis B1. It is also called the representation of v with respect to B1."
},
{
"code": null,
"e": 9559,
"s": 9469,
"text": "Let’s express the vector v as a linear combination of the input and output basis vectors:"
},
{
"code": null,
"e": 9771,
"s": 9559,
"text": "The scalars c1 and c2 are weighting the linear combination of the input basis vectors, and the scalars d1 and d2 are weighting the linear combination of the output basis vectors. You can merge the two equations:"
},
{
"code": null,
"e": 9818,
"s": 9771,
"text": "Now, let’s write this equation in matrix form:"
},
{
"code": null,
"e": 9963,
"s": 9818,
"text": "The vector containing the scalars c1 and c2 corresponds to [v]B1 and the vector containing the scalars d1 and d2 corresponds to [v]B2. You have:"
},
{
"code": null,
"e": 10088,
"s": 9963,
"text": "That’s good, this an equation with the term you want to find: [v]B2. You can isolate it by multiplying each side by B2^{-1}:"
},
{
"code": null,
"e": 10103,
"s": 10088,
"text": "You have also:"
},
{
"code": null,
"e": 10328,
"s": 10103,
"text": "The term B2^{-1} B1 is the inverse of B1^{-1} B2, which is the change of basis matrix C described before. This shows that C^{-1} allows you to convert vectors from an input basis B1 to an output basis B2 and C from B2 to B1."
},
{
"code": null,
"e": 10410,
"s": 10328,
"text": "In the context of this example, since B1 is the standard basis, it simplifies to:"
},
{
"code": null,
"e": 10504,
"s": 10410,
"text": "This means that, applying the matrix B2 ^{-1} to [v]B_1 allows you to change its basis to B2."
},
{
"code": null,
"e": 10521,
"s": 10504,
"text": "Let’s code this:"
},
{
"code": null,
"e": 10555,
"s": 10521,
"text": "array([ 0.86757991, -1.00456621])"
},
{
"code": null,
"e": 10774,
"s": 10555,
"text": "These values are the coordinates of the vector v relative to the basis B2. This means that if you go to 0.86757991 i’ — 1.00456621 j’ you arrive to the position (2, 1) in the standard basis, as illustrated in Figure 6."
},
{
"code": null,
"e": 10785,
"s": 10774,
"text": "Conclusion"
},
{
"code": null,
"e": 11354,
"s": 10785,
"text": "Understanding the concept of basis is a nice way to approach matrix decomposition (also called matrix factorization), like eigendecomposition or singular value decomposition (SVD). In these terms, you can think of matrix decomposition as finding a basis where the matrix associated with a transformation has specific properties: the factorization is a change of basis matrix, the new transformation matrix, and finally the inverse of the change of basis matrix to come back into the initial basis (more details in Chapter 09 and 10 of Essential Math for Data Science)."
},
{
"code": null,
"e": 11420,
"s": 11354,
"text": "This post is a sample of my book Essential Math for Data Science!"
}
] |
CSS | rotateZ() Function - GeeksforGeeks
|
20 Aug, 2019
The rotateZ() function is an inbuilt function which is used to rotate an element around the z-axis.
Syntax:
rotateZ( angle )
Parameters: This function accepts single parameter angle which represents the angle of rotations. The positive and negative angles rotate the elements in clockwise and counter-clockwise respectively.
Below examples illustrate the rotateZ() function in CSS:
Example 1:
<!DOCTYPE html><html> <head> <title>CSS rotateZ() function</title> <style> body { text-align: center; } h1 { color: green; } .rotateZ_image { transform: rotateZ(45deg); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateZ() function</h2> <br><br> <img class="rotateZ_image" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"></body> </html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title>CSS rotateZ() function</title> <style> body { text-align: center; } h1 { color: green; } .GFG { font-size: 35px; font-weight: bold; color: green; transform: rotateZ(45deg); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateZ() function</h2> <br><br> <div class="GFG">Welcome to GeeksforGeeks</div></body> </html>
Output:
Supported Browsers: The browsers supported by rotateZ() function are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n20 Aug, 2019"
},
{
"code": null,
"e": 25085,
"s": 24985,
"text": "The rotateZ() function is an inbuilt function which is used to rotate an element around the z-axis."
},
{
"code": null,
"e": 25093,
"s": 25085,
"text": "Syntax:"
},
{
"code": null,
"e": 25110,
"s": 25093,
"text": "rotateZ( angle )"
},
{
"code": null,
"e": 25310,
"s": 25110,
"text": "Parameters: This function accepts single parameter angle which represents the angle of rotations. The positive and negative angles rotate the elements in clockwise and counter-clockwise respectively."
},
{
"code": null,
"e": 25367,
"s": 25310,
"text": "Below examples illustrate the rotateZ() function in CSS:"
},
{
"code": null,
"e": 25378,
"s": 25367,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS rotateZ() function</title> <style> body { text-align: center; } h1 { color: green; } .rotateZ_image { transform: rotateZ(45deg); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateZ() function</h2> <br><br> <img class=\"rotateZ_image\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"></body> </html> ",
"e": 25943,
"s": 25378,
"text": null
},
{
"code": null,
"e": 25951,
"s": 25943,
"text": "Output:"
},
{
"code": null,
"e": 25962,
"s": 25951,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS rotateZ() function</title> <style> body { text-align: center; } h1 { color: green; } .GFG { font-size: 35px; font-weight: bold; color: green; transform: rotateZ(45deg); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateZ() function</h2> <br><br> <div class=\"GFG\">Welcome to GeeksforGeeks</div></body> </html>",
"e": 26461,
"s": 25962,
"text": null
},
{
"code": null,
"e": 26469,
"s": 26461,
"text": "Output:"
},
{
"code": null,
"e": 26552,
"s": 26469,
"text": "Supported Browsers: The browsers supported by rotateZ() function are listed below:"
},
{
"code": null,
"e": 26566,
"s": 26552,
"text": "Google Chrome"
},
{
"code": null,
"e": 26584,
"s": 26566,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26592,
"s": 26584,
"text": "Firefox"
},
{
"code": null,
"e": 26598,
"s": 26592,
"text": "Opera"
},
{
"code": null,
"e": 26605,
"s": 26598,
"text": "Safari"
},
{
"code": null,
"e": 26619,
"s": 26605,
"text": "CSS-Functions"
},
{
"code": null,
"e": 26623,
"s": 26619,
"text": "CSS"
},
{
"code": null,
"e": 26640,
"s": 26623,
"text": "Web Technologies"
},
{
"code": null,
"e": 26738,
"s": 26640,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26747,
"s": 26738,
"text": "Comments"
},
{
"code": null,
"e": 26760,
"s": 26747,
"text": "Old Comments"
},
{
"code": null,
"e": 26797,
"s": 26760,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26826,
"s": 26797,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26865,
"s": 26826,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 26907,
"s": 26865,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 26942,
"s": 26907,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 26998,
"s": 26942,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27031,
"s": 26998,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27074,
"s": 27031,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27135,
"s": 27074,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
C++ function call by value
|
The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows.
// function definition to swap the values.
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example −
#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
When the above code is put together in a file, compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had been changed inside the function.
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": 2556,
"s": 2318,
"text": "The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument."
},
{
"code": null,
"e": 2767,
"s": 2556,
"text": "By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows."
},
{
"code": null,
"e": 2969,
"s": 2767,
"text": "// function definition to swap the values.\nvoid swap(int x, int y) {\n int temp;\n\n temp = x; /* save the value of x */\n x = y; /* put y into x */\n y = temp; /* put x into y */\n \n return;\n}"
},
{
"code": null,
"e": 3061,
"s": 2969,
"text": "Now, let us call the function swap() by passing actual values as in the following example −"
},
{
"code": null,
"e": 3528,
"s": 3061,
"text": "#include <iostream>\nusing namespace std;\n \n// function declaration\nvoid swap(int x, int y);\n \nint main () {\n // local variable declaration:\n int a = 100;\n int b = 200;\n \n cout << \"Before swap, value of a :\" << a << endl;\n cout << \"Before swap, value of b :\" << b << endl;\n \n // calling a function to swap the values.\n swap(a, b);\n \n cout << \"After swap, value of a :\" << a << endl;\n cout << \"After swap, value of b :\" << b << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 3633,
"s": 3528,
"text": "When the above code is put together in a file, compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3748,
"s": 3633,
"text": "Before swap, value of a :100\nBefore swap, value of b :200\nAfter swap, value of a :100\nAfter swap, value of b :200\n"
},
{
"code": null,
"e": 3848,
"s": 3748,
"text": "Which shows that there is no change in the values though they had been changed inside the function."
},
{
"code": null,
"e": 3885,
"s": 3848,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 3904,
"s": 3885,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3936,
"s": 3904,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 3959,
"s": 3936,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 3995,
"s": 3959,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4012,
"s": 3995,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4047,
"s": 4012,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4064,
"s": 4047,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4099,
"s": 4064,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4116,
"s": 4099,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4151,
"s": 4116,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4168,
"s": 4151,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4175,
"s": 4168,
"text": " Print"
},
{
"code": null,
"e": 4186,
"s": 4175,
"text": " Add Notes"
}
] |
Java Generics - Set
|
Java has provided generic support in Set interface.
Set<T> set = new HashSet<T>();
Where
set − object of Set Interface.
set − object of Set Interface.
T − The generic type parameter passed during set declaration.
T − The generic type parameter passed during set declaration.
The T is a type parameter passed to the generic interface Set and its implemenation class HashSet.
Create the following java program using any editor of your choice.
package com.tutorialspoint;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class GenericsTester {
public static void main(String[] args) {
Set<Integer> integerSet = new HashSet<Integer>();
integerSet.add(Integer.valueOf(10));
integerSet.add(Integer.valueOf(11));
Set<String> stringSet = new HashSet<String>();
stringSet.add("Hello World");
stringSet.add("Hi World");
for(Integer data: integerSet) {
System.out.printf("Integer Value :%d\n", data);
}
Iterator<String> stringIterator = stringSet.iterator();
while(stringIterator.hasNext()) {
System.out.printf("String Value :%s\n", stringIterator.next());
}
}
}
This will produce the following result −
Integer Value :10
Integer Value :11
String Value :Hello World
String Value :Hi World
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": 2692,
"s": 2640,
"text": "Java has provided generic support in Set interface."
},
{
"code": null,
"e": 2724,
"s": 2692,
"text": "Set<T> set = new HashSet<T>();\n"
},
{
"code": null,
"e": 2730,
"s": 2724,
"text": "Where"
},
{
"code": null,
"e": 2761,
"s": 2730,
"text": "set − object of Set Interface."
},
{
"code": null,
"e": 2792,
"s": 2761,
"text": "set − object of Set Interface."
},
{
"code": null,
"e": 2854,
"s": 2792,
"text": "T − The generic type parameter passed during set declaration."
},
{
"code": null,
"e": 2916,
"s": 2854,
"text": "T − The generic type parameter passed during set declaration."
},
{
"code": null,
"e": 3015,
"s": 2916,
"text": "The T is a type parameter passed to the generic interface Set and its implemenation class HashSet."
},
{
"code": null,
"e": 3082,
"s": 3015,
"text": "Create the following java program using any editor of your choice."
},
{
"code": null,
"e": 3833,
"s": 3082,
"text": "package com.tutorialspoint;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n\n Set<Integer> integerSet = new HashSet<Integer>();\n \n integerSet.add(Integer.valueOf(10));\n integerSet.add(Integer.valueOf(11));\n\n Set<String> stringSet = new HashSet<String>();\n \n stringSet.add(\"Hello World\");\n stringSet.add(\"Hi World\");\n \n\n for(Integer data: integerSet) {\n System.out.printf(\"Integer Value :%d\\n\", data);\n }\n\n Iterator<String> stringIterator = stringSet.iterator();\n\n while(stringIterator.hasNext()) {\n System.out.printf(\"String Value :%s\\n\", stringIterator.next());\n }\n } \n}"
},
{
"code": null,
"e": 3874,
"s": 3833,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3960,
"s": 3874,
"text": "Integer Value :10\nInteger Value :11\nString Value :Hello World\nString Value :Hi World\n"
},
{
"code": null,
"e": 3993,
"s": 3960,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4009,
"s": 3993,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4042,
"s": 4009,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4058,
"s": 4042,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4093,
"s": 4058,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4107,
"s": 4093,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4141,
"s": 4107,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4155,
"s": 4141,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4192,
"s": 4155,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4207,
"s": 4192,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4240,
"s": 4207,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4259,
"s": 4240,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4266,
"s": 4259,
"text": " Print"
},
{
"code": null,
"e": 4277,
"s": 4266,
"text": " Add Notes"
}
] |
Python | TextBlob.sentiment() method - GeeksforGeeks
|
09 Sep, 2019
With the help of TextBlob.sentiment() method, we can get the sentiments of the sentences by using TextBlob.sentiment() method.
Syntax : TextBlob.sentiment()Return : Return the tuple of sentiments.
Example #1 :In this example we can say that by using TextBlob.sentiment() method, we are able to get the sentiments of a sentence.
# import TextBlobfrom textblob import TextBlob gfg = TextBlob("GFG is a good company and always value their employees.") # using TextBlob.sentiment methodgfg = gfg.sentiment print(gfg)
Output :
Sentiment(polarity=0.7, subjectivity=0.6000000000000001)
Example #2 :
# import TextBlobfrom textblob import TextBlob gfg = TextBlob("Sandeep Jain An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways.") # using TextBlob.sentiment methodgfg = gfg.sentiment print(gfg)
Output :
Sentiment(polarity=0.5, subjectivity=0.5)
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n09 Sep, 2019"
},
{
"code": null,
"e": 24028,
"s": 23901,
"text": "With the help of TextBlob.sentiment() method, we can get the sentiments of the sentences by using TextBlob.sentiment() method."
},
{
"code": null,
"e": 24098,
"s": 24028,
"text": "Syntax : TextBlob.sentiment()Return : Return the tuple of sentiments."
},
{
"code": null,
"e": 24229,
"s": 24098,
"text": "Example #1 :In this example we can say that by using TextBlob.sentiment() method, we are able to get the sentiments of a sentence."
},
{
"code": "# import TextBlobfrom textblob import TextBlob gfg = TextBlob(\"GFG is a good company and always value their employees.\") # using TextBlob.sentiment methodgfg = gfg.sentiment print(gfg)",
"e": 24417,
"s": 24229,
"text": null
},
{
"code": null,
"e": 24426,
"s": 24417,
"text": "Output :"
},
{
"code": null,
"e": 24483,
"s": 24426,
"text": "Sentiment(polarity=0.7, subjectivity=0.6000000000000001)"
},
{
"code": null,
"e": 24496,
"s": 24483,
"text": "Example #2 :"
},
{
"code": "# import TextBlobfrom textblob import TextBlob gfg = TextBlob(\"Sandeep Jain An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways.\") # using TextBlob.sentiment methodgfg = gfg.sentiment print(gfg)",
"e": 24757,
"s": 24496,
"text": null
},
{
"code": null,
"e": 24766,
"s": 24757,
"text": "Output :"
},
{
"code": null,
"e": 24808,
"s": 24766,
"text": "Sentiment(polarity=0.5, subjectivity=0.5)"
},
{
"code": null,
"e": 24825,
"s": 24808,
"text": "Python-Functions"
},
{
"code": null,
"e": 24832,
"s": 24825,
"text": "Python"
},
{
"code": null,
"e": 24930,
"s": 24832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24939,
"s": 24930,
"text": "Comments"
},
{
"code": null,
"e": 24952,
"s": 24939,
"text": "Old Comments"
},
{
"code": null,
"e": 24984,
"s": 24952,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25040,
"s": 24984,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25082,
"s": 25040,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25124,
"s": 25082,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25160,
"s": 25124,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25182,
"s": 25160,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25221,
"s": 25182,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25248,
"s": 25221,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 25279,
"s": 25248,
"text": "Python | os.path.join() method"
}
] |
How is a file read using a limited buffer size using Python?
|
You can read a file using a limited buffer by specifying the buffer size in the read function. It takes the number of bytes you want to read from the current position of the pointer in the file.
with open('my_file.txt', 'r') as f:
print(f.read(10)) # Read and print 10 bytes
This will give the output −
Hello worl
If the file contents were Hello world!
|
[
{
"code": null,
"e": 1258,
"s": 1062,
"text": "You can read a file using a limited buffer by specifying the buffer size in the read function. It takes the number of bytes you want to read from the current position of the pointer in the file. "
},
{
"code": null,
"e": 1343,
"s": 1258,
"text": "with open('my_file.txt', 'r') as f:\n print(f.read(10)) # Read and print 10 bytes"
},
{
"code": null,
"e": 1371,
"s": 1343,
"text": "This will give the output −"
},
{
"code": null,
"e": 1382,
"s": 1371,
"text": "Hello worl"
},
{
"code": null,
"e": 1421,
"s": 1382,
"text": "If the file contents were Hello world!"
}
] |
How to create Guid value in C#?
|
A Globally Unique Identifier or GUID represents a gigantic identification number — a number so large that it is mathematically guaranteed to be unique not only in a single system like a database, but across multiple systems or distributed applications.
The total number of unique keys (3.40282366×1038) is so large that the probability of the same number being generated twice is very small. For an application using 10 billion random GUIDs, the probability of a coincidence is approximately 1 in a quintillion.(1030)
For example, in Retail domain if we want to generate a unique for each transaction so that a customer can use that id to do post sale operations like return, adjustment etc., GUID can be used. GUIDs are most commonly written in text as a sequence of hexadecimal digits like 3F2504E0-4F89-11D3-9A0C-0305E82C3301.
Guid is present in System namespace in C#. It can be created like below.
Guid demoGuid = Guid.NewGuid();
Live Demo
using System;
namespace DemoApplication{
class Program{
static void Main(string[] args){
Guid demoGuid = Guid.NewGuid();
Console.WriteLine(demoGuid);
Console.WriteLine(Guid.NewGuid());
Console.ReadLine();
}
}
}
The output of the above code is
3a251d82-e8ce-442f-9e42-5285653a5e8a
09081b06-26e2-49fa-8e96-93748a99defa
Each time when Guid.NewGuid() is called it will generate a random unique guid.
|
[
{
"code": null,
"e": 1315,
"s": 1062,
"text": "A Globally Unique Identifier or GUID represents a gigantic identification number — a number so large that it is mathematically guaranteed to be unique not only in a single system like a database, but across multiple systems or distributed applications."
},
{
"code": null,
"e": 1580,
"s": 1315,
"text": "The total number of unique keys (3.40282366×1038) is so large that the probability of the same number being generated twice is very small. For an application using 10 billion random GUIDs, the probability of a coincidence is approximately 1 in a quintillion.(1030)"
},
{
"code": null,
"e": 1892,
"s": 1580,
"text": "For example, in Retail domain if we want to generate a unique for each transaction so that a customer can use that id to do post sale operations like return, adjustment etc., GUID can be used. GUIDs are most commonly written in text as a sequence of hexadecimal digits like 3F2504E0-4F89-11D3-9A0C-0305E82C3301."
},
{
"code": null,
"e": 1965,
"s": 1892,
"text": "Guid is present in System namespace in C#. It can be created like below."
},
{
"code": null,
"e": 1997,
"s": 1965,
"text": "Guid demoGuid = Guid.NewGuid();"
},
{
"code": null,
"e": 2008,
"s": 1997,
"text": " Live Demo"
},
{
"code": null,
"e": 2273,
"s": 2008,
"text": "using System;\nnamespace DemoApplication{\n class Program{\n static void Main(string[] args){\n Guid demoGuid = Guid.NewGuid();\n Console.WriteLine(demoGuid);\n Console.WriteLine(Guid.NewGuid());\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2305,
"s": 2273,
"text": "The output of the above code is"
},
{
"code": null,
"e": 2458,
"s": 2305,
"text": "3a251d82-e8ce-442f-9e42-5285653a5e8a\n09081b06-26e2-49fa-8e96-93748a99defa\nEach time when Guid.NewGuid() is called it will generate a random unique guid."
}
] |
How to create an unordered_map of user defined class in C++? - GeeksforGeeks
|
22 Nov, 2021
unordered_map is used to implement hash tables. It stores key value pairs. For every key, a hash function is computed and value is stored at that hash entry. Hash functions for standard data types (int, char, string, ..) are predefined. How to use our own data types for implementing hash tables?unordered_map allows a third parameter which is used to specify our own hash function.
// Create an unordered_map with given KeyType,
// ValueType and hash function defined by
// MyHashType
unordered_map<KeyType, ValueType, MyHashType> um;
Here MyHashFunction is class or struct that must contain an operator function (). We must also implement operator == in our own class which is used for handling collisions. Below is a sample code where objects of Person class are used as keys. We define our own hash function that uses sum of lengths of first and last names as key in the hash table. Note that the purpose of this code is to only demonstrate working with a simple code and sum of lengths may not be a good idea as a hash function.
CPP
// CPP program to demonstrate working of unordered_map// for user defined data types.#include <bits/stdc++.h>using namespace std; // Objects of this class are used as key in hash// table. This class must implement operator ==()// to handle collisions.struct Person { string first, last; // First and last names Person(string f, string l) { first = f; last = l; } // Match both first and last names in case // of collisions. bool operator==(const Person& p) const { return first == p.first && last == p.last; }}; class MyHashFunction {public: // Use sum of lengths of first and last names // as hash function. size_t operator()(const Person& p) const { return p.first.length() + p.last.length(); }}; // Driver codeint main(){ unordered_map<Person, int, MyHashFunction> um; Person p1("kartik", "kapoor"); Person p2("Ram", "Singh"); Person p3("Laxman", "Prasad"); um[p1] = 100; um[p2] = 200; um[p3] = 100; for (auto e : um) { cout << "[" << e.first.first << ", " << e.first.last << "] = > " << e.second << '\n'; } return 0;}
[Laxman, Prasad] = > 100
[kartik, kapoor] = > 100
[Ram, Singh] = > 200
Another example where predefined operator functions of predefined hash class to make our overall hash.
CPP
// CPP program to demonstrate working of unordered_map// for user defined data types.#include <bits/stdc++.h>using namespace std; struct Person { string first, last; Person(string f, string l) { first = f; last = l; } bool operator==(const Person& p) const { return first == p.first && last == p.last; }}; class MyHashFunction {public: // We use predefined hash functions of strings // and define our hash function as XOR of the // hash values. size_t operator()(const Person& p) const { return (hash<string>()(p.first)) ^ (hash<string>()(p.last)); }}; // Driver codeint main(){ unordered_map<Person, int, MyHashFunction> um; Person p1("kartik", "kapoor"); Person p2("Ram", "Singh"); Person p3("Laxman", "Prasad"); um[p1] = 100; um[p2] = 200; um[p3] = 100; for (auto e : um) { cout << "[" << e.first.first << ", " << e.first.last << "] = > " << e.second << '\n'; } return 0;}
[Laxman, Prasad] = > 100
[kartik, kapoor] = > 100
[Ram, Singh] = > 200
as5853535
cpp-unordered_map
Picked
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Socket Programming in C/C++
C++ Classes and Objects
Operator Overloading in C++
Iterators in C++ STL
Constructors in C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Object Oriented Programming in C++
Copy Constructor in C++
|
[
{
"code": null,
"e": 24516,
"s": 24488,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 24901,
"s": 24516,
"text": "unordered_map is used to implement hash tables. It stores key value pairs. For every key, a hash function is computed and value is stored at that hash entry. Hash functions for standard data types (int, char, string, ..) are predefined. How to use our own data types for implementing hash tables?unordered_map allows a third parameter which is used to specify our own hash function. "
},
{
"code": null,
"e": 25056,
"s": 24901,
"text": "// Create an unordered_map with given KeyType, \n// ValueType and hash function defined by \n// MyHashType\nunordered_map<KeyType, ValueType, MyHashType> um;"
},
{
"code": null,
"e": 25555,
"s": 25056,
"text": "Here MyHashFunction is class or struct that must contain an operator function (). We must also implement operator == in our own class which is used for handling collisions. Below is a sample code where objects of Person class are used as keys. We define our own hash function that uses sum of lengths of first and last names as key in the hash table. Note that the purpose of this code is to only demonstrate working with a simple code and sum of lengths may not be a good idea as a hash function. "
},
{
"code": null,
"e": 25559,
"s": 25555,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of unordered_map// for user defined data types.#include <bits/stdc++.h>using namespace std; // Objects of this class are used as key in hash// table. This class must implement operator ==()// to handle collisions.struct Person { string first, last; // First and last names Person(string f, string l) { first = f; last = l; } // Match both first and last names in case // of collisions. bool operator==(const Person& p) const { return first == p.first && last == p.last; }}; class MyHashFunction {public: // Use sum of lengths of first and last names // as hash function. size_t operator()(const Person& p) const { return p.first.length() + p.last.length(); }}; // Driver codeint main(){ unordered_map<Person, int, MyHashFunction> um; Person p1(\"kartik\", \"kapoor\"); Person p2(\"Ram\", \"Singh\"); Person p3(\"Laxman\", \"Prasad\"); um[p1] = 100; um[p2] = 200; um[p3] = 100; for (auto e : um) { cout << \"[\" << e.first.first << \", \" << e.first.last << \"] = > \" << e.second << '\\n'; } return 0;}",
"e": 26719,
"s": 25559,
"text": null
},
{
"code": null,
"e": 26790,
"s": 26719,
"text": "[Laxman, Prasad] = > 100\n[kartik, kapoor] = > 100\n[Ram, Singh] = > 200"
},
{
"code": null,
"e": 26896,
"s": 26792,
"text": "Another example where predefined operator functions of predefined hash class to make our overall hash. "
},
{
"code": null,
"e": 26900,
"s": 26896,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of unordered_map// for user defined data types.#include <bits/stdc++.h>using namespace std; struct Person { string first, last; Person(string f, string l) { first = f; last = l; } bool operator==(const Person& p) const { return first == p.first && last == p.last; }}; class MyHashFunction {public: // We use predefined hash functions of strings // and define our hash function as XOR of the // hash values. size_t operator()(const Person& p) const { return (hash<string>()(p.first)) ^ (hash<string>()(p.last)); }}; // Driver codeint main(){ unordered_map<Person, int, MyHashFunction> um; Person p1(\"kartik\", \"kapoor\"); Person p2(\"Ram\", \"Singh\"); Person p3(\"Laxman\", \"Prasad\"); um[p1] = 100; um[p2] = 200; um[p3] = 100; for (auto e : um) { cout << \"[\" << e.first.first << \", \" << e.first.last << \"] = > \" << e.second << '\\n'; } return 0;}",
"e": 27924,
"s": 26900,
"text": null
},
{
"code": null,
"e": 27995,
"s": 27924,
"text": "[Laxman, Prasad] = > 100\n[kartik, kapoor] = > 100\n[Ram, Singh] = > 200"
},
{
"code": null,
"e": 28007,
"s": 27997,
"text": "as5853535"
},
{
"code": null,
"e": 28025,
"s": 28007,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 28032,
"s": 28025,
"text": "Picked"
},
{
"code": null,
"e": 28036,
"s": 28032,
"text": "STL"
},
{
"code": null,
"e": 28040,
"s": 28036,
"text": "C++"
},
{
"code": null,
"e": 28044,
"s": 28040,
"text": "STL"
},
{
"code": null,
"e": 28048,
"s": 28044,
"text": "CPP"
},
{
"code": null,
"e": 28146,
"s": 28048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28155,
"s": 28146,
"text": "Comments"
},
{
"code": null,
"e": 28168,
"s": 28155,
"text": "Old Comments"
},
{
"code": null,
"e": 28187,
"s": 28168,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28215,
"s": 28187,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 28239,
"s": 28215,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 28267,
"s": 28239,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28288,
"s": 28267,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 28308,
"s": 28288,
"text": "Constructors in C++"
},
{
"code": null,
"e": 28332,
"s": 28308,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 28367,
"s": 28332,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28402,
"s": 28367,
"text": "Object Oriented Programming in C++"
}
] |
Fine-tuning pre-trained transformer models for sentence entailment | by Dhruv Verma | Towards Data Science
|
In this article, I will be describing the process of fine-tuning pre-trained models such as BERT and ALBERT on the task of sentence entailment using the MultiNLI dataset (Bowman et al. A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference). The models will be loaded using the Hugging Face library and are fine-tuned using PyTorch.
To understand entailment, let’s start with an example.1. Jim rides a bike to school every morning.2. Jim can ride a bike.
Entailment occurs if a proposed premise is true. In this example, if the sentence ‘Jim rides a bike to school every morning.’ is true, then the premise entails that Jim goes to school every morning and Jim also knows how to ride a bike. Hence, this would make the second sentence, or the hypothesis, true as well.
To define entailment in simple terms, a sentence Y is said to entail sentence X if X is true and Y can be logically derived from it. For the dataset I used, a pair of sentences can either entail each other, be neutral or contradict each other—more on the dataset in the next section.
The Multi-Genre Natural Language Inference (MultiNLI) corpus is a dataset designed for use in the development and evaluation of machine learning models for sentence understanding. It has over 433,000 examples and is one of the largest datasets available for natural language inference (a.k.a recognizing textual entailment). The dataset is also designed so that existing machine learning models trained on the Stanford NLI corpus can also be evaluated using MultiNLI. You can read more about this dataset in the paper — A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference.
As part of the training process, 3 columns were considered in the dataset — ‘gold_label,’ ‘sentence1’ (premise), and ‘sentence2’ (hypothesis). The ‘gold_label’ is the column indicating the label given to the pair of sentences. There were three labels — ‘entailment,’ ‘neutral,’ and ‘contradiction.’The training set had 392,702 samples, and the validation set had 10,000 samples left.
BERT (Bidirectional Encoder Representations from Transformers) is a language model by Google based on the encoder-decoder transformer model introduced in this paper. It uses transformers' attention mechanism to learn the contextual meaning of words and the relations between them. BERT, along with its modifications such as ALBERT, RoBERTa, etc. have been known to achieve state-of-the-art results on various natural language process tasks such as question-answering and natural language inference.
The Transformer encoder reads an entire sequence of words at once, unlike the directional Long Short-Term Memory network. This allows the model to learn the context of a word based on all of its surroundings. The encoder block of a transformer takes a sequence of tokens as an input. These are first embedded into vectors and fed through a feed-forward neural network. The output from this neural network is a sequence of vectors that each corresponds to an input sequence at a given index.
While I will not be elaborating much on BERT’s training process, you can read this article for a great detailed description of it’s working as well as the procedure to train it.
Finally, coming to the process of fine-tuning a pre-trained BERT model using Hugging Face and PyTorch. For this case, I used the “bert-base” model. This was trained on 100,000 training examples sampled from the original training set due to compute limitations and training time on Google Colab.
The first step involved creating a DataLoader object to feed data to the model. BERT for sequence classification requires the data to be arranged in a certain format. Each sentence's start needs to have a [CLS] token present, and the end of the sentence needs a [SEP] token. So with our sequence consisting of two sentences, it will need to be formatted as [CLS] sentence1 [SEP] sentence2 [SEP]. Additionally, each sequence will need to have segment_ids associated with it. The first sentence in the sequence is marked by [0], while the second sentence is marked by [1]. Lastly, each sequence needs an attention mask to help the model determine which part of the input sequence is not part of the padding.
Now that the DataLoader objects for the training and validation sets are created, the model can be loaded along with its optimizer. For this case, I will be using the BertForSequenceClassification pre-trained model. This model offers an additional argument to add an optional classification head with the required number of labels. For this case, there are three classes. Hence I set num_labels to three. This adds a classification head with three output units as the final layer.
Now that the model is loaded, time to move to the training and validation loops. As part of the training process, the model was fine-tuned for 5 epochs.
With the training and validation loops defined, we can tune the model on the MultiNLI dataset to try and achieve the expected performance.
Epoch 1: train_loss: 0.5973 train_acc: 0.7530 | val_loss: 0.5398 val_acc: 0.7836 01:47:59.10 Epoch 2: train_loss: 0.3623 train_acc: 0.8643 | val_loss: 0.5222 val_acc: 0.8072 01:48:18.70 Epoch 3: train_loss: 0.2096 train_acc: 0.9256 | val_loss: 0.6908 val_acc: 0.7939 01:48:11.29 Epoch 4: train_loss: 0.1295 train_acc: 0.9558 | val_loss: 0.7929 val_acc: 0.7891 01:47:59.77 Epoch 5: train_loss: 0.0916 train_acc: 0.9690 | val_loss: 0.8490 val_acc: 0.7906 01:47:52.39
As seen from the loss and accuracy values above, the model seems to be learning while overfitting a bit. This can be solved by training with more data instead of the sampled 100,000 samples.
Thank you for reading this article! The entire code for this project, along with other model benchmarks, can be found at https://github.com/dh1105/Sentence-Entailment.
A Broad-Coverage Challenge Corpus for Sentence Understanding through InferenceBERT: Pre-training of Deep Bidirectional Transformers for Language UnderstandingAttention is all you needALBERT: A Lite BERT for Self-supervised Learning of Language RepresentationsRoBERTa: A Robustly Optimized BERT Pretraining Approachhttps://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270
A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference
BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
Attention is all you need
ALBERT: A Lite BERT for Self-supervised Learning of Language Representations
RoBERTa: A Robustly Optimized BERT Pretraining Approach
|
[
{
"code": null,
"e": 529,
"s": 172,
"text": "In this article, I will be describing the process of fine-tuning pre-trained models such as BERT and ALBERT on the task of sentence entailment using the MultiNLI dataset (Bowman et al. A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference). The models will be loaded using the Hugging Face library and are fine-tuned using PyTorch."
},
{
"code": null,
"e": 651,
"s": 529,
"text": "To understand entailment, let’s start with an example.1. Jim rides a bike to school every morning.2. Jim can ride a bike."
},
{
"code": null,
"e": 965,
"s": 651,
"text": "Entailment occurs if a proposed premise is true. In this example, if the sentence ‘Jim rides a bike to school every morning.’ is true, then the premise entails that Jim goes to school every morning and Jim also knows how to ride a bike. Hence, this would make the second sentence, or the hypothesis, true as well."
},
{
"code": null,
"e": 1249,
"s": 965,
"text": "To define entailment in simple terms, a sentence Y is said to entail sentence X if X is true and Y can be logically derived from it. For the dataset I used, a pair of sentences can either entail each other, be neutral or contradict each other—more on the dataset in the next section."
},
{
"code": null,
"e": 1849,
"s": 1249,
"text": "The Multi-Genre Natural Language Inference (MultiNLI) corpus is a dataset designed for use in the development and evaluation of machine learning models for sentence understanding. It has over 433,000 examples and is one of the largest datasets available for natural language inference (a.k.a recognizing textual entailment). The dataset is also designed so that existing machine learning models trained on the Stanford NLI corpus can also be evaluated using MultiNLI. You can read more about this dataset in the paper — A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference."
},
{
"code": null,
"e": 2233,
"s": 1849,
"text": "As part of the training process, 3 columns were considered in the dataset — ‘gold_label,’ ‘sentence1’ (premise), and ‘sentence2’ (hypothesis). The ‘gold_label’ is the column indicating the label given to the pair of sentences. There were three labels — ‘entailment,’ ‘neutral,’ and ‘contradiction.’The training set had 392,702 samples, and the validation set had 10,000 samples left."
},
{
"code": null,
"e": 2732,
"s": 2233,
"text": "BERT (Bidirectional Encoder Representations from Transformers) is a language model by Google based on the encoder-decoder transformer model introduced in this paper. It uses transformers' attention mechanism to learn the contextual meaning of words and the relations between them. BERT, along with its modifications such as ALBERT, RoBERTa, etc. have been known to achieve state-of-the-art results on various natural language process tasks such as question-answering and natural language inference."
},
{
"code": null,
"e": 3223,
"s": 2732,
"text": "The Transformer encoder reads an entire sequence of words at once, unlike the directional Long Short-Term Memory network. This allows the model to learn the context of a word based on all of its surroundings. The encoder block of a transformer takes a sequence of tokens as an input. These are first embedded into vectors and fed through a feed-forward neural network. The output from this neural network is a sequence of vectors that each corresponds to an input sequence at a given index."
},
{
"code": null,
"e": 3401,
"s": 3223,
"text": "While I will not be elaborating much on BERT’s training process, you can read this article for a great detailed description of it’s working as well as the procedure to train it."
},
{
"code": null,
"e": 3696,
"s": 3401,
"text": "Finally, coming to the process of fine-tuning a pre-trained BERT model using Hugging Face and PyTorch. For this case, I used the “bert-base” model. This was trained on 100,000 training examples sampled from the original training set due to compute limitations and training time on Google Colab."
},
{
"code": null,
"e": 4402,
"s": 3696,
"text": "The first step involved creating a DataLoader object to feed data to the model. BERT for sequence classification requires the data to be arranged in a certain format. Each sentence's start needs to have a [CLS] token present, and the end of the sentence needs a [SEP] token. So with our sequence consisting of two sentences, it will need to be formatted as [CLS] sentence1 [SEP] sentence2 [SEP]. Additionally, each sequence will need to have segment_ids associated with it. The first sentence in the sequence is marked by [0], while the second sentence is marked by [1]. Lastly, each sequence needs an attention mask to help the model determine which part of the input sequence is not part of the padding."
},
{
"code": null,
"e": 4883,
"s": 4402,
"text": "Now that the DataLoader objects for the training and validation sets are created, the model can be loaded along with its optimizer. For this case, I will be using the BertForSequenceClassification pre-trained model. This model offers an additional argument to add an optional classification head with the required number of labels. For this case, there are three classes. Hence I set num_labels to three. This adds a classification head with three output units as the final layer."
},
{
"code": null,
"e": 5036,
"s": 4883,
"text": "Now that the model is loaded, time to move to the training and validation loops. As part of the training process, the model was fine-tuned for 5 epochs."
},
{
"code": null,
"e": 5175,
"s": 5036,
"text": "With the training and validation loops defined, we can tune the model on the MultiNLI dataset to try and achieve the expected performance."
},
{
"code": null,
"e": 5640,
"s": 5175,
"text": "Epoch 1: train_loss: 0.5973 train_acc: 0.7530 | val_loss: 0.5398 val_acc: 0.7836 01:47:59.10 Epoch 2: train_loss: 0.3623 train_acc: 0.8643 | val_loss: 0.5222 val_acc: 0.8072 01:48:18.70 Epoch 3: train_loss: 0.2096 train_acc: 0.9256 | val_loss: 0.6908 val_acc: 0.7939 01:48:11.29 Epoch 4: train_loss: 0.1295 train_acc: 0.9558 | val_loss: 0.7929 val_acc: 0.7891 01:47:59.77 Epoch 5: train_loss: 0.0916 train_acc: 0.9690 | val_loss: 0.8490 val_acc: 0.7906 01:47:52.39"
},
{
"code": null,
"e": 5831,
"s": 5640,
"text": "As seen from the loss and accuracy values above, the model seems to be learning while overfitting a bit. This can be solved by training with more data instead of the sampled 100,000 samples."
},
{
"code": null,
"e": 5999,
"s": 5831,
"text": "Thank you for reading this article! The entire code for this project, along with other model benchmarks, can be found at https://github.com/dh1105/Sentence-Entailment."
},
{
"code": null,
"e": 6412,
"s": 5999,
"text": "A Broad-Coverage Challenge Corpus for Sentence Understanding through InferenceBERT: Pre-training of Deep Bidirectional Transformers for Language UnderstandingAttention is all you needALBERT: A Lite BERT for Self-supervised Learning of Language RepresentationsRoBERTa: A Robustly Optimized BERT Pretraining Approachhttps://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270"
},
{
"code": null,
"e": 6491,
"s": 6412,
"text": "A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference"
},
{
"code": null,
"e": 6572,
"s": 6491,
"text": "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding"
},
{
"code": null,
"e": 6598,
"s": 6572,
"text": "Attention is all you need"
},
{
"code": null,
"e": 6675,
"s": 6598,
"text": "ALBERT: A Lite BERT for Self-supervised Learning of Language Representations"
}
] |
How to write retry logic in C#?
|
Retry logic is implemented whenever there is a failing operation. Implement retry
logic only where the full context of a failing operation.
It's important to log all connectivity failures that cause a retry so that underlying
problems with the application, services, or resources can be identified.
class Program{
public static void Main(){
HttpClient client = new HttpClient();
dynamic res = null;
var retryAttempts = 3;
var delay = TimeSpan.FromSeconds(2);
RetryHelper.Retry(retryAttempts, delay, () =>{
res = client.GetAsync("https://example22.com/api/cycles/1");
});
Console.ReadLine();
}
}
public static class RetryHelper{
public static void Retry(int times, TimeSpan delay, Action operation){
var attempts = 0;
do{
try{
attempts++;
System.Console.WriteLine(attempts);
operation();
break;
}
catch (Exception ex){
if (attempts == times)
throw;
Task.Delay(delay).Wait();
}
} while (true);
}
}
|
[
{
"code": null,
"e": 1202,
"s": 1062,
"text": "Retry logic is implemented whenever there is a failing operation. Implement retry\nlogic only where the full context of a failing operation."
},
{
"code": null,
"e": 1361,
"s": 1202,
"text": "It's important to log all connectivity failures that cause a retry so that underlying\nproblems with the application, services, or resources can be identified."
},
{
"code": null,
"e": 2162,
"s": 1361,
"text": "class Program{\n public static void Main(){\n HttpClient client = new HttpClient();\n dynamic res = null;\n var retryAttempts = 3;\n var delay = TimeSpan.FromSeconds(2);\n RetryHelper.Retry(retryAttempts, delay, () =>{\n res = client.GetAsync(\"https://example22.com/api/cycles/1\");\n });\n Console.ReadLine();\n }\n}\npublic static class RetryHelper{\n public static void Retry(int times, TimeSpan delay, Action operation){\n var attempts = 0;\n do{\n try{\n attempts++;\n System.Console.WriteLine(attempts);\n operation();\n break;\n }\n catch (Exception ex){\n if (attempts == times)\n throw;\n Task.Delay(delay).Wait();\n }\n } while (true);\n }\n}"
}
] |
How to check if a variable is NaN in JavaScript?
|
NaN is a JavaScript property, which is "Not-a-Number" value. To find out whether value is NaN, use the Number.isNaN() or isNan() method.
Here’s an example to check if a variable in NaN in JavaScript
Live Demo
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Check</button>
<p id="test"></p>
<script>
function display() {
var a = "";
a = a + isNaN(6234) + ": 6234<br>";
a = a + isNaN(-52.1) + ": -52.1<br>";
a = a + isNaN('Website') + ": 'Hello'<br>";
a = a + isNaN(NaN) + ": NaN<br>";
a = a + isNaN('') + ": ''<br>";
a = a + isNaN(0) + ": 0<br>";
a = a + isNaN(false) + ": false<br>";
document.getElementById("test").innerHTML = a;
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "NaN is a JavaScript property, which is \"Not-a-Number\" value. To find out whether value is NaN, use the Number.isNaN() or isNan() method."
},
{
"code": null,
"e": 1261,
"s": 1199,
"text": "Here’s an example to check if a variable in NaN in JavaScript"
},
{
"code": null,
"e": 1271,
"s": 1261,
"text": "Live Demo"
},
{
"code": null,
"e": 1887,
"s": 1271,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"display()\">Check</button>\n <p id=\"test\"></p>\n <script>\n function display() {\n var a = \"\";\n a = a + isNaN(6234) + \": 6234<br>\";\n a = a + isNaN(-52.1) + \": -52.1<br>\";\n a = a + isNaN('Website') + \": 'Hello'<br>\";\n a = a + isNaN(NaN) + \": NaN<br>\";\n a = a + isNaN('') + \": ''<br>\";\n a = a + isNaN(0) + \": 0<br>\";\n a = a + isNaN(false) + \": false<br>\";\n document.getElementById(\"test\").innerHTML = a;\n }\n </script>\n </body>\n</html>"
}
] |
Laravel - Artisan Console
|
Laravel framework provides three primary tools for interaction through command-line namely: Artisan, Ticker and REPL. This chapter explains about Artisan in detail.
Artisan is the command line interface frequently used in Laravel and it includes a set of helpful commands for developing a web application.
Here is a list of few commands in Artisan along with their respective functionalities −
To start Laravel project
php artisan serve
To enable caching mechanism
php artisan route:cache
To view the list of available commands supported by Artisan
php artisan list
To view help about any command and view the available options and arguments
php artisan help serve
The following screenshot shows the output of the commands given above −
In addition to the commands listed in Artisan, a user can also create a custom command which can be used in the web application. Please note that commands are stored in app/console/commands directory.
The default command for creating user defined command is shown below −
php artisan make:console <name-of-command>
Once you type the above given command, you can see the output as shown in the screenshot given below −
The file created for DefaultCommand is named as DefaultCommand.php and is shown below −
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class DefaultCommand extends Command{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:name';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct() {
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle() {
//
}
}
This file includes the signature and description for the command that user defined. The public function named handle executes the functionalities when the command is executed. These commands are registered in the file Kernel.php in the same directory.
You can also create the schedule of tasks for the user defined command as shown in the following code −
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
// Commands\Inspire::class,
Commands\DefaultCommand::class
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule) {
// $schedule->command('inspire')
// ->hourly();
}
}
Note that the schedule of tasks for the given command is defined in the function named schedule, which includes a parameter for scheduling the tasks which takes hourly parameter.
The commands are registered in the array of commands, which includes the path and name of the commands.
Once the command is registered, it is listed in Artisan commands. The values included in the signature and description section will be displayed when you call for the help attribute of the specified command.
Let us see how to view the attributes of our command DefaultCommand. You should use the command as shown below −
php artisan help DefaultCommand
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2637,
"s": 2472,
"text": "Laravel framework provides three primary tools for interaction through command-line namely: Artisan, Ticker and REPL. This chapter explains about Artisan in detail."
},
{
"code": null,
"e": 2778,
"s": 2637,
"text": "Artisan is the command line interface frequently used in Laravel and it includes a set of helpful commands for developing a web application."
},
{
"code": null,
"e": 2866,
"s": 2778,
"text": "Here is a list of few commands in Artisan along with their respective functionalities −"
},
{
"code": null,
"e": 2891,
"s": 2866,
"text": "To start Laravel project"
},
{
"code": null,
"e": 2910,
"s": 2891,
"text": "php artisan serve\n"
},
{
"code": null,
"e": 2938,
"s": 2910,
"text": "To enable caching mechanism"
},
{
"code": null,
"e": 2963,
"s": 2938,
"text": "php artisan route:cache\n"
},
{
"code": null,
"e": 3023,
"s": 2963,
"text": "To view the list of available commands supported by Artisan"
},
{
"code": null,
"e": 3041,
"s": 3023,
"text": "php artisan list\n"
},
{
"code": null,
"e": 3117,
"s": 3041,
"text": "To view help about any command and view the available options and arguments"
},
{
"code": null,
"e": 3141,
"s": 3117,
"text": "php artisan help serve\n"
},
{
"code": null,
"e": 3213,
"s": 3141,
"text": "The following screenshot shows the output of the commands given above −"
},
{
"code": null,
"e": 3414,
"s": 3213,
"text": "In addition to the commands listed in Artisan, a user can also create a custom command which can be used in the web application. Please note that commands are stored in app/console/commands directory."
},
{
"code": null,
"e": 3485,
"s": 3414,
"text": "The default command for creating user defined command is shown below −"
},
{
"code": null,
"e": 3529,
"s": 3485,
"text": "php artisan make:console <name-of-command>\n"
},
{
"code": null,
"e": 3632,
"s": 3529,
"text": "Once you type the above given command, you can see the output as shown in the screenshot given below −"
},
{
"code": null,
"e": 3720,
"s": 3632,
"text": "The file created for DefaultCommand is named as DefaultCommand.php and is shown below −"
},
{
"code": null,
"e": 4405,
"s": 3720,
"text": "<?php\n\nnamespace App\\Console\\Commands;\nuse Illuminate\\Console\\Command;\n\nclass DefaultCommand extends Command{\n /**\n * The name and signature of the console command.\n *\n * @var string\n */\n \n protected $signature = 'command:name';\n \n /**\n * The console command description.\n *\n * @var string\n */\n \n protected $description = 'Command description';\n \n /**\n * Create a new command instance.\n *\n * @return void\n */\n \n public function __construct() {\n parent::__construct();\n }\n \n /**\n * Execute the console command.\n *\n * @return mixed\n */\n \n public function handle() {\n //\n }\n}"
},
{
"code": null,
"e": 4657,
"s": 4405,
"text": "This file includes the signature and description for the command that user defined. The public function named handle executes the functionalities when the command is executed. These commands are registered in the file Kernel.php in the same directory."
},
{
"code": null,
"e": 4761,
"s": 4657,
"text": "You can also create the schedule of tasks for the user defined command as shown in the following code −"
},
{
"code": null,
"e": 5426,
"s": 4761,
"text": "<?php\n\nnamespace App\\Console;\n\nuse Illuminate\\Console\\Scheduling\\Schedule;\nuse Illuminate\\Foundation\\Console\\Kernel as ConsoleKernel;\n\nclass Kernel extends ConsoleKernel {\n /**\n * The Artisan commands provided by your application.\n *\n * @var array\n */\n \n protected $commands = [\n // Commands\\Inspire::class,\n Commands\\DefaultCommand::class\n ];\n \n /**\n * Define the application's command schedule.\n *\n * @param \\Illuminate\\Console\\Scheduling\\Schedule $schedule\n * @return void\n */\n \n protected function schedule(Schedule $schedule) {\n // $schedule->command('inspire')\n // ->hourly();\n }\n}"
},
{
"code": null,
"e": 5605,
"s": 5426,
"text": "Note that the schedule of tasks for the given command is defined in the function named schedule, which includes a parameter for scheduling the tasks which takes hourly parameter."
},
{
"code": null,
"e": 5709,
"s": 5605,
"text": "The commands are registered in the array of commands, which includes the path and name of the commands."
},
{
"code": null,
"e": 5917,
"s": 5709,
"text": "Once the command is registered, it is listed in Artisan commands. The values included in the signature and description section will be displayed when you call for the help attribute of the specified command."
},
{
"code": null,
"e": 6030,
"s": 5917,
"text": "Let us see how to view the attributes of our command DefaultCommand. You should use the command as shown below −"
},
{
"code": null,
"e": 6063,
"s": 6030,
"text": "php artisan help DefaultCommand\n"
},
{
"code": null,
"e": 6096,
"s": 6063,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6116,
"s": 6096,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 6151,
"s": 6116,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6165,
"s": 6151,
"text": " Antonio Papa"
},
{
"code": null,
"e": 6199,
"s": 6165,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6219,
"s": 6199,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 6252,
"s": 6219,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6272,
"s": 6252,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6307,
"s": 6272,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6330,
"s": 6307,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 6365,
"s": 6330,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6385,
"s": 6365,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 6392,
"s": 6385,
"text": " Print"
},
{
"code": null,
"e": 6403,
"s": 6392,
"text": " Add Notes"
}
] |
Happy Number in Python
|
Here we will see how to detect a number n is one Happy number or not. So the happy number is a number, where starting with any positive integers replace the number by the sum of squares of its digits, this process will be repeated until it becomes 1, otherwise it will loop endlessly in a cycle. Those numbers, when the 1 has found, they will be happy number.
Suppose the number is 19, the output will be true as the number is happy number. As we can see from 19, we will get
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
To solve this, we will follow these steps −
Here we will use the dynamic programming approach, and solve this using recursion
Base case is, when n = 1, then return true
When n is already visited, return false
mark n as visited
n := n as string, l := list of all digits in n
temp := squared sum of all digits
return function recursively with parameter temp and visited list
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
return self.solve(n,{})
def solve(self,n,visited):
if n == 1:
return True
if n in visited:
return False
visited[n]= 1
n = str(n)
l = list(n)
l = list(map(int,l))
temp = 0
for i in l:
temp += (i**2)
return self.solve(temp,visited)
ob1 = Solution()
op = ob1.isHappy(19)
print("Is Happy:",op)
19
Is Happy: True
|
[
{
"code": null,
"e": 1422,
"s": 1062,
"text": "Here we will see how to detect a number n is one Happy number or not. So the happy number is a number, where starting with any positive integers replace the number by the sum of squares of its digits, this process will be repeated until it becomes 1, otherwise it will loop endlessly in a cycle. Those numbers, when the 1 has found, they will be happy number."
},
{
"code": null,
"e": 1538,
"s": 1422,
"text": "Suppose the number is 19, the output will be true as the number is happy number. As we can see from 19, we will get"
},
{
"code": null,
"e": 1551,
"s": 1538,
"text": "12 + 92 = 82"
},
{
"code": null,
"e": 1564,
"s": 1551,
"text": "82 + 22 = 68"
},
{
"code": null,
"e": 1578,
"s": 1564,
"text": "62 + 82 = 100"
},
{
"code": null,
"e": 1595,
"s": 1578,
"text": "12 + 02 + 02 = 1"
},
{
"code": null,
"e": 1639,
"s": 1595,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1721,
"s": 1639,
"text": "Here we will use the dynamic programming approach, and solve this using recursion"
},
{
"code": null,
"e": 1764,
"s": 1721,
"text": "Base case is, when n = 1, then return true"
},
{
"code": null,
"e": 1804,
"s": 1764,
"text": "When n is already visited, return false"
},
{
"code": null,
"e": 1822,
"s": 1804,
"text": "mark n as visited"
},
{
"code": null,
"e": 1869,
"s": 1822,
"text": "n := n as string, l := list of all digits in n"
},
{
"code": null,
"e": 1903,
"s": 1869,
"text": "temp := squared sum of all digits"
},
{
"code": null,
"e": 1968,
"s": 1903,
"text": "return function recursively with parameter temp and visited list"
},
{
"code": null,
"e": 2038,
"s": 1968,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2049,
"s": 2038,
"text": " Live Demo"
},
{
"code": null,
"e": 2536,
"s": 2049,
"text": "class Solution(object):\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n return self.solve(n,{})\n def solve(self,n,visited):\n if n == 1:\n return True\n if n in visited:\n return False\n visited[n]= 1\n n = str(n)\n l = list(n)\n l = list(map(int,l))\n temp = 0\n for i in l:\n temp += (i**2)\n return self.solve(temp,visited)\nob1 = Solution()\nop = ob1.isHappy(19)\nprint(\"Is Happy:\",op)"
},
{
"code": null,
"e": 2539,
"s": 2536,
"text": "19"
},
{
"code": null,
"e": 2554,
"s": 2539,
"text": "Is Happy: True"
}
] |
How to save cache in local storage of android webview?
|
This example demonstrate about How to save cache in local storage of android webview.
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"?>
<LinearLayout 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:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<WebView
android:id = "@+id/web_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken web view to show facebook.com.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.setCancelable(false);
WebView web_view = findViewById(R.id.web_view);
web_view.requestFocus();
web_view.getSettings().setJavaScriptEnabled(true);
web_view.getSettings().setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/cache");
web_view.loadUrl("https://touch.facebook.com/");
web_view.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
web_view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100) {
progressDialog.show();
}
if (progress = = 100) {
progressDialog.dismiss();
}
}
});
}
}
Step 4 − Add the following code to AndroidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click 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": 1148,
"s": 1062,
"text": "This example demonstrate about How to save cache in local storage of android webview."
},
{
"code": null,
"e": 1277,
"s": 1148,
"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": 1342,
"s": 1277,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1909,
"s": 1342,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout 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:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1973,
"s": 1909,
"text": "In the above code, we have taken web view to show facebook.com."
},
{
"code": null,
"e": 2030,
"s": 1973,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3738,
"s": 2030,
"text": "package com.example.myapplication;\nimport android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Loading Data...\");\n progressDialog.setCancelable(false);\n WebView web_view = findViewById(R.id.web_view);\n web_view.requestFocus();\n web_view.getSettings().setJavaScriptEnabled(true);\n web_view.getSettings().setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + \"/cache\");\n web_view.loadUrl(\"https://touch.facebook.com/\");\n web_view.setWebViewClient(new WebViewClient() {\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n view.loadUrl(url);\n return true;\n }\n });\n web_view.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int progress) {\n if (progress < 100) {\n progressDialog.show();\n }\n if (progress = = 100) {\n progressDialog.dismiss();\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3793,
"s": 3738,
"text": "Step 4 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 4570,
"s": 3793,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4917,
"s": 4570,
"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": 4957,
"s": 4917,
"text": "Click here to download the project code"
}
] |
K-Means Clustering: Identifying Profitable Hotel Customers | by Michael Grogan | Towards Data Science
|
In this instance, K-Means is used to analyse market segment clusters for a hotel in Portugal.
This analysis is based on the original study by Antonio, Almeida and Nunes as cited in the References section below.
Given lead time (the period of time from when the customer makes their booking to when they actually stay at the hotel), along with ADR (average daily rate per customer), the k-means clustering algorithm is used to visually identify which market segments are most profitable for the hotel.
A customer with a high ADR and a low lead time is ideal, as it means that 1) the customer is paying a high daily rate which means a greater profit margin for the hotel, while a low lead time means that the customer pays for their booking quicker — which increases cash flow for the hotel in question.
The data is loaded and 100 samples are chosen at random:
df = pd.read_csv('H1full.csv')df = df.sample(n = 100)
The interval (or continuous random variables) are of lead time and ADR are defined as below:
leadtime = df['LeadTime']adr = df['ADR']
Variables with a categorical component are defined using ‘’’cat.codes’’’, in this case market segment.
marketsegmentcat=df.MarketSegment.astype("category").cat.codesmarketsegmentcat=pd.Series(marketsegmentcat)
The purpose of this is to assign categorical codes to each market segment. For instance, here is a snippet of some of the market segment entries in the dataset:
10871 Online TA7752 Online TA35566 Offline TA/TO1353 Online TA17532 Online TA ... 1312 Online TA10364 Groups16113 Direct23633 Online TA23406 Direct
Upon applying cat.codes, here are the corresponding categories.
10871 47752 435566 31353 417532 4 ..1312 410364 216113 123633 423406 1
The market segment labels are as follows:
0 = Corporate
1 = Direct
2 = Groups
3 = Offline TA/TO
4 = Online TA
The lead time and ADR features are scaled using sklearn:
from sklearn.preprocessing import scaleX = scale(x1)
Here is a sample of X:
array([[ 1.07577693, -1.01441847], [-0.75329711, 2.25432473], [-0.60321924, -0.80994917], [-0.20926483, 0.26328418], [ 0.53174465, -0.40967609], [-0.82833604, 0.40156369], [-0.89399511, -1.01810593], [ 0.59740372, 1.40823851], [-0.89399511, -1.16560407],
When it comes to choosing the number of clusters, one possible solution is to use what is called the elbow method. Here is an example of an elbow curve:
This is a technique whereby the in-cluster variance for each cluster is calculated — the lower the variance, the tighter the cluster.
In this regard, as the score starts to flatten out, this means that the reduction in variance becomes less and less as we increase the number of clusters, which allows us to determine the ideal value for k.
However, this technique is not necessarily suitable for smaller clusters. Moreover, we already know the number of clusters (k=5) that we wish to define, as we already know the number of market segments that we wish to analyse.
Additionally, while k-means clustering methods may also use PCA (or Principal Dimensionality Reduction) to reduce the number of features, this is not appropriate in this case as the only two features being used (apart from market segment) are ADR and lead time.
Accordingly, the k-means algorithm is defined as follows:
>>> km = KMeans(n_clusters = 5, n_jobs = None, random_state = None)>>> km.fit(X)KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300, n_clusters=5, n_init=10, n_jobs=None, precompute_distances='auto', random_state=None, tol=0.0001, verbose=0)
The color themes are defined for each of the market segment labels:
# Market Segment Labels: 0 (Complementary) = firebrick, 1 (Corporate) = dodgerblue, 2 (Direct) = forestgreen, 3 (Groups) = goldenrod, 4 (Offline TA/TO) = rebeccapurplecolor_theme = np.array(['firebrick', 'dodgerblue', 'forestgreen', 'goldenrod', 'rebeccapurple'])
Here is a plot of the actual labels:
Here is a plot of the generated clusters by the k-means algorithm:
As mentioned, customers with the lowest lead time and the highest ADR are deemed to be the most profitable.
However, there seems to be a problem! Many of the market segment categories have been mislabelled.
This is a common problem when working with k-means clustering, and does not necessarily indicate that the model should be thrown out! Instead, it merely suggests that we need to think about our data in a different way.
For instance, we already know which customers belong to which market segment. In this regard, generating a k-means clustering algorithm to predict this once again does not serve much use. Rather, the point of running this algorithm is to get a quick visual of what types of customers are most profitable.
Furthermore, we have only considered lead time and ADR as the two features. There may be other features that we have not considered which would better indicate what market segment a customer might belong to, and there is no visual evidence from what we have seen so far that certain market segments are more profitable than others.
In this regard, let’s simplify the analysis a little bit. What if we use three clusters instead?
We see that the blue category has the highest ADR and lowest lead time (most profitable), while the green category shows the lowest ADR and highest lead time (least profitable).
From this standpoint, the k-means clustering algorithm is offering an efficient way at quickly categorising the hotel’s most profitable customers and further analysis can be conducted to analyse certain attributes that are common to the customers in each group.
When it comes to unsupervised learning — it is important to remember that this is largely an exploratory method of analysis — the goal is not necessarily prediction but rather to reveal insights about the data that may not have been considered previously. For instance, why do certain customers have a lower lead time than others? Are customers from certain countries more likely to fit this profile? What about different customer types?
These are all questions that the k-means clustering algorithm may not directly answer for us — but reducing data into separate clusters provides a strong baseline for being able to pose questions such as these.
In this example, we have seen:
How to use Python to conduct k-means clustering
Use of k-means clustering in segmenting hotel customers by profitability
Configuration of data to use the k-means model effectively
Many thanks for your time, and the associated GitHub repository for this example can be found here.
Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way.
Antonio, Almeida, and Nunes: Using Data Science to Predict Hotel Booking Cancellations
OpenClassrooms: Carry Out A K-Means Clustering
Medium: PREDICTING IRIS FLOWER SPECIES WITH K-MEANS CLUSTERING IN PYTHON
Towards Data Science: When Clustering Doesn’t Make Sense
Variance Explained: K-Means Clustering Is Not A Free Lunch
|
[
{
"code": null,
"e": 266,
"s": 172,
"text": "In this instance, K-Means is used to analyse market segment clusters for a hotel in Portugal."
},
{
"code": null,
"e": 383,
"s": 266,
"text": "This analysis is based on the original study by Antonio, Almeida and Nunes as cited in the References section below."
},
{
"code": null,
"e": 673,
"s": 383,
"text": "Given lead time (the period of time from when the customer makes their booking to when they actually stay at the hotel), along with ADR (average daily rate per customer), the k-means clustering algorithm is used to visually identify which market segments are most profitable for the hotel."
},
{
"code": null,
"e": 974,
"s": 673,
"text": "A customer with a high ADR and a low lead time is ideal, as it means that 1) the customer is paying a high daily rate which means a greater profit margin for the hotel, while a low lead time means that the customer pays for their booking quicker — which increases cash flow for the hotel in question."
},
{
"code": null,
"e": 1031,
"s": 974,
"text": "The data is loaded and 100 samples are chosen at random:"
},
{
"code": null,
"e": 1085,
"s": 1031,
"text": "df = pd.read_csv('H1full.csv')df = df.sample(n = 100)"
},
{
"code": null,
"e": 1178,
"s": 1085,
"text": "The interval (or continuous random variables) are of lead time and ADR are defined as below:"
},
{
"code": null,
"e": 1219,
"s": 1178,
"text": "leadtime = df['LeadTime']adr = df['ADR']"
},
{
"code": null,
"e": 1322,
"s": 1219,
"text": "Variables with a categorical component are defined using ‘’’cat.codes’’’, in this case market segment."
},
{
"code": null,
"e": 1429,
"s": 1322,
"text": "marketsegmentcat=df.MarketSegment.astype(\"category\").cat.codesmarketsegmentcat=pd.Series(marketsegmentcat)"
},
{
"code": null,
"e": 1590,
"s": 1429,
"text": "The purpose of this is to assign categorical codes to each market segment. For instance, here is a snippet of some of the market segment entries in the dataset:"
},
{
"code": null,
"e": 1833,
"s": 1590,
"text": "10871 Online TA7752 Online TA35566 Offline TA/TO1353 Online TA17532 Online TA ... 1312 Online TA10364 Groups16113 Direct23633 Online TA23406 Direct"
},
{
"code": null,
"e": 1897,
"s": 1833,
"text": "Upon applying cat.codes, here are the corresponding categories."
},
{
"code": null,
"e": 2008,
"s": 1897,
"text": "10871 47752 435566 31353 417532 4 ..1312 410364 216113 123633 423406 1"
},
{
"code": null,
"e": 2050,
"s": 2008,
"text": "The market segment labels are as follows:"
},
{
"code": null,
"e": 2064,
"s": 2050,
"text": "0 = Corporate"
},
{
"code": null,
"e": 2075,
"s": 2064,
"text": "1 = Direct"
},
{
"code": null,
"e": 2086,
"s": 2075,
"text": "2 = Groups"
},
{
"code": null,
"e": 2104,
"s": 2086,
"text": "3 = Offline TA/TO"
},
{
"code": null,
"e": 2118,
"s": 2104,
"text": "4 = Online TA"
},
{
"code": null,
"e": 2175,
"s": 2118,
"text": "The lead time and ADR features are scaled using sklearn:"
},
{
"code": null,
"e": 2228,
"s": 2175,
"text": "from sklearn.preprocessing import scaleX = scale(x1)"
},
{
"code": null,
"e": 2251,
"s": 2228,
"text": "Here is a sample of X:"
},
{
"code": null,
"e": 2558,
"s": 2251,
"text": "array([[ 1.07577693, -1.01441847], [-0.75329711, 2.25432473], [-0.60321924, -0.80994917], [-0.20926483, 0.26328418], [ 0.53174465, -0.40967609], [-0.82833604, 0.40156369], [-0.89399511, -1.01810593], [ 0.59740372, 1.40823851], [-0.89399511, -1.16560407],"
},
{
"code": null,
"e": 2711,
"s": 2558,
"text": "When it comes to choosing the number of clusters, one possible solution is to use what is called the elbow method. Here is an example of an elbow curve:"
},
{
"code": null,
"e": 2845,
"s": 2711,
"text": "This is a technique whereby the in-cluster variance for each cluster is calculated — the lower the variance, the tighter the cluster."
},
{
"code": null,
"e": 3052,
"s": 2845,
"text": "In this regard, as the score starts to flatten out, this means that the reduction in variance becomes less and less as we increase the number of clusters, which allows us to determine the ideal value for k."
},
{
"code": null,
"e": 3279,
"s": 3052,
"text": "However, this technique is not necessarily suitable for smaller clusters. Moreover, we already know the number of clusters (k=5) that we wish to define, as we already know the number of market segments that we wish to analyse."
},
{
"code": null,
"e": 3541,
"s": 3279,
"text": "Additionally, while k-means clustering methods may also use PCA (or Principal Dimensionality Reduction) to reduce the number of features, this is not appropriate in this case as the only two features being used (apart from market segment) are ADR and lead time."
},
{
"code": null,
"e": 3599,
"s": 3541,
"text": "Accordingly, the k-means algorithm is defined as follows:"
},
{
"code": null,
"e": 3870,
"s": 3599,
"text": ">>> km = KMeans(n_clusters = 5, n_jobs = None, random_state = None)>>> km.fit(X)KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300, n_clusters=5, n_init=10, n_jobs=None, precompute_distances='auto', random_state=None, tol=0.0001, verbose=0)"
},
{
"code": null,
"e": 3938,
"s": 3870,
"text": "The color themes are defined for each of the market segment labels:"
},
{
"code": null,
"e": 4202,
"s": 3938,
"text": "# Market Segment Labels: 0 (Complementary) = firebrick, 1 (Corporate) = dodgerblue, 2 (Direct) = forestgreen, 3 (Groups) = goldenrod, 4 (Offline TA/TO) = rebeccapurplecolor_theme = np.array(['firebrick', 'dodgerblue', 'forestgreen', 'goldenrod', 'rebeccapurple'])"
},
{
"code": null,
"e": 4239,
"s": 4202,
"text": "Here is a plot of the actual labels:"
},
{
"code": null,
"e": 4306,
"s": 4239,
"text": "Here is a plot of the generated clusters by the k-means algorithm:"
},
{
"code": null,
"e": 4414,
"s": 4306,
"text": "As mentioned, customers with the lowest lead time and the highest ADR are deemed to be the most profitable."
},
{
"code": null,
"e": 4513,
"s": 4414,
"text": "However, there seems to be a problem! Many of the market segment categories have been mislabelled."
},
{
"code": null,
"e": 4732,
"s": 4513,
"text": "This is a common problem when working with k-means clustering, and does not necessarily indicate that the model should be thrown out! Instead, it merely suggests that we need to think about our data in a different way."
},
{
"code": null,
"e": 5037,
"s": 4732,
"text": "For instance, we already know which customers belong to which market segment. In this regard, generating a k-means clustering algorithm to predict this once again does not serve much use. Rather, the point of running this algorithm is to get a quick visual of what types of customers are most profitable."
},
{
"code": null,
"e": 5369,
"s": 5037,
"text": "Furthermore, we have only considered lead time and ADR as the two features. There may be other features that we have not considered which would better indicate what market segment a customer might belong to, and there is no visual evidence from what we have seen so far that certain market segments are more profitable than others."
},
{
"code": null,
"e": 5466,
"s": 5369,
"text": "In this regard, let’s simplify the analysis a little bit. What if we use three clusters instead?"
},
{
"code": null,
"e": 5644,
"s": 5466,
"text": "We see that the blue category has the highest ADR and lowest lead time (most profitable), while the green category shows the lowest ADR and highest lead time (least profitable)."
},
{
"code": null,
"e": 5906,
"s": 5644,
"text": "From this standpoint, the k-means clustering algorithm is offering an efficient way at quickly categorising the hotel’s most profitable customers and further analysis can be conducted to analyse certain attributes that are common to the customers in each group."
},
{
"code": null,
"e": 6344,
"s": 5906,
"text": "When it comes to unsupervised learning — it is important to remember that this is largely an exploratory method of analysis — the goal is not necessarily prediction but rather to reveal insights about the data that may not have been considered previously. For instance, why do certain customers have a lower lead time than others? Are customers from certain countries more likely to fit this profile? What about different customer types?"
},
{
"code": null,
"e": 6555,
"s": 6344,
"text": "These are all questions that the k-means clustering algorithm may not directly answer for us — but reducing data into separate clusters provides a strong baseline for being able to pose questions such as these."
},
{
"code": null,
"e": 6586,
"s": 6555,
"text": "In this example, we have seen:"
},
{
"code": null,
"e": 6634,
"s": 6586,
"text": "How to use Python to conduct k-means clustering"
},
{
"code": null,
"e": 6707,
"s": 6634,
"text": "Use of k-means clustering in segmenting hotel customers by profitability"
},
{
"code": null,
"e": 6766,
"s": 6707,
"text": "Configuration of data to use the k-means model effectively"
},
{
"code": null,
"e": 6866,
"s": 6766,
"text": "Many thanks for your time, and the associated GitHub repository for this example can be found here."
},
{
"code": null,
"e": 7094,
"s": 6866,
"text": "Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way."
},
{
"code": null,
"e": 7181,
"s": 7094,
"text": "Antonio, Almeida, and Nunes: Using Data Science to Predict Hotel Booking Cancellations"
},
{
"code": null,
"e": 7228,
"s": 7181,
"text": "OpenClassrooms: Carry Out A K-Means Clustering"
},
{
"code": null,
"e": 7301,
"s": 7228,
"text": "Medium: PREDICTING IRIS FLOWER SPECIES WITH K-MEANS CLUSTERING IN PYTHON"
},
{
"code": null,
"e": 7358,
"s": 7301,
"text": "Towards Data Science: When Clustering Doesn’t Make Sense"
}
] |
File and Directory Management
|
Here, we will learn the concepts of File and Directory Management −
File is nothing but a collection of information. The information can be of numbers, characters, graphs, images, etc. Every file should be stored under a unique name for its future reference. Every file should be saved along with an extension. Some of the extensions and their description are given below −
.avi
Microsoft videos for Windows movie
.dbf
dbase II, III, IV data file
.doc(x)
Microsoft word for windows
.gif
Graphics Interchange Format
.htm
Hypertext Markup Language
.html
Hypertext Markup Language
.jpg
JPEG graphics file
.mpg
MPEG video file
.mid
MIDI music file
.mov
QuickTime movie
File should be represented in address bar along with path of the file, filename and extension.
For example: C:\Windows\system32\Hello.html
In which C:\Windows\system32 → path
Hello → filename
.html → extension.
Directory is a place/area/location where a set of file(s) will be stored. It is a folder which contains details about files, file size and time when they are created and last modified. The different types of directories are discussed below −
Root Directory is created when we start formatting the disk and start putting files on it. In this, we can create new directories called "sub-directories". Root directory is the highest level directory and is seen when booting a system.
Subdirectory is a directory inside root directory, in turn, it can have another sub-directory in it.
107 Lectures
13.5 hours
Arnab Chakraborty
106 Lectures
8 hours
Arnab Chakraborty
99 Lectures
6 hours
Arnab Chakraborty
46 Lectures
2.5 hours
Shweta
70 Lectures
9 hours
Abhilash Nelson
52 Lectures
7 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1938,
"s": 1870,
"text": "Here, we will learn the concepts of File and Directory Management −"
},
{
"code": null,
"e": 2244,
"s": 1938,
"text": "File is nothing but a collection of information. The information can be of numbers, characters, graphs, images, etc. Every file should be stored under a unique name for its future reference. Every file should be saved along with an extension. Some of the extensions and their description are given below −"
},
{
"code": null,
"e": 2249,
"s": 2244,
"text": ".avi"
},
{
"code": null,
"e": 2284,
"s": 2249,
"text": "Microsoft videos for Windows movie"
},
{
"code": null,
"e": 2289,
"s": 2284,
"text": ".dbf"
},
{
"code": null,
"e": 2317,
"s": 2289,
"text": "dbase II, III, IV data file"
},
{
"code": null,
"e": 2325,
"s": 2317,
"text": ".doc(x)"
},
{
"code": null,
"e": 2352,
"s": 2325,
"text": "Microsoft word for windows"
},
{
"code": null,
"e": 2357,
"s": 2352,
"text": ".gif"
},
{
"code": null,
"e": 2385,
"s": 2357,
"text": "Graphics Interchange Format"
},
{
"code": null,
"e": 2390,
"s": 2385,
"text": ".htm"
},
{
"code": null,
"e": 2416,
"s": 2390,
"text": "Hypertext Markup Language"
},
{
"code": null,
"e": 2422,
"s": 2416,
"text": ".html"
},
{
"code": null,
"e": 2448,
"s": 2422,
"text": "Hypertext Markup Language"
},
{
"code": null,
"e": 2453,
"s": 2448,
"text": ".jpg"
},
{
"code": null,
"e": 2472,
"s": 2453,
"text": "JPEG graphics file"
},
{
"code": null,
"e": 2477,
"s": 2472,
"text": ".mpg"
},
{
"code": null,
"e": 2493,
"s": 2477,
"text": "MPEG video file"
},
{
"code": null,
"e": 2498,
"s": 2493,
"text": ".mid"
},
{
"code": null,
"e": 2514,
"s": 2498,
"text": "MIDI music file"
},
{
"code": null,
"e": 2519,
"s": 2514,
"text": ".mov"
},
{
"code": null,
"e": 2535,
"s": 2519,
"text": "QuickTime movie"
},
{
"code": null,
"e": 2630,
"s": 2535,
"text": "File should be represented in address bar along with path of the file, filename and extension."
},
{
"code": null,
"e": 2753,
"s": 2630,
"text": "For example: C:\\Windows\\system32\\Hello.html\nIn which C:\\Windows\\system32 → path\n Hello → filename\n .html → extension.\n"
},
{
"code": null,
"e": 2995,
"s": 2753,
"text": "Directory is a place/area/location where a set of file(s) will be stored. It is a folder which contains details about files, file size and time when they are created and last modified. The different types of directories are discussed below −"
},
{
"code": null,
"e": 3232,
"s": 2995,
"text": "Root Directory is created when we start formatting the disk and start putting files on it. In this, we can create new directories called \"sub-directories\". Root directory is the highest level directory and is seen when booting a system."
},
{
"code": null,
"e": 3333,
"s": 3232,
"text": "Subdirectory is a directory inside root directory, in turn, it can have another sub-directory in it."
},
{
"code": null,
"e": 3370,
"s": 3333,
"text": "\n 107 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 3389,
"s": 3370,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3423,
"s": 3389,
"text": "\n 106 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3442,
"s": 3423,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3475,
"s": 3442,
"text": "\n 99 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3494,
"s": 3475,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3529,
"s": 3494,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3537,
"s": 3529,
"text": " Shweta"
},
{
"code": null,
"e": 3570,
"s": 3537,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3587,
"s": 3570,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3620,
"s": 3587,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3642,
"s": 3620,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3649,
"s": 3642,
"text": " Print"
},
{
"code": null,
"e": 3660,
"s": 3649,
"text": " Add Notes"
}
] |
How to show shaking / wobble view animation in android?
|
This example demonstrate about How to show shaking / wobble view animation in android.
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">
<Button
android:id = "@+id/button"
android:layout_centerHorizontal = "true"
android:layout_marginTop = "100dp"
android:layout_width = "150dp"
android:text = "Click"
android:layout_height = "wrap_content"/>
<ImageView
android:id = "@+id/imageView"
android:src = "@mipmap/ic_launcher_round"
android:layout_width = "match_parent"
android:layout_height = "300dp" />
</RelativeLayout>
In the above code, we have taken button to show shake animation for image view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
ImageView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = findViewById(R.id.imageView);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Animation animShake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.shake);
view.startAnimation(animShake);
}
});
}
}
In the above code, when user click on button, it will shake imageview using shake animation for that we need to create a file called shake.xml in anim folder. Add the following code in shake.xml -
<?xml version = "1.0" encoding = "utf-8"?>
<set xmlns:android = "http://schemas.android.com/apk/res/android">
<translate android:duration = "150"
android:fromXDelta = "-10%"
android:repeatCount = "5"
android:repeatMode = "reverse"
android:toXDelta = "10%"/>
</set>
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 −
Now click on button to shake background image as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "This example demonstrate about How to show shaking / wobble view animation in android."
},
{
"code": null,
"e": 1278,
"s": 1149,
"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": 1343,
"s": 1278,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2048,
"s": 1343,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout\n 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 <Button\n android:id = \"@+id/button\"\n android:layout_centerHorizontal = \"true\"\n android:layout_marginTop = \"100dp\"\n android:layout_width = \"150dp\"\n android:text = \"Click\"\n android:layout_height = \"wrap_content\"/>\n <ImageView\n android:id = \"@+id/imageView\"\n android:src = \"@mipmap/ic_launcher_round\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"300dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2128,
"s": 2048,
"text": "In the above code, we have taken button to show shake animation for image view."
},
{
"code": null,
"e": 2185,
"s": 2128,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3190,
"s": 2185,
"text": "package com.example.andy.myapplication;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.animation.Animation;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.ScaleAnimation;\nimport android.view.animation.TranslateAnimation;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\n\npublic class MainActivity extends AppCompatActivity {\n ImageView view;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n view = findViewById(R.id.imageView);\n findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Animation animShake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.shake);\n view.startAnimation(animShake);\n }\n });\n }\n}"
},
{
"code": null,
"e": 3387,
"s": 3190,
"text": "In the above code, when user click on button, it will shake imageview using shake animation for that we need to create a file called shake.xml in anim folder. Add the following code in shake.xml -"
},
{
"code": null,
"e": 3679,
"s": 3387,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<set xmlns:android = \"http://schemas.android.com/apk/res/android\">\n <translate android:duration = \"150\"\n android:fromXDelta = \"-10%\"\n android:repeatCount = \"5\"\n android:repeatMode = \"reverse\"\n android:toXDelta = \"10%\"/>\n</set>"
},
{
"code": null,
"e": 4027,
"s": 3679,
"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": 4090,
"s": 4027,
"text": "Now click on button to shake background image as shown below -"
},
{
"code": null,
"e": 4130,
"s": 4090,
"text": "Click here to download the project code"
}
] |
ASP.NET - Event Handling
|
An event is an action or occurrence such as a mouse click, a key press, mouse movements, or any system-generated notification. A process communicates through events. For example, interrupts are system-generated events. When events occur, the application should be able to respond to it and manage it.
Events in ASP.NET raised at the client machine, and handled at the server machine. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server.
The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler. If it has, the event handler is executed.
ASP.NET event handlers generally take two parameters and return void. The first parameter represents the object raising the event and the second parameter is event argument.
The general syntax of an event is:
private void EventName (object sender, EventArgs e);
The most important application events are:
Application_Start - It is raised when the application/website is started.
Application_Start - It is raised when the application/website is started.
Application_End - It is raised when the application/website is stopped.
Application_End - It is raised when the application/website is stopped.
Similarly, the most used Session events are:
Session_Start - It is raised when a user first requests a page from the application.
Session_Start - It is raised when a user first requests a page from the application.
Session_End - It is raised when the session ends.
Session_End - It is raised when the session ends.
Common page and control events are:
DataBinding - It is raised when a control binds to a data source.
DataBinding - It is raised when a control binds to a data source.
Disposed - It is raised when the page or the control is released.
Disposed - It is raised when the page or the control is released.
Error - It is a page event, occurs when an unhandled exception is thrown.
Error - It is a page event, occurs when an unhandled exception is thrown.
Init - It is raised when the page or the control is initialized.
Init - It is raised when the page or the control is initialized.
Load - It is raised when the page or a control is loaded.
Load - It is raised when the page or a control is loaded.
PreRender - It is raised when the page or the control is to be rendered.
PreRender - It is raised when the page or the control is to be rendered.
Unload - It is raised when the page or control is unloaded from memory.
Unload - It is raised when the page or control is unloaded from memory.
All ASP.NET controls are implemented as classes, and they have events which are fired when a user performs a certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling events, there are in-built attributes and event handlers. Event handler is coded to respond to an event, and take appropriate action on it.
By default, Visual Studio creates an event handler by including a Handles clause on the Sub procedure. This clause names the control and event that the procedure handles.
The ASP tag for a button control:
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
The event handler for the Click event:
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles btnCancel.Click
End Sub
An event can also be coded without Handles clause. Then, the handler must be named according to the appropriate event attribute of the control.
The ASP tag for a button control:
<asp:Button ID="btnCancel" runat="server" Text="Cancel" Onclick="btnCancel_Click" />
The event handler for the Click event:
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
End Sub
The common control events are:
Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click event such as, Button.Click.
Some events are not posted back to the server immediately, these are called non-postback events.
For example, the change events or selection events such as TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true.
The default event for the Page object is Load event. Similarly, every control has a default event. For example, default event for the button control is the Click event.
The default event handler could be created in Visual Studio, just by double clicking the control in design view. The following table shows some of the default events for common controls:
This example includes a simple page with a label control and a button control on it. As the page events such as Page_Load, Page_Init, Page_PreRender etc. take place, it sends a message, which is displayed by the label control. When the button is clicked, the Button_Click event is raised and that also sends a message to be displayed on the label.
Create a new website and drag a label control and a button control on it from the control tool box. Using the properties window, set the IDs of the controls as .lblmessage. and .btnclick. respectively. Set the Text property of the Button control as 'Click'.
The markup file (.aspx):
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="eventdemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblmessage" runat="server" >
</asp:Label>
<br />
<br />
<br />
<asp:Button ID="btnclick" runat="server" Text="Click" onclick="btnclick_Click" />
</div>
</form>
</body>
</html>
Double click on the design view to move to the code behind file. The Page_Load event is automatically created without any code in it. Write down the following self-explanatory code lines:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace eventdemo {
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
lblmessage.Text += "Page load event handled. <br />";
if (Page.IsPostBack) {
lblmessage.Text += "Page post back event handled.<br/>";
}
}
protected void Page_Init(object sender, EventArgs e) {
lblmessage.Text += "Page initialization event handled.<br/>";
}
protected void Page_PreRender(object sender, EventArgs e) {
lblmessage.Text += "Page prerender event handled. <br/>";
}
protected void btnclick_Click(object sender, EventArgs e) {
lblmessage.Text += "Button click event handled. <br/>";
}
}
}
Execute the page. The label shows page load, page initialization and, the page pre-render events. Click the button to see effect:
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2648,
"s": 2347,
"text": "An event is an action or occurrence such as a mouse click, a key press, mouse movements, or any system-generated notification. A process communicates through events. For example, interrupts are system-generated events. When events occur, the application should be able to respond to it and manage it."
},
{
"code": null,
"e": 2890,
"s": 2648,
"text": "Events in ASP.NET raised at the client machine, and handled at the server machine. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server."
},
{
"code": null,
"e": 3171,
"s": 2890,
"text": "The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler. If it has, the event handler is executed."
},
{
"code": null,
"e": 3345,
"s": 3171,
"text": "ASP.NET event handlers generally take two parameters and return void. The first parameter represents the object raising the event and the second parameter is event argument."
},
{
"code": null,
"e": 3380,
"s": 3345,
"text": "The general syntax of an event is:"
},
{
"code": null,
"e": 3433,
"s": 3380,
"text": "private void EventName (object sender, EventArgs e);"
},
{
"code": null,
"e": 3476,
"s": 3433,
"text": "The most important application events are:"
},
{
"code": null,
"e": 3550,
"s": 3476,
"text": "Application_Start - It is raised when the application/website is started."
},
{
"code": null,
"e": 3624,
"s": 3550,
"text": "Application_Start - It is raised when the application/website is started."
},
{
"code": null,
"e": 3696,
"s": 3624,
"text": "Application_End - It is raised when the application/website is stopped."
},
{
"code": null,
"e": 3768,
"s": 3696,
"text": "Application_End - It is raised when the application/website is stopped."
},
{
"code": null,
"e": 3813,
"s": 3768,
"text": "Similarly, the most used Session events are:"
},
{
"code": null,
"e": 3898,
"s": 3813,
"text": "Session_Start - It is raised when a user first requests a page from the application."
},
{
"code": null,
"e": 3983,
"s": 3898,
"text": "Session_Start - It is raised when a user first requests a page from the application."
},
{
"code": null,
"e": 4033,
"s": 3983,
"text": "Session_End - It is raised when the session ends."
},
{
"code": null,
"e": 4083,
"s": 4033,
"text": "Session_End - It is raised when the session ends."
},
{
"code": null,
"e": 4119,
"s": 4083,
"text": "Common page and control events are:"
},
{
"code": null,
"e": 4185,
"s": 4119,
"text": "DataBinding - It is raised when a control binds to a data source."
},
{
"code": null,
"e": 4251,
"s": 4185,
"text": "DataBinding - It is raised when a control binds to a data source."
},
{
"code": null,
"e": 4317,
"s": 4251,
"text": "Disposed - It is raised when the page or the control is released."
},
{
"code": null,
"e": 4383,
"s": 4317,
"text": "Disposed - It is raised when the page or the control is released."
},
{
"code": null,
"e": 4457,
"s": 4383,
"text": "Error - It is a page event, occurs when an unhandled exception is thrown."
},
{
"code": null,
"e": 4531,
"s": 4457,
"text": "Error - It is a page event, occurs when an unhandled exception is thrown."
},
{
"code": null,
"e": 4596,
"s": 4531,
"text": "Init - It is raised when the page or the control is initialized."
},
{
"code": null,
"e": 4661,
"s": 4596,
"text": "Init - It is raised when the page or the control is initialized."
},
{
"code": null,
"e": 4719,
"s": 4661,
"text": "Load - It is raised when the page or a control is loaded."
},
{
"code": null,
"e": 4777,
"s": 4719,
"text": "Load - It is raised when the page or a control is loaded."
},
{
"code": null,
"e": 4850,
"s": 4777,
"text": "PreRender - It is raised when the page or the control is to be rendered."
},
{
"code": null,
"e": 4923,
"s": 4850,
"text": "PreRender - It is raised when the page or the control is to be rendered."
},
{
"code": null,
"e": 4995,
"s": 4923,
"text": "Unload - It is raised when the page or control is unloaded from memory."
},
{
"code": null,
"e": 5067,
"s": 4995,
"text": "Unload - It is raised when the page or control is unloaded from memory."
},
{
"code": null,
"e": 5426,
"s": 5067,
"text": "All ASP.NET controls are implemented as classes, and they have events which are fired when a user performs a certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling events, there are in-built attributes and event handlers. Event handler is coded to respond to an event, and take appropriate action on it."
},
{
"code": null,
"e": 5597,
"s": 5426,
"text": "By default, Visual Studio creates an event handler by including a Handles clause on the Sub procedure. This clause names the control and event that the procedure handles."
},
{
"code": null,
"e": 5631,
"s": 5597,
"text": "The ASP tag for a button control:"
},
{
"code": null,
"e": 5690,
"s": 5631,
"text": "<asp:Button ID=\"btnCancel\" runat=\"server\" Text=\"Cancel\" />"
},
{
"code": null,
"e": 5729,
"s": 5690,
"text": "The event handler for the Click event:"
},
{
"code": null,
"e": 5853,
"s": 5729,
"text": "Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) \n\n Handles btnCancel.Click\n \nEnd Sub"
},
{
"code": null,
"e": 5997,
"s": 5853,
"text": "An event can also be coded without Handles clause. Then, the handler must be named according to the appropriate event attribute of the control."
},
{
"code": null,
"e": 6031,
"s": 5997,
"text": "The ASP tag for a button control:"
},
{
"code": null,
"e": 6116,
"s": 6031,
"text": "<asp:Button ID=\"btnCancel\" runat=\"server\" Text=\"Cancel\" Onclick=\"btnCancel_Click\" />"
},
{
"code": null,
"e": 6155,
"s": 6116,
"text": "The event handler for the Click event:"
},
{
"code": null,
"e": 6247,
"s": 6155,
"text": "Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)\n\nEnd Sub"
},
{
"code": null,
"e": 6278,
"s": 6247,
"text": "The common control events are:"
},
{
"code": null,
"e": 6440,
"s": 6278,
"text": "Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click event such as, Button.Click."
},
{
"code": null,
"e": 6537,
"s": 6440,
"text": "Some events are not posted back to the server immediately, these are called non-postback events."
},
{
"code": null,
"e": 6754,
"s": 6537,
"text": "For example, the change events or selection events such as TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true."
},
{
"code": null,
"e": 6923,
"s": 6754,
"text": "The default event for the Page object is Load event. Similarly, every control has a default event. For example, default event for the button control is the Click event."
},
{
"code": null,
"e": 7110,
"s": 6923,
"text": "The default event handler could be created in Visual Studio, just by double clicking the control in design view. The following table shows some of the default events for common controls:"
},
{
"code": null,
"e": 7458,
"s": 7110,
"text": "This example includes a simple page with a label control and a button control on it. As the page events such as Page_Load, Page_Init, Page_PreRender etc. take place, it sends a message, which is displayed by the label control. When the button is clicked, the Button_Click event is raised and that also sends a message to be displayed on the label."
},
{
"code": null,
"e": 7716,
"s": 7458,
"text": "Create a new website and drag a label control and a button control on it from the control tool box. Using the properties window, set the IDs of the controls as .lblmessage. and .btnclick. respectively. Set the Text property of the Button control as 'Click'."
},
{
"code": null,
"e": 7741,
"s": 7716,
"text": "The markup file (.aspx):"
},
{
"code": null,
"e": 8490,
"s": 7741,
"text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" \n Inherits=\"eventdemo._Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\n <head runat=\"server\">\n <title>Untitled Page</title>\n </head>\n \n <body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <asp:Label ID=\"lblmessage\" runat=\"server\" >\n \n </asp:Label>\n \n <br />\n <br />\n <br />\n \n <asp:Button ID=\"btnclick\" runat=\"server\" Text=\"Click\" onclick=\"btnclick_Click\" />\n </div>\n </form>\n </body>\n \n</html>"
},
{
"code": null,
"e": 8678,
"s": 8490,
"text": "Double click on the design view to move to the code behind file. The Page_Load event is automatically created without any code in it. Write down the following self-explanatory code lines:"
},
{
"code": null,
"e": 9770,
"s": 8678,
"text": "using System;\nusing System.Collections;\nusing System.Configuration;\nusing System.Data;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.HtmlControls;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\n\nusing System.Xml.Linq;\n\nnamespace eventdemo {\n\n public partial class _Default : System.Web.UI.Page {\n \n protected void Page_Load(object sender, EventArgs e) {\n lblmessage.Text += \"Page load event handled. <br />\";\n \n if (Page.IsPostBack) {\n lblmessage.Text += \"Page post back event handled.<br/>\";\n }\n }\n \n protected void Page_Init(object sender, EventArgs e) {\n lblmessage.Text += \"Page initialization event handled.<br/>\";\n }\n \n protected void Page_PreRender(object sender, EventArgs e) {\n lblmessage.Text += \"Page prerender event handled. <br/>\";\n }\n \n protected void btnclick_Click(object sender, EventArgs e) {\n lblmessage.Text += \"Button click event handled. <br/>\";\n }\n }\n}"
},
{
"code": null,
"e": 9900,
"s": 9770,
"text": "Execute the page. The label shows page load, page initialization and, the page pre-render events. Click the button to see effect:"
},
{
"code": null,
"e": 9935,
"s": 9900,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9949,
"s": 9935,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9984,
"s": 9949,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10007,
"s": 9984,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 10041,
"s": 10007,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 10061,
"s": 10041,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 10096,
"s": 10061,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10113,
"s": 10096,
"text": " University Code"
},
{
"code": null,
"e": 10148,
"s": 10113,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10165,
"s": 10148,
"text": " University Code"
},
{
"code": null,
"e": 10199,
"s": 10165,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 10214,
"s": 10199,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 10221,
"s": 10214,
"text": " Print"
},
{
"code": null,
"e": 10232,
"s": 10221,
"text": " Add Notes"
}
] |
Fine-tuning a BERT model with transformers | by Thiago G. Martins | Towards Data Science
|
This post describes a simple way to get started with fine-tuning transformer models. It will cover the basics and introduce you to the amazing Trainer class from the transformers library. You can run the code from Google Colab but do not forget to enable GPU support.
We use a dataset built from COVID-19 Open Research Dataset Challenge. This work is one small piece of a larger project that is to build the cord19 search app.
!pip install pandas transformers
To fine-tune the BERT models for the cord19 application, we need to generate a set of query-document features and labels that indicate which documents are relevant for the specific queries. For this exercise, we will use the query string to represent the query and the title string to represent the documents.
training_data = read_csv("https://thigm85.github.io/data/cord19/cord19-query-title-label.csv")training_data.head()
There are 50 unique queries.
len(training_data["query"].unique())50
For each query, we have a list of documents, divided between relevant (label=1) and irrelevant (label=0).
training_data[["title", "label"]].groupby("label").count()
We are going to use a simple data split into train and validation sets for illustration purposes. Even though we have more than 50 thousand data points when considering unique query and document pairs, I believe this specific case would benefit from cross-validation since it has only 50 queries containing relevance judgment.
from sklearn.model_selection import train_test_splittrain_queries, val_queries, train_docs, val_docs, train_labels, val_labels = train_test_split( training_data["query"].tolist(), training_data["title"].tolist(), training_data["label"].tolist(), test_size=.2)
Create a train and validation encodings. To do that, we need to chose which BERT model to use. We will use padding and truncation because the training routine expects all tensors within a batch to have the same dimensions.
from transformers import BertTokenizerFastmodel_name = "google/bert_uncased_L-4_H-512_A-8"tokenizer = BertTokenizerFast.from_pretrained(model_name)train_encodings = tokenizer(train_queries, train_docs, truncation=True, padding='max_length', max_length=128)val_encodings = tokenizer(val_queries, val_docs, truncation=True, padding='max_length', max_length=128)
Now that we have the encodings and the labels, we can create a Dataset object as described in the transformers webpage about custom datasets.
import torchclass Cord19Dataset(torch.utils.data.Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labels def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.labels)train_dataset = Cord19Dataset(train_encodings, train_labels)val_dataset = Cord19Dataset(val_encodings, val_labels)
We are going to use BertForSequenceClassification, since we are trying to classify query and document pairs into two distinct classes (non-relevant, relevant).
from transformers import BertForSequenceClassificationmodel = BertForSequenceClassification.from_pretrained(model_name)
We can set requires_grad to False for all the base model parameters to fine-tune only the task-specific parameters.
for param in model.base_model.parameters(): param.requires_grad = False
We can then fine-tune the model with Trainer. Below is a basic routine with an out-of-the-box set of parameters. Care should be taken when choosing the parameters below, but this is out of this piece's scope.
from transformers import Trainer, TrainingArgumentstraining_args = TrainingArguments( output_dir='./results', # output directory evaluation_strategy="epoch", # Evaluation is done at the end of each epoch. num_train_epochs=3, # total number of training epochs per_device_train_batch_size=16, # batch size per device during training per_device_eval_batch_size=64, # batch size for evaluation warmup_steps=500, # number of warmup steps for learning rate scheduler weight_decay=0.01, # strength of weight decay save_total_limit=1, # limit the total amount of checkpoints. Deletes the older checkpoints. )trainer = Trainer( model=model, # the instantiated 🤗 Transformers model to be trained args=training_args, # training arguments, defined above train_dataset=train_dataset, # training dataset eval_dataset=val_dataset # evaluation dataset)trainer.train()
Once training is complete, we can export the model using the ONNX format to be deployed elsewhere. I assume below that you have access to a GPU, which you can get from Google Colab, for example.
from torch.onnx import exportdevice = torch.device("cuda") model_onnx_path = "model.onnx"dummy_input = ( train_dataset[0]["input_ids"].unsqueeze(0).to(device), train_dataset[0]["token_type_ids"].unsqueeze(0).to(device), train_dataset[0]["attention_mask"].unsqueeze(0).to(device))input_names = ["input_ids", "token_type_ids", "attention_mask"]output_names = ["logits"]export( model, dummy_input, model_onnx_path, input_names = input_names, output_names = output_names, verbose=False, opset_version=11)
As mentioned before, this post covered basic training setup. This is a good starting point to be improved upon. It is better to start simple and complement than the opposite, especially when learning something new. I left important topics such as hyperparameter tuning, cross-validation, and more detailed model validation to followup posts. But having a basic training setup is a good first step.
|
[
{
"code": null,
"e": 440,
"s": 172,
"text": "This post describes a simple way to get started with fine-tuning transformer models. It will cover the basics and introduce you to the amazing Trainer class from the transformers library. You can run the code from Google Colab but do not forget to enable GPU support."
},
{
"code": null,
"e": 599,
"s": 440,
"text": "We use a dataset built from COVID-19 Open Research Dataset Challenge. This work is one small piece of a larger project that is to build the cord19 search app."
},
{
"code": null,
"e": 632,
"s": 599,
"text": "!pip install pandas transformers"
},
{
"code": null,
"e": 942,
"s": 632,
"text": "To fine-tune the BERT models for the cord19 application, we need to generate a set of query-document features and labels that indicate which documents are relevant for the specific queries. For this exercise, we will use the query string to represent the query and the title string to represent the documents."
},
{
"code": null,
"e": 1057,
"s": 942,
"text": "training_data = read_csv(\"https://thigm85.github.io/data/cord19/cord19-query-title-label.csv\")training_data.head()"
},
{
"code": null,
"e": 1086,
"s": 1057,
"text": "There are 50 unique queries."
},
{
"code": null,
"e": 1125,
"s": 1086,
"text": "len(training_data[\"query\"].unique())50"
},
{
"code": null,
"e": 1231,
"s": 1125,
"text": "For each query, we have a list of documents, divided between relevant (label=1) and irrelevant (label=0)."
},
{
"code": null,
"e": 1290,
"s": 1231,
"text": "training_data[[\"title\", \"label\"]].groupby(\"label\").count()"
},
{
"code": null,
"e": 1617,
"s": 1290,
"text": "We are going to use a simple data split into train and validation sets for illustration purposes. Even though we have more than 50 thousand data points when considering unique query and document pairs, I believe this specific case would benefit from cross-validation since it has only 50 queries containing relevance judgment."
},
{
"code": null,
"e": 1892,
"s": 1617,
"text": "from sklearn.model_selection import train_test_splittrain_queries, val_queries, train_docs, val_docs, train_labels, val_labels = train_test_split( training_data[\"query\"].tolist(), training_data[\"title\"].tolist(), training_data[\"label\"].tolist(), test_size=.2)"
},
{
"code": null,
"e": 2115,
"s": 1892,
"text": "Create a train and validation encodings. To do that, we need to chose which BERT model to use. We will use padding and truncation because the training routine expects all tensors within a batch to have the same dimensions."
},
{
"code": null,
"e": 2475,
"s": 2115,
"text": "from transformers import BertTokenizerFastmodel_name = \"google/bert_uncased_L-4_H-512_A-8\"tokenizer = BertTokenizerFast.from_pretrained(model_name)train_encodings = tokenizer(train_queries, train_docs, truncation=True, padding='max_length', max_length=128)val_encodings = tokenizer(val_queries, val_docs, truncation=True, padding='max_length', max_length=128)"
},
{
"code": null,
"e": 2617,
"s": 2475,
"text": "Now that we have the encodings and the labels, we can create a Dataset object as described in the transformers webpage about custom datasets."
},
{
"code": null,
"e": 3135,
"s": 2617,
"text": "import torchclass Cord19Dataset(torch.utils.data.Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labels def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.labels)train_dataset = Cord19Dataset(train_encodings, train_labels)val_dataset = Cord19Dataset(val_encodings, val_labels)"
},
{
"code": null,
"e": 3295,
"s": 3135,
"text": "We are going to use BertForSequenceClassification, since we are trying to classify query and document pairs into two distinct classes (non-relevant, relevant)."
},
{
"code": null,
"e": 3415,
"s": 3295,
"text": "from transformers import BertForSequenceClassificationmodel = BertForSequenceClassification.from_pretrained(model_name)"
},
{
"code": null,
"e": 3531,
"s": 3415,
"text": "We can set requires_grad to False for all the base model parameters to fine-tune only the task-specific parameters."
},
{
"code": null,
"e": 3606,
"s": 3531,
"text": "for param in model.base_model.parameters(): param.requires_grad = False"
},
{
"code": null,
"e": 3815,
"s": 3606,
"text": "We can then fine-tune the model with Trainer. Below is a basic routine with an out-of-the-box set of parameters. Care should be taken when choosing the parameters below, but this is out of this piece's scope."
},
{
"code": null,
"e": 4838,
"s": 3815,
"text": "from transformers import Trainer, TrainingArgumentstraining_args = TrainingArguments( output_dir='./results', # output directory evaluation_strategy=\"epoch\", # Evaluation is done at the end of each epoch. num_train_epochs=3, # total number of training epochs per_device_train_batch_size=16, # batch size per device during training per_device_eval_batch_size=64, # batch size for evaluation warmup_steps=500, # number of warmup steps for learning rate scheduler weight_decay=0.01, # strength of weight decay save_total_limit=1, # limit the total amount of checkpoints. Deletes the older checkpoints. )trainer = Trainer( model=model, # the instantiated 🤗 Transformers model to be trained args=training_args, # training arguments, defined above train_dataset=train_dataset, # training dataset eval_dataset=val_dataset # evaluation dataset)trainer.train()"
},
{
"code": null,
"e": 5033,
"s": 4838,
"text": "Once training is complete, we can export the model using the ONNX format to be deployed elsewhere. I assume below that you have access to a GPU, which you can get from Google Colab, for example."
},
{
"code": null,
"e": 5552,
"s": 5033,
"text": "from torch.onnx import exportdevice = torch.device(\"cuda\") model_onnx_path = \"model.onnx\"dummy_input = ( train_dataset[0][\"input_ids\"].unsqueeze(0).to(device), train_dataset[0][\"token_type_ids\"].unsqueeze(0).to(device), train_dataset[0][\"attention_mask\"].unsqueeze(0).to(device))input_names = [\"input_ids\", \"token_type_ids\", \"attention_mask\"]output_names = [\"logits\"]export( model, dummy_input, model_onnx_path, input_names = input_names, output_names = output_names, verbose=False, opset_version=11)"
}
] |
Unix / Linux - File System Basics
|
A file system is a logical collection of files on a partition or disk. A partition is a container for information and can span an entire hard drive if desired.
Your hard drive can have various partitions which usually contain only one file system, such as one file system housing the /file system or another containing the /home file system.
One file system per partition allows for the logical maintenance and management of differing file systems.
Everything in Unix is considered to be a file, including physical devices such as DVD-ROMs, USB devices, and floppy drives.
Unix uses a hierarchical file system structure, much like an upside-down tree, with root (/) at the base of the file system and all other directories spreading from there.
A Unix filesystem is a collection of files and directories that has the following properties −
It has a root directory (/) that contains other files and directories.
It has a root directory (/) that contains other files and directories.
Each file or directory is uniquely identified by its name, the directory in which it resides, and a unique identifier, typically called an inode.
Each file or directory is uniquely identified by its name, the directory in which it resides, and a unique identifier, typically called an inode.
By convention, the root directory has an inode number of 2 and the lost+found directory has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can be seen by specifying the -i option to ls command.
By convention, the root directory has an inode number of 2 and the lost+found directory has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can be seen by specifying the -i option to ls command.
It is self-contained. There are no dependencies between one filesystem and another.
It is self-contained. There are no dependencies between one filesystem and another.
The directories have specific purposes and generally hold the same types of information for easily locating files. Following are the directories that exist on the major versions of Unix −
/
This is the root directory which should contain only the directories needed at the top level of the file structure
/bin
This is where the executable files are located. These files are available to all users
/dev
These are device drivers
/etc
Supervisor directory commands, configuration files, disk configuration files, valid user lists, groups, ethernet, hosts, where to send critical messages
/lib
Contains shared library files and sometimes other kernel-related files
/boot
Contains files for booting the system
/home
Contains the home directory for users and other accounts
/mnt
Used to mount other temporary file systems, such as cdrom and floppy for the CD-ROM drive and floppy diskette drive, respectively
/proc
Contains all processes marked as a file by process number or other information that is dynamic to the system
/tmp
Holds temporary files used between system boots
/usr
Used for miscellaneous purposes, and can be used by many users. Includes administrative commands, shared files, library files, and others
/var
Typically contains variable-length files such as log and print files and any other type of file that may contain a variable amount of data
/sbin
Contains binary (executable) files, usually for system administration. For example, fdisk and ifconfig utlities
/kernel
Contains kernel files
Now that you understand the basics of the file system, you can begin navigating to the files you need. The following commands are used to navigate the system −
cat filename
Displays a filename
cd dirname
Moves you to the identified directory
cp file1 file2
Copies one file/directory to the specified location
file filename
Identifies the file type (binary, text, etc)
find filename dir
Finds a file/directory
head filename
Shows the beginning of a file
less filename
Browses through a file from the end or the beginning
ls dirname
Shows the contents of the directory specified
mkdir dirname
Creates the specified directory
more filename
Browses through a file from the beginning to the end
mv file1 file2
Moves the location of, or renames a file/directory
pwd
Shows the current directory the user is in
rm filename
Removes a file
rmdir dirname
Removes a directory
tail filename
Shows the end of a file
touch filename
Creates a blank file or modifies an existing file or its attributes
whereis filename
Shows the location of a file
which filename
Shows the location of a file if it is in your PATH
You can use Manpage Help to check complete syntax for each command mentioned here.
The first way to manage your partition space is with the df (disk free) command. The command df -k (disk free) displays the disk space usage in kilobytes, as shown below −
$df -k
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/vzfs 10485760 7836644 2649116 75% /
/devices 0 0 0 0% /devices
$
Some of the directories, such as /devices, shows 0 in the kbytes, used, and avail columns as well as 0% for capacity. These are special (or virtual) file systems, and although they reside on the disk under /, by themselves they do not consume disk space.
The df -k output is generally the same on all Unix systems. Here's what it usually includes −
Filesystem
The physical file system name
kbytes
Total kilobytes of space available on the storage medium
used
Total kilobytes of space used (by files)
avail
Total kilobytes available for use
capacity
Percentage of total space used by files
Mounted on
What the file system is mounted on
You can use the -h (human readable) option to display the output in a format that shows the size in easier-to-understand notation.
The du (disk usage) command enables you to specify directories to show disk space usage on a particular directory.
This command is helpful if you want to determine how much space a particular directory is taking. The following command displays number of blocks consumed by each directory. A single block may take either 512 Bytes or 1 Kilo Byte depending on your system.
$du /etc
10 /etc/cron.d
126 /etc/default
6 /etc/dfs
...
$
The -h option makes the output easier to comprehend −
$du -h /etc
5k /etc/cron.d
63k /etc/default
3k /etc/dfs
...
$
A file system must be mounted in order to be usable by the system. To see what is currently mounted (available for use) on your system, use the following command −
$ mount
/dev/vzfs on / type reiserfs (rw,usrquota,grpquota)
proc on /proc type proc (rw,nodiratime)
devpts on /dev/pts type devpts (rw)
$
The /mnt directory, by the Unix convention, is where temporary mounts (such as CDROM drives, remote network drives, and floppy drives) are located. If you need to mount a file system, you can use the mount command with the following syntax −
mount -t file_system_type device_to_mount directory_to_mount_to
For example, if you want to mount a CD-ROM to the directory /mnt/cdrom, you can type −
$ mount -t iso9660 /dev/cdrom /mnt/cdrom
This assumes that your CD-ROM device is called /dev/cdrom and that you want to mount it to /mnt/cdrom. Refer to the mount man page for more specific information or type mount -h at the command line for help information.
After mounting, you can use the cd command to navigate the newly available file system through the mount point you just made.
To unmount (remove) the file system from your system, use the umount command by identifying the mount point or device.
For example, to unmount cdrom, use the following command −
$ umount /dev/cdrom
The mount command enables you to access your file systems, but on most modern Unix systems, the automount function makes this process invisible to the user and requires no intervention.
The user and group quotas provide the mechanisms by which the amount of space used by a single user or all users within a specific group can be limited to a value defined by the administrator.
Quotas operate around two limits that allow the user to take some action if the amount of space or number of disk blocks start to exceed the administrator defined limits −
Soft Limit − If the user exceeds the limit defined, there is a grace period that allows the user to free up some space.
Soft Limit − If the user exceeds the limit defined, there is a grace period that allows the user to free up some space.
Hard Limit − When the hard limit is reached, regardless of the grace period, no further files or blocks can be allocated.
Hard Limit − When the hard limit is reached, regardless of the grace period, no further files or blocks can be allocated.
There are a number of commands to administer quotas −
quota
Displays disk usage and limits for a user of group
edquota
This is a quota editor. Users or Groups quota can be edited using this command
quotacheck
Scans a filesystem for disk usage, creates, checks and repairs quota files
setquota
This is a command line quota editor
quotaon
This announces to the system that disk quotas should be enabled on one or more filesystems
quotaoff
This announces to the system that disk quotas should be disabled for one or more filesystems
repquota
This prints a summary of the disc usage and quotas for the specified file systems
You can use Manpage Help to check complete syntax for each command mentioned here.
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": 2907,
"s": 2747,
"text": "A file system is a logical collection of files on a partition or disk. A partition is a container for information and can span an entire hard drive if desired."
},
{
"code": null,
"e": 3089,
"s": 2907,
"text": "Your hard drive can have various partitions which usually contain only one file system, such as one file system housing the /file system or another containing the /home file system."
},
{
"code": null,
"e": 3196,
"s": 3089,
"text": "One file system per partition allows for the logical maintenance and management of differing file systems."
},
{
"code": null,
"e": 3320,
"s": 3196,
"text": "Everything in Unix is considered to be a file, including physical devices such as DVD-ROMs, USB devices, and floppy drives."
},
{
"code": null,
"e": 3492,
"s": 3320,
"text": "Unix uses a hierarchical file system structure, much like an upside-down tree, with root (/) at the base of the file system and all other directories spreading from there."
},
{
"code": null,
"e": 3587,
"s": 3492,
"text": "A Unix filesystem is a collection of files and directories that has the following properties −"
},
{
"code": null,
"e": 3658,
"s": 3587,
"text": "It has a root directory (/) that contains other files and directories."
},
{
"code": null,
"e": 3729,
"s": 3658,
"text": "It has a root directory (/) that contains other files and directories."
},
{
"code": null,
"e": 3875,
"s": 3729,
"text": "Each file or directory is uniquely identified by its name, the directory in which it resides, and a unique identifier, typically called an inode."
},
{
"code": null,
"e": 4021,
"s": 3875,
"text": "Each file or directory is uniquely identified by its name, the directory in which it resides, and a unique identifier, typically called an inode."
},
{
"code": null,
"e": 4245,
"s": 4021,
"text": "By convention, the root directory has an inode number of 2 and the lost+found directory has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can be seen by specifying the -i option to ls command."
},
{
"code": null,
"e": 4469,
"s": 4245,
"text": "By convention, the root directory has an inode number of 2 and the lost+found directory has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can be seen by specifying the -i option to ls command."
},
{
"code": null,
"e": 4553,
"s": 4469,
"text": "It is self-contained. There are no dependencies between one filesystem and another."
},
{
"code": null,
"e": 4637,
"s": 4553,
"text": "It is self-contained. There are no dependencies between one filesystem and another."
},
{
"code": null,
"e": 4825,
"s": 4637,
"text": "The directories have specific purposes and generally hold the same types of information for easily locating files. Following are the directories that exist on the major versions of Unix −"
},
{
"code": null,
"e": 4827,
"s": 4825,
"text": "/"
},
{
"code": null,
"e": 4942,
"s": 4827,
"text": "This is the root directory which should contain only the directories needed at the top level of the file structure"
},
{
"code": null,
"e": 4947,
"s": 4942,
"text": "/bin"
},
{
"code": null,
"e": 5034,
"s": 4947,
"text": "This is where the executable files are located. These files are available to all users"
},
{
"code": null,
"e": 5039,
"s": 5034,
"text": "/dev"
},
{
"code": null,
"e": 5064,
"s": 5039,
"text": "These are device drivers"
},
{
"code": null,
"e": 5069,
"s": 5064,
"text": "/etc"
},
{
"code": null,
"e": 5222,
"s": 5069,
"text": "Supervisor directory commands, configuration files, disk configuration files, valid user lists, groups, ethernet, hosts, where to send critical messages"
},
{
"code": null,
"e": 5227,
"s": 5222,
"text": "/lib"
},
{
"code": null,
"e": 5298,
"s": 5227,
"text": "Contains shared library files and sometimes other kernel-related files"
},
{
"code": null,
"e": 5304,
"s": 5298,
"text": "/boot"
},
{
"code": null,
"e": 5342,
"s": 5304,
"text": "Contains files for booting the system"
},
{
"code": null,
"e": 5348,
"s": 5342,
"text": "/home"
},
{
"code": null,
"e": 5405,
"s": 5348,
"text": "Contains the home directory for users and other accounts"
},
{
"code": null,
"e": 5410,
"s": 5405,
"text": "/mnt"
},
{
"code": null,
"e": 5540,
"s": 5410,
"text": "Used to mount other temporary file systems, such as cdrom and floppy for the CD-ROM drive and floppy diskette drive, respectively"
},
{
"code": null,
"e": 5546,
"s": 5540,
"text": "/proc"
},
{
"code": null,
"e": 5655,
"s": 5546,
"text": "Contains all processes marked as a file by process number or other information that is dynamic to the system"
},
{
"code": null,
"e": 5660,
"s": 5655,
"text": "/tmp"
},
{
"code": null,
"e": 5708,
"s": 5660,
"text": "Holds temporary files used between system boots"
},
{
"code": null,
"e": 5713,
"s": 5708,
"text": "/usr"
},
{
"code": null,
"e": 5851,
"s": 5713,
"text": "Used for miscellaneous purposes, and can be used by many users. Includes administrative commands, shared files, library files, and others"
},
{
"code": null,
"e": 5856,
"s": 5851,
"text": "/var"
},
{
"code": null,
"e": 5995,
"s": 5856,
"text": "Typically contains variable-length files such as log and print files and any other type of file that may contain a variable amount of data"
},
{
"code": null,
"e": 6001,
"s": 5995,
"text": "/sbin"
},
{
"code": null,
"e": 6113,
"s": 6001,
"text": "Contains binary (executable) files, usually for system administration. For example, fdisk and ifconfig utlities"
},
{
"code": null,
"e": 6121,
"s": 6113,
"text": "/kernel"
},
{
"code": null,
"e": 6143,
"s": 6121,
"text": "Contains kernel files"
},
{
"code": null,
"e": 6303,
"s": 6143,
"text": "Now that you understand the basics of the file system, you can begin navigating to the files you need. The following commands are used to navigate the system −"
},
{
"code": null,
"e": 6316,
"s": 6303,
"text": "cat filename"
},
{
"code": null,
"e": 6336,
"s": 6316,
"text": "Displays a filename"
},
{
"code": null,
"e": 6347,
"s": 6336,
"text": "cd dirname"
},
{
"code": null,
"e": 6385,
"s": 6347,
"text": "Moves you to the identified directory"
},
{
"code": null,
"e": 6400,
"s": 6385,
"text": "cp file1 file2"
},
{
"code": null,
"e": 6452,
"s": 6400,
"text": "Copies one file/directory to the specified location"
},
{
"code": null,
"e": 6466,
"s": 6452,
"text": "file filename"
},
{
"code": null,
"e": 6511,
"s": 6466,
"text": "Identifies the file type (binary, text, etc)"
},
{
"code": null,
"e": 6529,
"s": 6511,
"text": "find filename dir"
},
{
"code": null,
"e": 6552,
"s": 6529,
"text": "Finds a file/directory"
},
{
"code": null,
"e": 6566,
"s": 6552,
"text": "head filename"
},
{
"code": null,
"e": 6596,
"s": 6566,
"text": "Shows the beginning of a file"
},
{
"code": null,
"e": 6610,
"s": 6596,
"text": "less filename"
},
{
"code": null,
"e": 6663,
"s": 6610,
"text": "Browses through a file from the end or the beginning"
},
{
"code": null,
"e": 6674,
"s": 6663,
"text": "ls dirname"
},
{
"code": null,
"e": 6720,
"s": 6674,
"text": "Shows the contents of the directory specified"
},
{
"code": null,
"e": 6734,
"s": 6720,
"text": "mkdir dirname"
},
{
"code": null,
"e": 6766,
"s": 6734,
"text": "Creates the specified directory"
},
{
"code": null,
"e": 6780,
"s": 6766,
"text": "more filename"
},
{
"code": null,
"e": 6833,
"s": 6780,
"text": "Browses through a file from the beginning to the end"
},
{
"code": null,
"e": 6848,
"s": 6833,
"text": "mv file1 file2"
},
{
"code": null,
"e": 6899,
"s": 6848,
"text": "Moves the location of, or renames a file/directory"
},
{
"code": null,
"e": 6903,
"s": 6899,
"text": "pwd"
},
{
"code": null,
"e": 6946,
"s": 6903,
"text": "Shows the current directory the user is in"
},
{
"code": null,
"e": 6958,
"s": 6946,
"text": "rm filename"
},
{
"code": null,
"e": 6973,
"s": 6958,
"text": "Removes a file"
},
{
"code": null,
"e": 6987,
"s": 6973,
"text": "rmdir dirname"
},
{
"code": null,
"e": 7007,
"s": 6987,
"text": "Removes a directory"
},
{
"code": null,
"e": 7021,
"s": 7007,
"text": "tail filename"
},
{
"code": null,
"e": 7045,
"s": 7021,
"text": "Shows the end of a file"
},
{
"code": null,
"e": 7060,
"s": 7045,
"text": "touch filename"
},
{
"code": null,
"e": 7128,
"s": 7060,
"text": "Creates a blank file or modifies an existing file or its attributes"
},
{
"code": null,
"e": 7145,
"s": 7128,
"text": "whereis filename"
},
{
"code": null,
"e": 7174,
"s": 7145,
"text": "Shows the location of a file"
},
{
"code": null,
"e": 7189,
"s": 7174,
"text": "which filename"
},
{
"code": null,
"e": 7240,
"s": 7189,
"text": "Shows the location of a file if it is in your PATH"
},
{
"code": null,
"e": 7323,
"s": 7240,
"text": "You can use Manpage Help to check complete syntax for each command mentioned here."
},
{
"code": null,
"e": 7495,
"s": 7323,
"text": "The first way to manage your partition space is with the df (disk free) command. The command df -k (disk free) displays the disk space usage in kilobytes, as shown below −"
},
{
"code": null,
"e": 7686,
"s": 7495,
"text": "$df -k\nFilesystem 1K-blocks Used Available Use% Mounted on\n/dev/vzfs 10485760 7836644 2649116 75% /\n/devices 0 0 0 0% /devices\n$\n"
},
{
"code": null,
"e": 7941,
"s": 7686,
"text": "Some of the directories, such as /devices, shows 0 in the kbytes, used, and avail columns as well as 0% for capacity. These are special (or virtual) file systems, and although they reside on the disk under /, by themselves they do not consume disk space."
},
{
"code": null,
"e": 8035,
"s": 7941,
"text": "The df -k output is generally the same on all Unix systems. Here's what it usually includes −"
},
{
"code": null,
"e": 8046,
"s": 8035,
"text": "Filesystem"
},
{
"code": null,
"e": 8076,
"s": 8046,
"text": "The physical file system name"
},
{
"code": null,
"e": 8083,
"s": 8076,
"text": "kbytes"
},
{
"code": null,
"e": 8140,
"s": 8083,
"text": "Total kilobytes of space available on the storage medium"
},
{
"code": null,
"e": 8145,
"s": 8140,
"text": "used"
},
{
"code": null,
"e": 8186,
"s": 8145,
"text": "Total kilobytes of space used (by files)"
},
{
"code": null,
"e": 8192,
"s": 8186,
"text": "avail"
},
{
"code": null,
"e": 8226,
"s": 8192,
"text": "Total kilobytes available for use"
},
{
"code": null,
"e": 8235,
"s": 8226,
"text": "capacity"
},
{
"code": null,
"e": 8275,
"s": 8235,
"text": "Percentage of total space used by files"
},
{
"code": null,
"e": 8286,
"s": 8275,
"text": "Mounted on"
},
{
"code": null,
"e": 8321,
"s": 8286,
"text": "What the file system is mounted on"
},
{
"code": null,
"e": 8452,
"s": 8321,
"text": "You can use the -h (human readable) option to display the output in a format that shows the size in easier-to-understand notation."
},
{
"code": null,
"e": 8567,
"s": 8452,
"text": "The du (disk usage) command enables you to specify directories to show disk space usage on a particular directory."
},
{
"code": null,
"e": 8823,
"s": 8567,
"text": "This command is helpful if you want to determine how much space a particular directory is taking. The following command displays number of blocks consumed by each directory. A single block may take either 512 Bytes or 1 Kilo Byte depending on your system."
},
{
"code": null,
"e": 8894,
"s": 8823,
"text": "$du /etc\n10 /etc/cron.d\n126 /etc/default\n6 /etc/dfs\n...\n$\n"
},
{
"code": null,
"e": 8948,
"s": 8894,
"text": "The -h option makes the output easier to comprehend −"
},
{
"code": null,
"e": 9018,
"s": 8948,
"text": "$du -h /etc\n5k /etc/cron.d\n63k /etc/default\n3k /etc/dfs\n...\n$"
},
{
"code": null,
"e": 9182,
"s": 9018,
"text": "A file system must be mounted in order to be usable by the system. To see what is currently mounted (available for use) on your system, use the following command −"
},
{
"code": null,
"e": 9321,
"s": 9182,
"text": "$ mount\n/dev/vzfs on / type reiserfs (rw,usrquota,grpquota)\nproc on /proc type proc (rw,nodiratime)\ndevpts on /dev/pts type devpts (rw)\n$\n"
},
{
"code": null,
"e": 9563,
"s": 9321,
"text": "The /mnt directory, by the Unix convention, is where temporary mounts (such as CDROM drives, remote network drives, and floppy drives) are located. If you need to mount a file system, you can use the mount command with the following syntax −"
},
{
"code": null,
"e": 9628,
"s": 9563,
"text": "mount -t file_system_type device_to_mount directory_to_mount_to\n"
},
{
"code": null,
"e": 9715,
"s": 9628,
"text": "For example, if you want to mount a CD-ROM to the directory /mnt/cdrom, you can type −"
},
{
"code": null,
"e": 9757,
"s": 9715,
"text": "$ mount -t iso9660 /dev/cdrom /mnt/cdrom\n"
},
{
"code": null,
"e": 9977,
"s": 9757,
"text": "This assumes that your CD-ROM device is called /dev/cdrom and that you want to mount it to /mnt/cdrom. Refer to the mount man page for more specific information or type mount -h at the command line for help information."
},
{
"code": null,
"e": 10103,
"s": 9977,
"text": "After mounting, you can use the cd command to navigate the newly available file system through the mount point you just made."
},
{
"code": null,
"e": 10222,
"s": 10103,
"text": "To unmount (remove) the file system from your system, use the umount command by identifying the mount point or device."
},
{
"code": null,
"e": 10281,
"s": 10222,
"text": "For example, to unmount cdrom, use the following command −"
},
{
"code": null,
"e": 10302,
"s": 10281,
"text": "$ umount /dev/cdrom\n"
},
{
"code": null,
"e": 10488,
"s": 10302,
"text": "The mount command enables you to access your file systems, but on most modern Unix systems, the automount function makes this process invisible to the user and requires no intervention."
},
{
"code": null,
"e": 10681,
"s": 10488,
"text": "The user and group quotas provide the mechanisms by which the amount of space used by a single user or all users within a specific group can be limited to a value defined by the administrator."
},
{
"code": null,
"e": 10853,
"s": 10681,
"text": "Quotas operate around two limits that allow the user to take some action if the amount of space or number of disk blocks start to exceed the administrator defined limits −"
},
{
"code": null,
"e": 10973,
"s": 10853,
"text": "Soft Limit − If the user exceeds the limit defined, there is a grace period that allows the user to free up some space."
},
{
"code": null,
"e": 11093,
"s": 10973,
"text": "Soft Limit − If the user exceeds the limit defined, there is a grace period that allows the user to free up some space."
},
{
"code": null,
"e": 11215,
"s": 11093,
"text": "Hard Limit − When the hard limit is reached, regardless of the grace period, no further files or blocks can be allocated."
},
{
"code": null,
"e": 11337,
"s": 11215,
"text": "Hard Limit − When the hard limit is reached, regardless of the grace period, no further files or blocks can be allocated."
},
{
"code": null,
"e": 11391,
"s": 11337,
"text": "There are a number of commands to administer quotas −"
},
{
"code": null,
"e": 11397,
"s": 11391,
"text": "quota"
},
{
"code": null,
"e": 11448,
"s": 11397,
"text": "Displays disk usage and limits for a user of group"
},
{
"code": null,
"e": 11456,
"s": 11448,
"text": "edquota"
},
{
"code": null,
"e": 11535,
"s": 11456,
"text": "This is a quota editor. Users or Groups quota can be edited using this command"
},
{
"code": null,
"e": 11546,
"s": 11535,
"text": "quotacheck"
},
{
"code": null,
"e": 11621,
"s": 11546,
"text": "Scans a filesystem for disk usage, creates, checks and repairs quota files"
},
{
"code": null,
"e": 11630,
"s": 11621,
"text": "setquota"
},
{
"code": null,
"e": 11666,
"s": 11630,
"text": "This is a command line quota editor"
},
{
"code": null,
"e": 11674,
"s": 11666,
"text": "quotaon"
},
{
"code": null,
"e": 11765,
"s": 11674,
"text": "This announces to the system that disk quotas should be enabled on one or more filesystems"
},
{
"code": null,
"e": 11774,
"s": 11765,
"text": "quotaoff"
},
{
"code": null,
"e": 11867,
"s": 11774,
"text": "This announces to the system that disk quotas should be disabled for one or more filesystems"
},
{
"code": null,
"e": 11876,
"s": 11867,
"text": "repquota"
},
{
"code": null,
"e": 11958,
"s": 11876,
"text": "This prints a summary of the disc usage and quotas for the specified file systems"
},
{
"code": null,
"e": 12041,
"s": 11958,
"text": "You can use Manpage Help to check complete syntax for each command mentioned here."
},
{
"code": null,
"e": 12076,
"s": 12041,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12104,
"s": 12076,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12138,
"s": 12104,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12155,
"s": 12138,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12188,
"s": 12155,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12199,
"s": 12188,
"text": " Pradeep D"
},
{
"code": null,
"e": 12234,
"s": 12199,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12250,
"s": 12234,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12283,
"s": 12250,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12295,
"s": 12283,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12327,
"s": 12295,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12335,
"s": 12327,
"text": " Uplatz"
},
{
"code": null,
"e": 12342,
"s": 12335,
"text": " Print"
},
{
"code": null,
"e": 12353,
"s": 12342,
"text": " Add Notes"
}
] |
C library function - sqrt()
|
The C library function double sqrt(double x) returns the square root of x.
Following is the declaration for sqrt() function.
double sqrt(double x)
x − This is the floating point value.
x − This is the floating point value.
This function returns the square root of x.
The following example shows the usage of sqrt() function.
#include <stdio.h>
#include <math.h>
int main () {
printf("Square root of %lf is %lf\n", 4.0, sqrt(4.0) );
printf("Square root of %lf is %lf\n", 5.0, sqrt(5.0) );
return(0);
}
Let us compile and run the above program that will produce the following result −
Square root of 4.000000 is 2.000000
Square root of 5.000000 is 2.236068
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2082,
"s": 2007,
"text": "The C library function double sqrt(double x) returns the square root of x."
},
{
"code": null,
"e": 2132,
"s": 2082,
"text": "Following is the declaration for sqrt() function."
},
{
"code": null,
"e": 2154,
"s": 2132,
"text": "double sqrt(double x)"
},
{
"code": null,
"e": 2192,
"s": 2154,
"text": "x − This is the floating point value."
},
{
"code": null,
"e": 2230,
"s": 2192,
"text": "x − This is the floating point value."
},
{
"code": null,
"e": 2274,
"s": 2230,
"text": "This function returns the square root of x."
},
{
"code": null,
"e": 2332,
"s": 2274,
"text": "The following example shows the usage of sqrt() function."
},
{
"code": null,
"e": 2523,
"s": 2332,
"text": "#include <stdio.h>\n#include <math.h>\n\nint main () {\n\n printf(\"Square root of %lf is %lf\\n\", 4.0, sqrt(4.0) );\n printf(\"Square root of %lf is %lf\\n\", 5.0, sqrt(5.0) );\n \n return(0);\n}"
},
{
"code": null,
"e": 2605,
"s": 2523,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 2678,
"s": 2605,
"text": "Square root of 4.000000 is 2.000000\nSquare root of 5.000000 is 2.236068\n"
},
{
"code": null,
"e": 2711,
"s": 2678,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2726,
"s": 2711,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2761,
"s": 2726,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2776,
"s": 2761,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2811,
"s": 2776,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2825,
"s": 2811,
"text": " Asif Hussain"
},
{
"code": null,
"e": 2858,
"s": 2825,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2876,
"s": 2858,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 2911,
"s": 2876,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2930,
"s": 2911,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 2963,
"s": 2930,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2975,
"s": 2963,
"text": " Amit Diwan"
},
{
"code": null,
"e": 2982,
"s": 2975,
"text": " Print"
},
{
"code": null,
"e": 2993,
"s": 2982,
"text": " Add Notes"
}
] |
Sum of first N natural numbers which are divisible by X or Y - GeeksforGeeks
|
11 May, 2022
Given a number N. Given two numbers X and Y, the task is to find the sum of all those numbers from 1 to N that are divisible by X or by Y.Examples:
Input : N = 20
Output : 98
Input : N = 14
Output : 45
Approach: To solve the problem, follow the below steps:->Find the sum of numbers that are divisible by X upto N. Denote it by S1. ->Find the sum of numbers that are divisible by Y upto N. Denote it by S2. ->Find the sum of numbers that are divisible by both X and Y (X*Y) upto N. Denote it by S3. ->The final answer will be S1 + S2 – S3.In order to find the sum, we can use the general formula of A.P. which is:
Sn = (n/2) * {2*a + (n-1)*d}
For S1: The total numbers that will be divisible by X upto N will be N/X and the sum will be:
Hence,
S1 = ((N/X)/2) * (2 * X + (N/X - 1) * X)
For S2: The total numbers that will be divisible by Y upto N will be N/Y and the sum will be:
Hence,
S2 = ((N/Y)/2) * (2 * Y + (N/Y - 1) * Y)
For S3: The total numbers that will be divisible by both X and Y upto N will be N/(X*Y) and the sum will be:
Hence,
S2 = ((N/(X*Y))/2) * (2 * Y + (N/(X*Y) - 1) * (X*Y))
Therefore, the result will be:
S = S1 + S2 - S3
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
C
// C++ program to find sum of numbers from// 1 to N which are divisible by X or Y#include <bits/stdc++.h>using namespace std; // Function to calculate the sum// of numbers divisible by X or Yint sum(int N, int X, int Y){ int S1, S2, S3; S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2; S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2; S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3;} // Driver codeint main(){ int N = 14; int X = 3, Y = 5; cout << sum(N, X, Y); return 0;}
// Java program to find sum of numbers from// 1 to N which are divisible by X or Y public class GFG{ // Function to calculate the sum // of numbers divisible by X or Y static int sum(int N, int X, int Y) { int S1, S2, S3; S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2; S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2; S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3; } // Driver code public static void main(String []args) { int N = 14; int X = 3, Y = 5; System.out.println(sum(N, X, Y)); } // This code is contributed by Ryuga}
# Python 3 program to find sum of numbers from# 1 to N which are divisible by X or Yfrom math import ceil, floor # Function to calculate the sum# of numbers divisible by X or Ydef sum(N, X, Y): S1 = floor(floor(N / X) * floor(2 * X + floor(N / X - 1) * X) / 2) S2 = floor(floor(N / Y)) * floor(2 * Y + floor(N / Y - 1) * Y) / 2 S3 = floor(floor(N / (X * Y))) * floor (2 * (X * Y) + floor(N / (X * Y) - 1) * (X * Y))/ 2 return S1 + S2 - S3 # Driver codeif __name__ == '__main__': N = 14 X = 3 Y = 5 print(int(sum(N, X, Y))) # This code is contributed by# Surendra_Gangwar
// C# program to find sum of numbers from// 1 to N which are divisible by X or Y using System;public class GFG{ // Function to calculate the sum // of numbers divisible by X or Y static int sum(int N, int X, int Y) { int S1, S2, S3; S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2; S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2; S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3; } // Driver code public static void Main() { int N = 14; int X = 3, Y = 5; Console.Write(sum(N, X, Y)); } }
<?php// PHP program to find sum of numbers from// 1 to N which are divisible by X or Y// Function to calculate the sum// of numbers divisible by X or Yfunction sum($N, $X, $Y){ $S1; $S2; $S3; $S1 = floor(((int)$N / $X)) * (2 * $X + (int)((int)$N / $X - 1) * $X) / 2; $S2 = floor(((int)$N / $Y)) * (2 * $Y + (int)((int)$N / $Y - 1) * $Y) / 2; $S3 = floor(((int)$N / ($X * $Y))) * (2 * ($X * $Y) + ((int)$N / ($X * $Y) - 1) * (int)($X * $Y))/ 2; return ceil($S1 + ($S2 - $S3));} // Driver code $N = 14; $X = 3; $Y = 5; echo sum($N, $X, $Y); #This code is contributed by ajit.?>
<script>// javascript program to find sum of numbers from// 1 to N which are divisible by X or Y // Function to calculate the sum// of numbers divisible by X or Yfunction sum(N , X , Y){ var S1, S2, S3; S1 = (parseInt(N / X)) * (2 * X + parseInt(N / X - 1) * X) / 2; S2 = (parseInt(N / Y)) * (2 * Y + parseInt(N / Y - 1) * Y) / 2; S3 = (parseInt(N / (X * Y))) * (2 * (X * Y) + parseInt(N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3;} // Driver codevar N = 14;var X = 3, Y = 5; document.write(sum(N, X, Y)); // This code is contributed by Princi Singh</script>
// C program to find sum of numbers from// 1 to N which are divisible by X or Y#include <stdio.h> // Function to calculate the sum// of numbers divisible by X or Yint sum(int N, int X, int Y){ int S1, S2, S3; S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2; S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2; S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3;} // Driver codeint main(){ int N = 14; int X = 3, Y = 5; printf("%d ",sum(N, X, Y)); return 0;}
45
Time Complexity : O(1)
ankthon
ukasp
jit_t
SURENDRA_GANGWAR
VishalBachchas
princi singh
kothavvsaakash
arithmetic progression
number-theory
Technical Scripter 2018
C++ Programs
Mathematical
Technical Scripter
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shallow Copy and Deep Copy in C++
Passing a function as a parameter in C++
cin in C++
C++ Program to check if a given String is Palindrome or not
Program to implement Singly Linked List in C++ using class
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": 26333,
"s": 26305,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 26483,
"s": 26333,
"text": "Given a number N. Given two numbers X and Y, the task is to find the sum of all those numbers from 1 to N that are divisible by X or by Y.Examples: "
},
{
"code": null,
"e": 26539,
"s": 26483,
"text": "Input : N = 20\nOutput : 98\n\nInput : N = 14 \nOutput : 45"
},
{
"code": null,
"e": 26953,
"s": 26539,
"text": "Approach: To solve the problem, follow the below steps:->Find the sum of numbers that are divisible by X upto N. Denote it by S1. ->Find the sum of numbers that are divisible by Y upto N. Denote it by S2. ->Find the sum of numbers that are divisible by both X and Y (X*Y) upto N. Denote it by S3. ->The final answer will be S1 + S2 – S3.In order to find the sum, we can use the general formula of A.P. which is: "
},
{
"code": null,
"e": 26982,
"s": 26953,
"text": "Sn = (n/2) * {2*a + (n-1)*d}"
},
{
"code": null,
"e": 27078,
"s": 26982,
"text": "For S1: The total numbers that will be divisible by X upto N will be N/X and the sum will be: "
},
{
"code": null,
"e": 27127,
"s": 27078,
"text": "Hence, \nS1 = ((N/X)/2) * (2 * X + (N/X - 1) * X)"
},
{
"code": null,
"e": 27223,
"s": 27127,
"text": "For S2: The total numbers that will be divisible by Y upto N will be N/Y and the sum will be: "
},
{
"code": null,
"e": 27272,
"s": 27223,
"text": "Hence, \nS2 = ((N/Y)/2) * (2 * Y + (N/Y - 1) * Y)"
},
{
"code": null,
"e": 27383,
"s": 27272,
"text": "For S3: The total numbers that will be divisible by both X and Y upto N will be N/(X*Y) and the sum will be: "
},
{
"code": null,
"e": 27444,
"s": 27383,
"text": "Hence, \nS2 = ((N/(X*Y))/2) * (2 * Y + (N/(X*Y) - 1) * (X*Y))"
},
{
"code": null,
"e": 27477,
"s": 27444,
"text": "Therefore, the result will be: "
},
{
"code": null,
"e": 27494,
"s": 27477,
"text": "S = S1 + S2 - S3"
},
{
"code": null,
"e": 27547,
"s": 27494,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27551,
"s": 27547,
"text": "C++"
},
{
"code": null,
"e": 27556,
"s": 27551,
"text": "Java"
},
{
"code": null,
"e": 27564,
"s": 27556,
"text": "Python3"
},
{
"code": null,
"e": 27567,
"s": 27564,
"text": "C#"
},
{
"code": null,
"e": 27571,
"s": 27567,
"text": "PHP"
},
{
"code": null,
"e": 27582,
"s": 27571,
"text": "Javascript"
},
{
"code": null,
"e": 27584,
"s": 27582,
"text": "C"
},
{
"code": "// C++ program to find sum of numbers from// 1 to N which are divisible by X or Y#include <bits/stdc++.h>using namespace std; // Function to calculate the sum// of numbers divisible by X or Yint sum(int N, int X, int Y){ int S1, S2, S3; S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2; S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2; S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3;} // Driver codeint main(){ int N = 14; int X = 3, Y = 5; cout << sum(N, X, Y); return 0;}",
"e": 28151,
"s": 27584,
"text": null
},
{
"code": "// Java program to find sum of numbers from// 1 to N which are divisible by X or Y public class GFG{ // Function to calculate the sum // of numbers divisible by X or Y static int sum(int N, int X, int Y) { int S1, S2, S3; S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2; S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2; S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3; } // Driver code public static void main(String []args) { int N = 14; int X = 3, Y = 5; System.out.println(sum(N, X, Y)); } // This code is contributed by Ryuga}",
"e": 28864,
"s": 28151,
"text": null
},
{
"code": "# Python 3 program to find sum of numbers from# 1 to N which are divisible by X or Yfrom math import ceil, floor # Function to calculate the sum# of numbers divisible by X or Ydef sum(N, X, Y): S1 = floor(floor(N / X) * floor(2 * X + floor(N / X - 1) * X) / 2) S2 = floor(floor(N / Y)) * floor(2 * Y + floor(N / Y - 1) * Y) / 2 S3 = floor(floor(N / (X * Y))) * floor (2 * (X * Y) + floor(N / (X * Y) - 1) * (X * Y))/ 2 return S1 + S2 - S3 # Driver codeif __name__ == '__main__': N = 14 X = 3 Y = 5 print(int(sum(N, X, Y))) # This code is contributed by# Surendra_Gangwar",
"e": 29503,
"s": 28864,
"text": null
},
{
"code": "// C# program to find sum of numbers from// 1 to N which are divisible by X or Y using System;public class GFG{ // Function to calculate the sum // of numbers divisible by X or Y static int sum(int N, int X, int Y) { int S1, S2, S3; S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2; S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2; S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3; } // Driver code public static void Main() { int N = 14; int X = 3, Y = 5; Console.Write(sum(N, X, Y)); } }",
"e": 30181,
"s": 29503,
"text": null
},
{
"code": "<?php// PHP program to find sum of numbers from// 1 to N which are divisible by X or Y// Function to calculate the sum// of numbers divisible by X or Yfunction sum($N, $X, $Y){ $S1; $S2; $S3; $S1 = floor(((int)$N / $X)) * (2 * $X + (int)((int)$N / $X - 1) * $X) / 2; $S2 = floor(((int)$N / $Y)) * (2 * $Y + (int)((int)$N / $Y - 1) * $Y) / 2; $S3 = floor(((int)$N / ($X * $Y))) * (2 * ($X * $Y) + ((int)$N / ($X * $Y) - 1) * (int)($X * $Y))/ 2; return ceil($S1 + ($S2 - $S3));} // Driver code $N = 14; $X = 3; $Y = 5; echo sum($N, $X, $Y); #This code is contributed by ajit.?>",
"e": 30807,
"s": 30181,
"text": null
},
{
"code": "<script>// javascript program to find sum of numbers from// 1 to N which are divisible by X or Y // Function to calculate the sum// of numbers divisible by X or Yfunction sum(N , X , Y){ var S1, S2, S3; S1 = (parseInt(N / X)) * (2 * X + parseInt(N / X - 1) * X) / 2; S2 = (parseInt(N / Y)) * (2 * Y + parseInt(N / Y - 1) * Y) / 2; S3 = (parseInt(N / (X * Y))) * (2 * (X * Y) + parseInt(N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3;} // Driver codevar N = 14;var X = 3, Y = 5; document.write(sum(N, X, Y)); // This code is contributed by Princi Singh</script>",
"e": 31416,
"s": 30807,
"text": null
},
{
"code": "// C program to find sum of numbers from// 1 to N which are divisible by X or Y#include <stdio.h> // Function to calculate the sum// of numbers divisible by X or Yint sum(int N, int X, int Y){ int S1, S2, S3; S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2; S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2; S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2; return S1 + S2 - S3;} // Driver codeint main(){ int N = 14; int X = 3, Y = 5; printf(\"%d \",sum(N, X, Y)); return 0;}",
"e": 31937,
"s": 31416,
"text": null
},
{
"code": null,
"e": 31940,
"s": 31937,
"text": "45"
},
{
"code": null,
"e": 31966,
"s": 31942,
"text": "Time Complexity : O(1) "
},
{
"code": null,
"e": 31974,
"s": 31966,
"text": "ankthon"
},
{
"code": null,
"e": 31980,
"s": 31974,
"text": "ukasp"
},
{
"code": null,
"e": 31986,
"s": 31980,
"text": "jit_t"
},
{
"code": null,
"e": 32003,
"s": 31986,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32018,
"s": 32003,
"text": "VishalBachchas"
},
{
"code": null,
"e": 32031,
"s": 32018,
"text": "princi singh"
},
{
"code": null,
"e": 32046,
"s": 32031,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 32069,
"s": 32046,
"text": "arithmetic progression"
},
{
"code": null,
"e": 32083,
"s": 32069,
"text": "number-theory"
},
{
"code": null,
"e": 32107,
"s": 32083,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 32120,
"s": 32107,
"text": "C++ Programs"
},
{
"code": null,
"e": 32133,
"s": 32120,
"text": "Mathematical"
},
{
"code": null,
"e": 32152,
"s": 32133,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32166,
"s": 32152,
"text": "number-theory"
},
{
"code": null,
"e": 32179,
"s": 32166,
"text": "Mathematical"
},
{
"code": null,
"e": 32277,
"s": 32179,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32311,
"s": 32277,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 32352,
"s": 32311,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 32363,
"s": 32352,
"text": "cin in C++"
},
{
"code": null,
"e": 32423,
"s": 32363,
"text": "C++ Program to check if a given String is Palindrome or not"
},
{
"code": null,
"e": 32482,
"s": 32423,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 32512,
"s": 32482,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32572,
"s": 32512,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32587,
"s": 32572,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32630,
"s": 32587,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to Download and Install Python Latest Version on Linux? - GeeksforGeeks
|
06 Oct, 2021
Python is a widely-used general-purpose, high-level programming language. This article will serve as a complete tutorial on How to download and install Python latest version on Linux Operating Systems.On every Linux system including following OS,
Ubuntu
Linux Mint
Debian
openSUSE
CentOS
Fedora
and my favourite one, Arch Linux.
You will find Python already installed. You can check it using the following commands from the terminal
$ python --version
To check latest version of python 2.x.x :
$ python2 --version
To check latest version of python 3.x.x :
$ python3 --version
Clearly it won’t be the latest version of python. There can be multiple methods to install python on a linux base system and it all depends on your linux system.For almost every Linux system, the following commands would work definitely.
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$ sudo apt-get install python3.7
To install latest version from source code of Python follow below steps
First and foremost step is to open a browser and openhttps://www.python.org/downloads/source/
Underneath the Stable Releases find Download Gzipped source tarball (latest stable release as of now is Python 3.7.4).You can do all the above steps in a single command$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgzInstall Python 3.7.4 Latest Version on LinuxFor installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev
Now we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands$ tar xvf Python-3.6.5.tgz
$ cd Python-3.6.5
$ ./configure --enable-optimizations --with-ensurepip=install
$ make -j 8
$ sudo make altinstallBingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using below command.python --versionHow to set Python 3 as the default version in Linux?One can easily install python using various techniques mentioned above in their Linux system. But how to set it as default? so that whenever you enter Python anywhere in the terminal it always executes python3. Here is the simple command from which you can set Python3 as default version.Open your terminal and enter,sudo alias python = python3Now any code executed will automatically get python3 as default version.My Personal Notes
arrow_drop_upSave
You can do all the above steps in a single command
$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz
For installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev
Now we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands
$ tar xvf Python-3.6.5.tgz
$ cd Python-3.6.5
$ ./configure --enable-optimizations --with-ensurepip=install
$ make -j 8
$ sudo make altinstall
Bingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using below command.
python --version
One can easily install python using various techniques mentioned above in their Linux system. But how to set it as default? so that whenever you enter Python anywhere in the terminal it always executes python3. Here is the simple command from which you can set Python3 as default version.Open your terminal and enter,
sudo alias python = python3
Now any code executed will automatically get python3 as default version.
how-to-install
python-utility
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
How to Install Pygame on Windows ?
How to Install and Run Apache Kafka on Windows?
|
[
{
"code": null,
"e": 25875,
"s": 25847,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26122,
"s": 25875,
"text": "Python is a widely-used general-purpose, high-level programming language. This article will serve as a complete tutorial on How to download and install Python latest version on Linux Operating Systems.On every Linux system including following OS,"
},
{
"code": null,
"e": 26129,
"s": 26122,
"text": "Ubuntu"
},
{
"code": null,
"e": 26140,
"s": 26129,
"text": "Linux Mint"
},
{
"code": null,
"e": 26147,
"s": 26140,
"text": "Debian"
},
{
"code": null,
"e": 26156,
"s": 26147,
"text": "openSUSE"
},
{
"code": null,
"e": 26163,
"s": 26156,
"text": "CentOS"
},
{
"code": null,
"e": 26170,
"s": 26163,
"text": "Fedora"
},
{
"code": null,
"e": 26204,
"s": 26170,
"text": "and my favourite one, Arch Linux."
},
{
"code": null,
"e": 26308,
"s": 26204,
"text": "You will find Python already installed. You can check it using the following commands from the terminal"
},
{
"code": null,
"e": 26327,
"s": 26308,
"text": "$ python --version"
},
{
"code": null,
"e": 26369,
"s": 26327,
"text": "To check latest version of python 2.x.x :"
},
{
"code": null,
"e": 26389,
"s": 26369,
"text": "$ python2 --version"
},
{
"code": null,
"e": 26431,
"s": 26389,
"text": "To check latest version of python 3.x.x :"
},
{
"code": null,
"e": 26451,
"s": 26431,
"text": "$ python3 --version"
},
{
"code": null,
"e": 26689,
"s": 26451,
"text": "Clearly it won’t be the latest version of python. There can be multiple methods to install python on a linux base system and it all depends on your linux system.For almost every Linux system, the following commands would work definitely."
},
{
"code": null,
"e": 26790,
"s": 26689,
"text": "$ sudo add-apt-repository ppa:deadsnakes/ppa\n$ sudo apt-get update\n$ sudo apt-get install python3.7\n"
},
{
"code": null,
"e": 26862,
"s": 26790,
"text": "To install latest version from source code of Python follow below steps"
},
{
"code": null,
"e": 26956,
"s": 26862,
"text": "First and foremost step is to open a browser and openhttps://www.python.org/downloads/source/"
},
{
"code": null,
"e": 28526,
"s": 26956,
"text": "Underneath the Stable Releases find Download Gzipped source tarball (latest stable release as of now is Python 3.7.4).You can do all the above steps in a single command$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgzInstall Python 3.7.4 Latest Version on LinuxFor installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files$ sudo apt-get update\n$ sudo apt-get upgrade\n$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev\nNow we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands$ tar xvf Python-3.6.5.tgz\n$ cd Python-3.6.5\n$ ./configure --enable-optimizations --with-ensurepip=install\n$ make -j 8\n$ sudo make altinstallBingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using below command.python --versionHow to set Python 3 as the default version in Linux?One can easily install python using various techniques mentioned above in their Linux system. But how to set it as default? so that whenever you enter Python anywhere in the terminal it always executes python3. Here is the simple command from which you can set Python3 as default version.Open your terminal and enter,sudo alias python = python3Now any code executed will automatically get python3 as default version.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28577,
"s": 28526,
"text": "You can do all the above steps in a single command"
},
{
"code": null,
"e": 28641,
"s": 28577,
"text": "$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz"
},
{
"code": null,
"e": 28758,
"s": 28641,
"text": "For installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files"
},
{
"code": null,
"e": 28980,
"s": 28758,
"text": "$ sudo apt-get update\n$ sudo apt-get upgrade\n$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev\n"
},
{
"code": null,
"e": 29156,
"s": 28980,
"text": "Now we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands"
},
{
"code": null,
"e": 29298,
"s": 29156,
"text": "$ tar xvf Python-3.6.5.tgz\n$ cd Python-3.6.5\n$ ./configure --enable-optimizations --with-ensurepip=install\n$ make -j 8\n$ sudo make altinstall"
},
{
"code": null,
"e": 29421,
"s": 29298,
"text": "Bingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using below command."
},
{
"code": null,
"e": 29438,
"s": 29421,
"text": "python --version"
},
{
"code": null,
"e": 29756,
"s": 29438,
"text": "One can easily install python using various techniques mentioned above in their Linux system. But how to set it as default? so that whenever you enter Python anywhere in the terminal it always executes python3. Here is the simple command from which you can set Python3 as default version.Open your terminal and enter,"
},
{
"code": null,
"e": 29784,
"s": 29756,
"text": "sudo alias python = python3"
},
{
"code": null,
"e": 29857,
"s": 29784,
"text": "Now any code executed will automatically get python3 as default version."
},
{
"code": null,
"e": 29872,
"s": 29857,
"text": "how-to-install"
},
{
"code": null,
"e": 29887,
"s": 29872,
"text": "python-utility"
},
{
"code": null,
"e": 29894,
"s": 29887,
"text": "How To"
},
{
"code": null,
"e": 29913,
"s": 29894,
"text": "Installation Guide"
},
{
"code": null,
"e": 29920,
"s": 29913,
"text": "Python"
},
{
"code": null,
"e": 30018,
"s": 29920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30045,
"s": 30018,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 30093,
"s": 30045,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 30107,
"s": 30093,
"text": "Java Tutorial"
},
{
"code": null,
"e": 30141,
"s": 30107,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 30177,
"s": 30141,
"text": "How to Install Anaconda on Windows?"
},
{
"code": null,
"e": 30210,
"s": 30177,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30244,
"s": 30210,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 30280,
"s": 30244,
"text": "How to Install Anaconda on Windows?"
},
{
"code": null,
"e": 30315,
"s": 30280,
"text": "How to Install Pygame on Windows ?"
}
] |
Node.js crypto.publicEncrypt() Method - GeeksforGeeks
|
11 Oct, 2021
The crypto.publicEncrypt() method is an inbuilt application programming interface of the crypto module which is used to encrypt the stated content of the buffer with the parameter ‘key’.
Syntax:
crypto.publicEncrypt( key, buffer )
Parameters: This method accept two parameters as mentioned above and described below:
key: This parameter holds Object, string, Buffer, or KeyObject type of data and contains five parameters which are as follows:key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.oaepLabel: It is the label which is used for ‘OAEP’ padding. And if it’s not specified, then no label is used. It is of type Buffer, TypedArray or DataView.passphrase: It is an optional passphrase for the private key which is either string or buffer.padding: It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING. It is of type crypto.constants.
key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.oaepLabel: It is the label which is used for ‘OAEP’ padding. And if it’s not specified, then no label is used. It is of type Buffer, TypedArray or DataView.passphrase: It is an optional passphrase for the private key which is either string or buffer.padding: It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING. It is of type crypto.constants.
key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.
oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.
oaepLabel: It is the label which is used for ‘OAEP’ padding. And if it’s not specified, then no label is used. It is of type Buffer, TypedArray or DataView.
passphrase: It is an optional passphrase for the private key which is either string or buffer.
padding: It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING. It is of type crypto.constants.
buffer: It is of type Buffer, TypedArray, or DataView.
Return Value: It returns a new Buffer with the encrypted content.
Below example illustrate the use of crypto.publicEncrypt() method in Node.js:
Example 1:
// Node.js program to demonstrate the // crypto.publicEncrypt() method // Including crypto and fs moduleconst crypto = require('crypto');const fs = require("fs"); // Using a function generateKeyFilesfunction generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating public key file fs.writeFileSync("public_key", keyPair.publicKey);} // Generate keysgenerateKeyFiles(); // Creating a function to encrypt stringfunction encryptString (plaintext, publicKeyFile) { const publicKey = fs.readFileSync(publicKeyFile, "utf8"); // publicEncrypt() method with its parameters const encrypted = crypto.publicEncrypt( publicKey, Buffer.from(plaintext)); return encrypted.toString("base64");} // Defining a text to be encryptedconst plainText = "GfG"; // Defining encrypted textconst encrypted = encryptString(plainText, "./public_key"); // Prints plain textconsole.log("Plaintext:", plainText); // Prints encrypted textconsole.log("Encrypted: ", encrypted);
Output:
Plaintext: GfG
Encrypted: l0touwFaNv1DIgPE365VQD0G4rg+IbRD5G6IBQ1arLgWtFOStKO7duYJ6/JzlOJl3eBG7obqzAEJ0V2WrxtYRTg=
Example 2:
// Node.js program to demonstrate the // crypto.publicEncrypt() method // Including crypto and fs moduleconst crypto = require('crypto');const fs = require("fs"); // Using a function generateKeyFilesfunction generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating public key file fs.writeFileSync("public_key", keyPair.publicKey);} // Generate keysgenerateKeyFiles(); // Creating a function to encrypt stringfunction encryptString (plaintext, publicKeyFile) { const publicKey = fs.readFileSync(publicKeyFile, "utf8"); // publicEncrypt() method with its parameters const encrypted = crypto.publicEncrypt( publicKey, Buffer.from(plaintext)); return encrypted;} // Defining a text to be encryptedconst plainText = "Hello!"; // Defining encrypted textconst encrypted = encryptString(plainText, "./public_key"); // Prints plain textconsole.log("Plaintext:", plainText); // Prints bufferconsole.log("Buffer: ", encrypted);
Output:
Plaintext: Hello!
Buffer: <Buffer 1b 2a c7 4d 10 44 45 8e 9d e6
53 9d 8a 5e 39 0f ea e2 96 00 d7 d3 b3 eb 54 7e
74 7d a4 62 b8 eb 68 85 cb 8e 85 a5 f7 71 2f b7
93 d6 14 1c 38 cd 45 85 ... >
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_publicencrypt_key_buffer
Node.js-crypto-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.render() Function
Mongoose | findByIdAndUpdate() Function
Node.js fs.readdirSync() Method
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": 26215,
"s": 26187,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 26402,
"s": 26215,
"text": "The crypto.publicEncrypt() method is an inbuilt application programming interface of the crypto module which is used to encrypt the stated content of the buffer with the parameter ‘key’."
},
{
"code": null,
"e": 26410,
"s": 26402,
"text": "Syntax:"
},
{
"code": null,
"e": 26446,
"s": 26410,
"text": "crypto.publicEncrypt( key, buffer )"
},
{
"code": null,
"e": 26532,
"s": 26446,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 27358,
"s": 26532,
"text": "key: This parameter holds Object, string, Buffer, or KeyObject type of data and contains five parameters which are as follows:key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.oaepLabel: It is the label which is used for ‘OAEP’ padding. And if it’s not specified, then no label is used. It is of type Buffer, TypedArray or DataView.passphrase: It is an optional passphrase for the private key which is either string or buffer.padding: It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING. It is of type crypto.constants."
},
{
"code": null,
"e": 28058,
"s": 27358,
"text": "key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.oaepLabel: It is the label which is used for ‘OAEP’ padding. And if it’s not specified, then no label is used. It is of type Buffer, TypedArray or DataView.passphrase: It is an optional passphrase for the private key which is either string or buffer.padding: It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING. It is of type crypto.constants."
},
{
"code": null,
"e": 28157,
"s": 28058,
"text": "key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject."
},
{
"code": null,
"e": 28273,
"s": 28157,
"text": "oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’."
},
{
"code": null,
"e": 28430,
"s": 28273,
"text": "oaepLabel: It is the label which is used for ‘OAEP’ padding. And if it’s not specified, then no label is used. It is of type Buffer, TypedArray or DataView."
},
{
"code": null,
"e": 28525,
"s": 28430,
"text": "passphrase: It is an optional passphrase for the private key which is either string or buffer."
},
{
"code": null,
"e": 28762,
"s": 28525,
"text": "padding: It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING. It is of type crypto.constants."
},
{
"code": null,
"e": 28817,
"s": 28762,
"text": "buffer: It is of type Buffer, TypedArray, or DataView."
},
{
"code": null,
"e": 28883,
"s": 28817,
"text": "Return Value: It returns a new Buffer with the encrypted content."
},
{
"code": null,
"e": 28961,
"s": 28883,
"text": "Below example illustrate the use of crypto.publicEncrypt() method in Node.js:"
},
{
"code": null,
"e": 28972,
"s": 28961,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // crypto.publicEncrypt() method // Including crypto and fs moduleconst crypto = require('crypto');const fs = require(\"fs\"); // Using a function generateKeyFilesfunction generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating public key file fs.writeFileSync(\"public_key\", keyPair.publicKey);} // Generate keysgenerateKeyFiles(); // Creating a function to encrypt stringfunction encryptString (plaintext, publicKeyFile) { const publicKey = fs.readFileSync(publicKeyFile, \"utf8\"); // publicEncrypt() method with its parameters const encrypted = crypto.publicEncrypt( publicKey, Buffer.from(plaintext)); return encrypted.toString(\"base64\");} // Defining a text to be encryptedconst plainText = \"GfG\"; // Defining encrypted textconst encrypted = encryptString(plainText, \"./public_key\"); // Prints plain textconsole.log(\"Plaintext:\", plainText); // Prints encrypted textconsole.log(\"Encrypted: \", encrypted);",
"e": 30250,
"s": 28972,
"text": null
},
{
"code": null,
"e": 30258,
"s": 30250,
"text": "Output:"
},
{
"code": null,
"e": 30375,
"s": 30258,
"text": "Plaintext: GfG\nEncrypted: l0touwFaNv1DIgPE365VQD0G4rg+IbRD5G6IBQ1arLgWtFOStKO7duYJ6/JzlOJl3eBG7obqzAEJ0V2WrxtYRTg=\n"
},
{
"code": null,
"e": 30386,
"s": 30375,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // crypto.publicEncrypt() method // Including crypto and fs moduleconst crypto = require('crypto');const fs = require(\"fs\"); // Using a function generateKeyFilesfunction generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating public key file fs.writeFileSync(\"public_key\", keyPair.publicKey);} // Generate keysgenerateKeyFiles(); // Creating a function to encrypt stringfunction encryptString (plaintext, publicKeyFile) { const publicKey = fs.readFileSync(publicKeyFile, \"utf8\"); // publicEncrypt() method with its parameters const encrypted = crypto.publicEncrypt( publicKey, Buffer.from(plaintext)); return encrypted;} // Defining a text to be encryptedconst plainText = \"Hello!\"; // Defining encrypted textconst encrypted = encryptString(plainText, \"./public_key\"); // Prints plain textconsole.log(\"Plaintext:\", plainText); // Prints bufferconsole.log(\"Buffer: \", encrypted);",
"e": 31641,
"s": 30386,
"text": null
},
{
"code": null,
"e": 31649,
"s": 31641,
"text": "Output:"
},
{
"code": null,
"e": 31840,
"s": 31649,
"text": "Plaintext: Hello!\nBuffer: <Buffer 1b 2a c7 4d 10 44 45 8e 9d e6\n53 9d 8a 5e 39 0f ea e2 96 00 d7 d3 b3 eb 54 7e\n74 7d a4 62 b8 eb 68 85 cb 8e 85 a5 f7 71 2f b7\n93 d6 14 1c 38 cd 45 85 ... >\n"
},
{
"code": null,
"e": 31925,
"s": 31840,
"text": "Reference: https://nodejs.org/api/crypto.html#crypto_crypto_publicencrypt_key_buffer"
},
{
"code": null,
"e": 31947,
"s": 31925,
"text": "Node.js-crypto-module"
},
{
"code": null,
"e": 31955,
"s": 31947,
"text": "Node.js"
},
{
"code": null,
"e": 31972,
"s": 31955,
"text": "Web Technologies"
},
{
"code": null,
"e": 32070,
"s": 31972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32124,
"s": 32070,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 32161,
"s": 32124,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 32194,
"s": 32161,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 32234,
"s": 32194,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 32266,
"s": 32234,
"text": "Node.js fs.readdirSync() Method"
},
{
"code": null,
"e": 32306,
"s": 32266,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32351,
"s": 32306,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32394,
"s": 32351,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32444,
"s": 32394,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
UGC NET CS 2018 Dec – II - GeeksforGeeks
|
03 Nov, 2021
R ≥ P(N − 1) + 1
12 ≥ P(4 − 1) + 1
11 ≥ 3P
11/3 ≥ P
P ≤ 3.66
Writers are given exclusive access to shared objectsReaders are given exclusive access to shared objectsBoth readers and writers are given exclusive access to shared objects.
Writers are given exclusive access to shared objects
Readers are given exclusive access to shared objects
Both readers and writers are given exclusive access to shared objects.
SRS is said to be correct if it covers all the requirements that are actually expected from the system.
Requirements in SRS are said to be consistent if there are no conflicts between any set of requirements. Examples of conflict include differences in terminologies used at separate places, logical conflicts like time period of report generation, etc.
An SRS is said to be unambiguous if all the requirements stated have only 1 interpretation.
An SRS is verifiable if there exists a specific technique to quantifiably measure the extent to which every requirement is met by the system.
(⌐ 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 Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Spring - REST Controller
EPAM Interview Experience | On-Campus 2022
How to Read Text Files with Pandas?
Construct a DFA that Start With aa or bb
Python Data Structures and Algorithms
Data Science With Python Tutorial
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 28873,
"s": 28855,
"text": "R ≥ P(N − 1) + 1 "
},
{
"code": null,
"e": 28918,
"s": 28873,
"text": "12 ≥ P(4 − 1) + 1\n11 ≥ 3P\n11/3 ≥ P\nP ≤ 3.66 "
},
{
"code": null,
"e": 29093,
"s": 28918,
"text": "Writers are given exclusive access to shared objectsReaders are given exclusive access to shared objectsBoth readers and writers are given exclusive access to shared objects."
},
{
"code": null,
"e": 29146,
"s": 29093,
"text": "Writers are given exclusive access to shared objects"
},
{
"code": null,
"e": 29199,
"s": 29146,
"text": "Readers are given exclusive access to shared objects"
},
{
"code": null,
"e": 29270,
"s": 29199,
"text": "Both readers and writers are given exclusive access to shared objects."
},
{
"code": null,
"e": 29374,
"s": 29270,
"text": "SRS is said to be correct if it covers all the requirements that are actually expected from the system."
},
{
"code": null,
"e": 29624,
"s": 29374,
"text": "Requirements in SRS are said to be consistent if there are no conflicts between any set of requirements. Examples of conflict include differences in terminologies used at separate places, logical conflicts like time period of report generation, etc."
},
{
"code": null,
"e": 29716,
"s": 29624,
"text": "An SRS is said to be unambiguous if all the requirements stated have only 1 interpretation."
},
{
"code": null,
"e": 29858,
"s": 29716,
"text": "An SRS is verifiable if there exists a specific technique to quantifiably measure the extent to which every requirement is met by the system."
},
{
"code": null,
"e": 29885,
"s": 29858,
"text": "(⌐ A ∨ ⌐B ∨ ⌐C ∨ ⌐ D) "
},
{
"code": null,
"e": 29983,
"s": 29885,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30036,
"s": 29983,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 30098,
"s": 30036,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 30139,
"s": 30098,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30182,
"s": 30139,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 30207,
"s": 30182,
"text": "Spring - REST Controller"
},
{
"code": null,
"e": 30250,
"s": 30207,
"text": "EPAM Interview Experience | On-Campus 2022"
},
{
"code": null,
"e": 30286,
"s": 30250,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 30327,
"s": 30286,
"text": "Construct a DFA that Start With aa or bb"
},
{
"code": null,
"e": 30365,
"s": 30327,
"text": "Python Data Structures and Algorithms"
}
] |
What are variadic functions in Java?
|
Methods which uses variable arguments (varargs, arguments with three dots) are known as variadic functions.
Live Demo
public class Sample {
void demoMethod(String... args) {
for (String arg: args) {
System.out.println(arg);
}
}
public static void main(String args[] ){
new Sample().demoMethod("ram", "rahim", "robert");
new Sample().demoMethod("krishna", "kasyap");
}
}
ram
rahim
robert
krishna
kasyap
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "Methods which uses variable arguments (varargs, arguments with three dots) are known as variadic functions."
},
{
"code": null,
"e": 1180,
"s": 1170,
"text": "Live Demo"
},
{
"code": null,
"e": 1480,
"s": 1180,
"text": "public class Sample {\n void demoMethod(String... args) {\n for (String arg: args) {\n System.out.println(arg);\n }\n }\n\n public static void main(String args[] ){\n new Sample().demoMethod(\"ram\", \"rahim\", \"robert\");\n new Sample().demoMethod(\"krishna\", \"kasyap\");\n }\n}"
},
{
"code": null,
"e": 1512,
"s": 1480,
"text": "ram\nrahim\nrobert\nkrishna\nkasyap"
}
] |
Applied Bayesian Inference with PyMC3 and Bambi Part 3 | by Ani Madurkar | Towards Data Science
|
This is the final part of my Applied Bayesian Inference series. In part 1, I introduced the conditional world and probabilistic programming:
towardsdatascience.com
In part 2, I showed how you can scale your models up to “real” data by modeling Nike and Adidas shoes. This piece showed how you can run more effective A/B tests and group comparisons:
towardsdatascience.com
In this part, part 3, I will show why Bayesian modeling is so incredible by gently introducing Linear Regression in PyMC3 and then taking it further into Hierarchical Models, Generalized Linear Models, and Out-of-Sample Prediction.
This story will take a look at Spotify data, namely the Top 200 songs from 2020–2021. You can find the dataset here: https://www.kaggle.com/sashankpillai/spotify-top-200-charts-20202021. We’ll attempt to model the posterior of Streams for each song based on features related of each song (Danceability, Artist Followers, etc.)
Dtypes are a great place to start:
This will definitely need some cleaning up. Furthermore, because they’re objects, they’re likely to have weird text to clean up to make numeric. Between that, the biggest change I saw needed was the Genre column. Each song seems to fit ≥1 genre which is represented as a list. For our use case, we’ll want to One Hot Encode these column. This can easily be done with sklearn’s MultiLabelBinarizer.
That should be much better! Now we want to separate out the columns by type to 1. fix the dtype and 2. filtering down for a place to start. From there we can plot the Streams distribution to see what we’re targeting.
With Regressions, it’s common practice to center or standardize your values and it’s no different here. In fact, standardizing your values can be especially significant with MCMC models as the sampler will have a hard time converging otherwise. Standardizing can have another advantage for us which is being able to use weak informative priors since the Intercept will always be zero and the slope around -1 and 1. It also allows us to talk in terms of Z-scores, identifying how many standard deviations values are from the mean.
0
We’ll only work with these numeric fields for now; a later implementation of this can easily scale up to include the categorical columns we OneHotEncoded earlier (genre).
This is a common distribution shape we see in plenty of scenarios. It’s the consequence of having a lot of people at “lower” values and exponentially less as you go farther out in the tail to the right. It’s interesting we find it so strong even for the Top 200 songs, but this will be an important piece to remember as we go to model this posterior.
To start, we can take the plot the standardized log of Streams:
Still not the best, but much better. We clearly have some outliers that have seen some massive virality in the last year.
The best way to learn is to do, and when things are complex it’s best to start as simple as possible and then slowly scale up. The simplest example here is Linear Regression, so let’s see we wanted to model Streams as a function of Artist Followers. Maybe we have some premonition that the artist’s followers has some impact on Streams.
It’s good practice to first get an understanding of relationships; how does Artist’s Followers correlate to Streams for the Top 200?
Barely a correlation which seems to make sense as these are already highly popular songs — there could even be a reverse correlation occurring here (as a new song comes up to Top 200, that artist’s followers significantly increases). These kinds of insights are incredibly important to understand not only before modeling, but also when it comes time to draw conclusions from results. Everyone should understand by now that correlation != causation, but which direction may the correlation flow? And why? These can give amazing insight into how to fix problems in your model or what kind of data you may want to curate to improve your model.
What’s interesting here is that we are creating a prior for beta (the weight of x, the Artist’s Followers) and the bias and then creating a linear function (alpha + beta*x) to model the likelihood. Remember, we’re attempting to model the posterior of the likelihood as a function of priors, but when we do it this way we’re able quantify a distribution of values based on the uncertainty in the observed values. We want to wrap mu in a deterministic function because we don’t want it to be different each time; it should always follow the consequence of alpha + beta*x, but alpha and beta have stochastic priors that allow the model to scan a range of options for them.
Furthermore, we can create some deterministic metrics to measure our output pretty simply as well. Since we’re dealing with Regression, we can also calculate the r2 value in the model build itself. This creates a really easy way to identify how well the fitted line fits the data.
Now we can sample the data. NUTS (No-U-Turn Sampler) is a fantastic choice for most use cases. Although it can be slower per step than Metropolis, it is able to traverse diagonal spaces with less difficulties. Furthermore, it usually needs far fewer steps to get a reasonable approximation to the posterior.
We don’t see an noticeable divergences in the traces and the standardization/centering has significantly helped our model find appropriate distributions for each song. Let’s see our r2 and plot the findings.
So, our model performs great but we get quite a low correlation which should be obvious when seeing this scatterplot. There really isn’t much correlation to begin with , and this seems to pick up on it. There are a number of things we can do to improve on this model though. First, let’s use a StudentT distribution for our likelihood and see if we can make it more robust to outliers while also predicting out-of-sample.
We get a dramatic improvement in the line fitting to our data — ~.16! Technically, since we standardized the data, the slope and the Pearson correlation coefficient have the same value but this is a really interesting way to bake it into your modeling. Still not the best predictor of Streams, but we can see how the line is less likely to be picked up by potential outliers in our dataset. Although it would do us little good, we can also easily update our data and predict the posterior using this model on the test dataset.
Mean Squared Error: 0.6710557105827462
It is amazing how easy it can be to not only find a test point (mean value of each posterior distribution) but also a distribution of values to estimate the error! We can now take these skills to take this simple model and keep building on top of it.
Enter BAyesian Model-Building Interface — Bambi.
As before, if we’re going to incorporate more variables we should first visualize relationships and ensure minimum correlation between features and between features/predicted variable. We can do this effectively with my favorite visualization, the scatterplot matrix.
It seems ‘Energy’ and ‘Loudness’ are more correlated than we’d prefer. This can cause a lot of issues when attempting to model a relationship between these variables so we can remove one.
Note the last row is the Log_Streams value, so we don’t need to evaluate its correlations to Streams as we’re not modeling that (yet).
Using Bambi, we can easily write up our formula and cook up the model like so:
I’ll skip the traceplots and forestplots to analyze the data here, but make sure to use those to ensure your model is converging on each feature properly! Traceplots are fantastic ways to immediately visualize the outputs of a MCMC model.
Mean Squared Error: 0.5720862510645325
Note, we’re sampling 2 chains here on the posterior predictive to model the test predictions so this is why we’re taking two column-wise means — one for the mean of the two chains and two for the mean of the posterior distribution of each prediction (the test value).
The MSE is significantly better as we add more features of a particular song (Danceability, Valence, Energy, and more). From assessing the means in the fitted model’s summary, it is interesting that Followers appears to have the strongest effect to increase Log_Streams out of the other values. Features such as Danceability and Speechiness appear to have a negative effect on Log_Streams, but it is important to take these features with a grain of salt as I’m not entirely sure how Spotify records this information (let alone how someone may have manipulated it to get it in Kaggle).
An important question that you may have realized at this point is what about the variation of songs by artists? We are currently modeling each song individually (unpooled), but we also could model each artist’s songs (pooled). The issue with each of these is that you have to give something up for it. With unpooled, you lose the ability to see the nuance across artists; with pooled, you lose the granularity of each song’s distribution. So what can we do? Hierarchical partial pooling to the rescue!
This looks much more complicated, but it’s actually beautifully simple. The whole concept of Bayesian inference that we have learned so far is that you are able to bake in prior knowledge and model a posterior distribution which is suited to be updated as new knowledge is formed. So far we have only modeled the immediate priors (the mu and sigma priors on a Normal likelihood, for example), but what if we have a hierarchical nature to our data? Wouldn’t it be great if we could model the distribution of song metadata per artist? Short answer is that we can, and easily. This is a hierarchical model and it involves you adding hyperpriors to your priors; in this case, we’re adding grouping the song metadata features by Artist and adding hyperpriors to our priors along with our likelihood.
In the code block, we can signify we want a hierarchical model by adding the “(1|...)” to each feature and then simply adding Priors to values appropriately. The syntax can be broken down as such:
Common predictors are your main effects. For example, Danceability.
Group predictors can be identified by three different ways: 1. (Danceability|Artist) indicates we want to allow each artist to have his/her own slope and intercept for Danceability, 2. (1|Artist) indicates we wanted different intercepts for Artist but not slopes, and 3. (0+Danceability|Artist) indicates we only wanted slopes specific to each artist without including an artist specific intercept.
Obviously the less knowledge we may have, the wider priors we want to implement just the same as before. In any case, how did the model perform?
Unfortunately, Bambi does not have current functionality (version 0.6.3) to do out-of-sample predictions when you’re involving categorical grouping hierarchically yet, but our model does seem to learn the distribution just as well. The benefit of doing partial pooling is that we can not only see the posterior distribution in this regard, but also measure the impact each artist’s song attribute distribution had. Here’s an example of just a few for Popularity:
Although hierarchical modeling is extremely fascinating, it’s quite visible that we are not able to fully model the observed distribution as effectively. The reality in that is due to it’s non-gaussian shape. We’re attempting to model it with linear models that assume a level of normality which in reality, we just don’t see. And furthermore, our Streams don’t go below 0 ever so our Log_Streams will never go below 0 (the lowest Stream count possible is 1 and discrete). How can we model this?
Generalized Linear Models are incredibly easy to implement in Bambi, and they are the solution to our issue. Our Streams are not normally distributed by nature, and so we should think about how to effectively model their real nature. A good start is the guide I outlined in Part 1 — how do we believe this data is collected? Streams are a counting measure; they reflect the number of discrete times a song has been played on Spotify. Luckily for us, there is a popular GLM type that models exactly this: Poisson. Here’s how we’d implement it with Bambi and the results (Note how we’re modeling Streams directly now).
Important disclaimer: at time of writing I used the Streams field that was already standardized which isn’t correct to model as a Poisson distribution since this makes discrete count data into continuous data that lies below 0 (shoutout to Susia for catching this). Until I’m able to fix this, please make sure to know that the intended field to be modeled is the raw count of Streams.
Mean Squared Error: 0.2989611604295006
What a dramatic improvement! But why did the MSE get so much better? Actually, I’d wager that we could get it even lower but how? The answer to this question is the essence of Bayesian Machine Learning.
The reason the model performed dramatically better is because we carefully thought about the data and what it represents. We thought about the nuances of it and how it is collected. Throwing endless modeling techniques at a problem could improve your metrics, but the model doesn’t truly sing until you do the hard work of strategic design. Bayesian ML gives us the ability to do this really flexibly and also gets stronger with robust and precise priors, which is another thing we did/improve on. Allowing your priors a general space to learn in can create a really informative model that is able to converge quickly and learn effectively.
To wrap this up with a nice bow, let’s do model comparison to see how each performed a bit more clearly.
By default AriZ uses leave one out cross-validation. Another option is the widely applicable information criterion (WAIC). Since the results are in the log scale, the better out-of-sample predictive fit is given by the model with the highest value, which is the Generalized Linear Model as we saw earlier.
This wraps up my 3 part series on Applied Bayesian Inference and we have been able to do quite a lot in that time. Honestly, I started this series knowing very little about the field and knew I wanted to learn it deeply so I figured the best way would be to build with all the knowledge I’m finding as I read around. And what better addition to then document my journey for others to learn to?
I hope this series not only helped you learn this craft and dive into it yourself, but also opened your eyes to the beautiful world of Machine Learning. Learning Bayesian methods for ML gives you a greater appreciation for how a strong foundation in statistics can take you so far here. From modeling the uncertainty in your world, making predictions in spite of it, and updating your knowledge in light of new evidence.
The end of this series marks the official start for me with designing my brand in this space. Applied content that is meant to help you not only get started, but also understand concepts just enough to enrich your corner of the world. Follow along for more content related to the art & science of Machine Learning.
References
[1] Osvaldo Martin, Bayesian Analysis with Python
[2] PyMC3, GLM in PyMC3: Out-Of-Sample Predictions
[3] PyMC3, (Generalized) Linear and Hierarchical Linear Models in PyMC3
[4] PyMC3, GLM: Poisson Regression
[5] PyMC3, Hierarchical Partial Pooling
[6] PyMC3, A Primer on Bayesian Methods for Multilevel Modeling
[7] Bambi, Wald and Gamma Regression (Australian insurance claims 2004–2005)
[8] Bambi, Multi-level Regression
[9] Bambi, Logistic Regression and Model Comparison with Bambi and ArviZ
[9] Bambi, Hierarchical Logistic regression with Binomial family
|
[
{
"code": null,
"e": 313,
"s": 172,
"text": "This is the final part of my Applied Bayesian Inference series. In part 1, I introduced the conditional world and probabilistic programming:"
},
{
"code": null,
"e": 336,
"s": 313,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 521,
"s": 336,
"text": "In part 2, I showed how you can scale your models up to “real” data by modeling Nike and Adidas shoes. This piece showed how you can run more effective A/B tests and group comparisons:"
},
{
"code": null,
"e": 544,
"s": 521,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 776,
"s": 544,
"text": "In this part, part 3, I will show why Bayesian modeling is so incredible by gently introducing Linear Regression in PyMC3 and then taking it further into Hierarchical Models, Generalized Linear Models, and Out-of-Sample Prediction."
},
{
"code": null,
"e": 1103,
"s": 776,
"text": "This story will take a look at Spotify data, namely the Top 200 songs from 2020–2021. You can find the dataset here: https://www.kaggle.com/sashankpillai/spotify-top-200-charts-20202021. We’ll attempt to model the posterior of Streams for each song based on features related of each song (Danceability, Artist Followers, etc.)"
},
{
"code": null,
"e": 1138,
"s": 1103,
"text": "Dtypes are a great place to start:"
},
{
"code": null,
"e": 1536,
"s": 1138,
"text": "This will definitely need some cleaning up. Furthermore, because they’re objects, they’re likely to have weird text to clean up to make numeric. Between that, the biggest change I saw needed was the Genre column. Each song seems to fit ≥1 genre which is represented as a list. For our use case, we’ll want to One Hot Encode these column. This can easily be done with sklearn’s MultiLabelBinarizer."
},
{
"code": null,
"e": 1753,
"s": 1536,
"text": "That should be much better! Now we want to separate out the columns by type to 1. fix the dtype and 2. filtering down for a place to start. From there we can plot the Streams distribution to see what we’re targeting."
},
{
"code": null,
"e": 2283,
"s": 1753,
"text": "With Regressions, it’s common practice to center or standardize your values and it’s no different here. In fact, standardizing your values can be especially significant with MCMC models as the sampler will have a hard time converging otherwise. Standardizing can have another advantage for us which is being able to use weak informative priors since the Intercept will always be zero and the slope around -1 and 1. It also allows us to talk in terms of Z-scores, identifying how many standard deviations values are from the mean."
},
{
"code": null,
"e": 2285,
"s": 2283,
"text": "0"
},
{
"code": null,
"e": 2456,
"s": 2285,
"text": "We’ll only work with these numeric fields for now; a later implementation of this can easily scale up to include the categorical columns we OneHotEncoded earlier (genre)."
},
{
"code": null,
"e": 2807,
"s": 2456,
"text": "This is a common distribution shape we see in plenty of scenarios. It’s the consequence of having a lot of people at “lower” values and exponentially less as you go farther out in the tail to the right. It’s interesting we find it so strong even for the Top 200 songs, but this will be an important piece to remember as we go to model this posterior."
},
{
"code": null,
"e": 2871,
"s": 2807,
"text": "To start, we can take the plot the standardized log of Streams:"
},
{
"code": null,
"e": 2993,
"s": 2871,
"text": "Still not the best, but much better. We clearly have some outliers that have seen some massive virality in the last year."
},
{
"code": null,
"e": 3330,
"s": 2993,
"text": "The best way to learn is to do, and when things are complex it’s best to start as simple as possible and then slowly scale up. The simplest example here is Linear Regression, so let’s see we wanted to model Streams as a function of Artist Followers. Maybe we have some premonition that the artist’s followers has some impact on Streams."
},
{
"code": null,
"e": 3463,
"s": 3330,
"text": "It’s good practice to first get an understanding of relationships; how does Artist’s Followers correlate to Streams for the Top 200?"
},
{
"code": null,
"e": 4105,
"s": 3463,
"text": "Barely a correlation which seems to make sense as these are already highly popular songs — there could even be a reverse correlation occurring here (as a new song comes up to Top 200, that artist’s followers significantly increases). These kinds of insights are incredibly important to understand not only before modeling, but also when it comes time to draw conclusions from results. Everyone should understand by now that correlation != causation, but which direction may the correlation flow? And why? These can give amazing insight into how to fix problems in your model or what kind of data you may want to curate to improve your model."
},
{
"code": null,
"e": 4775,
"s": 4105,
"text": "What’s interesting here is that we are creating a prior for beta (the weight of x, the Artist’s Followers) and the bias and then creating a linear function (alpha + beta*x) to model the likelihood. Remember, we’re attempting to model the posterior of the likelihood as a function of priors, but when we do it this way we’re able quantify a distribution of values based on the uncertainty in the observed values. We want to wrap mu in a deterministic function because we don’t want it to be different each time; it should always follow the consequence of alpha + beta*x, but alpha and beta have stochastic priors that allow the model to scan a range of options for them."
},
{
"code": null,
"e": 5056,
"s": 4775,
"text": "Furthermore, we can create some deterministic metrics to measure our output pretty simply as well. Since we’re dealing with Regression, we can also calculate the r2 value in the model build itself. This creates a really easy way to identify how well the fitted line fits the data."
},
{
"code": null,
"e": 5364,
"s": 5056,
"text": "Now we can sample the data. NUTS (No-U-Turn Sampler) is a fantastic choice for most use cases. Although it can be slower per step than Metropolis, it is able to traverse diagonal spaces with less difficulties. Furthermore, it usually needs far fewer steps to get a reasonable approximation to the posterior."
},
{
"code": null,
"e": 5572,
"s": 5364,
"text": "We don’t see an noticeable divergences in the traces and the standardization/centering has significantly helped our model find appropriate distributions for each song. Let’s see our r2 and plot the findings."
},
{
"code": null,
"e": 5994,
"s": 5572,
"text": "So, our model performs great but we get quite a low correlation which should be obvious when seeing this scatterplot. There really isn’t much correlation to begin with , and this seems to pick up on it. There are a number of things we can do to improve on this model though. First, let’s use a StudentT distribution for our likelihood and see if we can make it more robust to outliers while also predicting out-of-sample."
},
{
"code": null,
"e": 6521,
"s": 5994,
"text": "We get a dramatic improvement in the line fitting to our data — ~.16! Technically, since we standardized the data, the slope and the Pearson correlation coefficient have the same value but this is a really interesting way to bake it into your modeling. Still not the best predictor of Streams, but we can see how the line is less likely to be picked up by potential outliers in our dataset. Although it would do us little good, we can also easily update our data and predict the posterior using this model on the test dataset."
},
{
"code": null,
"e": 6560,
"s": 6521,
"text": "Mean Squared Error: 0.6710557105827462"
},
{
"code": null,
"e": 6811,
"s": 6560,
"text": "It is amazing how easy it can be to not only find a test point (mean value of each posterior distribution) but also a distribution of values to estimate the error! We can now take these skills to take this simple model and keep building on top of it."
},
{
"code": null,
"e": 6860,
"s": 6811,
"text": "Enter BAyesian Model-Building Interface — Bambi."
},
{
"code": null,
"e": 7128,
"s": 6860,
"text": "As before, if we’re going to incorporate more variables we should first visualize relationships and ensure minimum correlation between features and between features/predicted variable. We can do this effectively with my favorite visualization, the scatterplot matrix."
},
{
"code": null,
"e": 7316,
"s": 7128,
"text": "It seems ‘Energy’ and ‘Loudness’ are more correlated than we’d prefer. This can cause a lot of issues when attempting to model a relationship between these variables so we can remove one."
},
{
"code": null,
"e": 7451,
"s": 7316,
"text": "Note the last row is the Log_Streams value, so we don’t need to evaluate its correlations to Streams as we’re not modeling that (yet)."
},
{
"code": null,
"e": 7530,
"s": 7451,
"text": "Using Bambi, we can easily write up our formula and cook up the model like so:"
},
{
"code": null,
"e": 7769,
"s": 7530,
"text": "I’ll skip the traceplots and forestplots to analyze the data here, but make sure to use those to ensure your model is converging on each feature properly! Traceplots are fantastic ways to immediately visualize the outputs of a MCMC model."
},
{
"code": null,
"e": 7808,
"s": 7769,
"text": "Mean Squared Error: 0.5720862510645325"
},
{
"code": null,
"e": 8076,
"s": 7808,
"text": "Note, we’re sampling 2 chains here on the posterior predictive to model the test predictions so this is why we’re taking two column-wise means — one for the mean of the two chains and two for the mean of the posterior distribution of each prediction (the test value)."
},
{
"code": null,
"e": 8661,
"s": 8076,
"text": "The MSE is significantly better as we add more features of a particular song (Danceability, Valence, Energy, and more). From assessing the means in the fitted model’s summary, it is interesting that Followers appears to have the strongest effect to increase Log_Streams out of the other values. Features such as Danceability and Speechiness appear to have a negative effect on Log_Streams, but it is important to take these features with a grain of salt as I’m not entirely sure how Spotify records this information (let alone how someone may have manipulated it to get it in Kaggle)."
},
{
"code": null,
"e": 9163,
"s": 8661,
"text": "An important question that you may have realized at this point is what about the variation of songs by artists? We are currently modeling each song individually (unpooled), but we also could model each artist’s songs (pooled). The issue with each of these is that you have to give something up for it. With unpooled, you lose the ability to see the nuance across artists; with pooled, you lose the granularity of each song’s distribution. So what can we do? Hierarchical partial pooling to the rescue!"
},
{
"code": null,
"e": 9958,
"s": 9163,
"text": "This looks much more complicated, but it’s actually beautifully simple. The whole concept of Bayesian inference that we have learned so far is that you are able to bake in prior knowledge and model a posterior distribution which is suited to be updated as new knowledge is formed. So far we have only modeled the immediate priors (the mu and sigma priors on a Normal likelihood, for example), but what if we have a hierarchical nature to our data? Wouldn’t it be great if we could model the distribution of song metadata per artist? Short answer is that we can, and easily. This is a hierarchical model and it involves you adding hyperpriors to your priors; in this case, we’re adding grouping the song metadata features by Artist and adding hyperpriors to our priors along with our likelihood."
},
{
"code": null,
"e": 10155,
"s": 9958,
"text": "In the code block, we can signify we want a hierarchical model by adding the “(1|...)” to each feature and then simply adding Priors to values appropriately. The syntax can be broken down as such:"
},
{
"code": null,
"e": 10223,
"s": 10155,
"text": "Common predictors are your main effects. For example, Danceability."
},
{
"code": null,
"e": 10622,
"s": 10223,
"text": "Group predictors can be identified by three different ways: 1. (Danceability|Artist) indicates we want to allow each artist to have his/her own slope and intercept for Danceability, 2. (1|Artist) indicates we wanted different intercepts for Artist but not slopes, and 3. (0+Danceability|Artist) indicates we only wanted slopes specific to each artist without including an artist specific intercept."
},
{
"code": null,
"e": 10767,
"s": 10622,
"text": "Obviously the less knowledge we may have, the wider priors we want to implement just the same as before. In any case, how did the model perform?"
},
{
"code": null,
"e": 11230,
"s": 10767,
"text": "Unfortunately, Bambi does not have current functionality (version 0.6.3) to do out-of-sample predictions when you’re involving categorical grouping hierarchically yet, but our model does seem to learn the distribution just as well. The benefit of doing partial pooling is that we can not only see the posterior distribution in this regard, but also measure the impact each artist’s song attribute distribution had. Here’s an example of just a few for Popularity:"
},
{
"code": null,
"e": 11726,
"s": 11230,
"text": "Although hierarchical modeling is extremely fascinating, it’s quite visible that we are not able to fully model the observed distribution as effectively. The reality in that is due to it’s non-gaussian shape. We’re attempting to model it with linear models that assume a level of normality which in reality, we just don’t see. And furthermore, our Streams don’t go below 0 ever so our Log_Streams will never go below 0 (the lowest Stream count possible is 1 and discrete). How can we model this?"
},
{
"code": null,
"e": 12343,
"s": 11726,
"text": "Generalized Linear Models are incredibly easy to implement in Bambi, and they are the solution to our issue. Our Streams are not normally distributed by nature, and so we should think about how to effectively model their real nature. A good start is the guide I outlined in Part 1 — how do we believe this data is collected? Streams are a counting measure; they reflect the number of discrete times a song has been played on Spotify. Luckily for us, there is a popular GLM type that models exactly this: Poisson. Here’s how we’d implement it with Bambi and the results (Note how we’re modeling Streams directly now)."
},
{
"code": null,
"e": 12729,
"s": 12343,
"text": "Important disclaimer: at time of writing I used the Streams field that was already standardized which isn’t correct to model as a Poisson distribution since this makes discrete count data into continuous data that lies below 0 (shoutout to Susia for catching this). Until I’m able to fix this, please make sure to know that the intended field to be modeled is the raw count of Streams."
},
{
"code": null,
"e": 12768,
"s": 12729,
"text": "Mean Squared Error: 0.2989611604295006"
},
{
"code": null,
"e": 12971,
"s": 12768,
"text": "What a dramatic improvement! But why did the MSE get so much better? Actually, I’d wager that we could get it even lower but how? The answer to this question is the essence of Bayesian Machine Learning."
},
{
"code": null,
"e": 13612,
"s": 12971,
"text": "The reason the model performed dramatically better is because we carefully thought about the data and what it represents. We thought about the nuances of it and how it is collected. Throwing endless modeling techniques at a problem could improve your metrics, but the model doesn’t truly sing until you do the hard work of strategic design. Bayesian ML gives us the ability to do this really flexibly and also gets stronger with robust and precise priors, which is another thing we did/improve on. Allowing your priors a general space to learn in can create a really informative model that is able to converge quickly and learn effectively."
},
{
"code": null,
"e": 13717,
"s": 13612,
"text": "To wrap this up with a nice bow, let’s do model comparison to see how each performed a bit more clearly."
},
{
"code": null,
"e": 14023,
"s": 13717,
"text": "By default AriZ uses leave one out cross-validation. Another option is the widely applicable information criterion (WAIC). Since the results are in the log scale, the better out-of-sample predictive fit is given by the model with the highest value, which is the Generalized Linear Model as we saw earlier."
},
{
"code": null,
"e": 14417,
"s": 14023,
"text": "This wraps up my 3 part series on Applied Bayesian Inference and we have been able to do quite a lot in that time. Honestly, I started this series knowing very little about the field and knew I wanted to learn it deeply so I figured the best way would be to build with all the knowledge I’m finding as I read around. And what better addition to then document my journey for others to learn to?"
},
{
"code": null,
"e": 14838,
"s": 14417,
"text": "I hope this series not only helped you learn this craft and dive into it yourself, but also opened your eyes to the beautiful world of Machine Learning. Learning Bayesian methods for ML gives you a greater appreciation for how a strong foundation in statistics can take you so far here. From modeling the uncertainty in your world, making predictions in spite of it, and updating your knowledge in light of new evidence."
},
{
"code": null,
"e": 15153,
"s": 14838,
"text": "The end of this series marks the official start for me with designing my brand in this space. Applied content that is meant to help you not only get started, but also understand concepts just enough to enrich your corner of the world. Follow along for more content related to the art & science of Machine Learning."
},
{
"code": null,
"e": 15164,
"s": 15153,
"text": "References"
},
{
"code": null,
"e": 15214,
"s": 15164,
"text": "[1] Osvaldo Martin, Bayesian Analysis with Python"
},
{
"code": null,
"e": 15265,
"s": 15214,
"text": "[2] PyMC3, GLM in PyMC3: Out-Of-Sample Predictions"
},
{
"code": null,
"e": 15337,
"s": 15265,
"text": "[3] PyMC3, (Generalized) Linear and Hierarchical Linear Models in PyMC3"
},
{
"code": null,
"e": 15372,
"s": 15337,
"text": "[4] PyMC3, GLM: Poisson Regression"
},
{
"code": null,
"e": 15412,
"s": 15372,
"text": "[5] PyMC3, Hierarchical Partial Pooling"
},
{
"code": null,
"e": 15476,
"s": 15412,
"text": "[6] PyMC3, A Primer on Bayesian Methods for Multilevel Modeling"
},
{
"code": null,
"e": 15553,
"s": 15476,
"text": "[7] Bambi, Wald and Gamma Regression (Australian insurance claims 2004–2005)"
},
{
"code": null,
"e": 15587,
"s": 15553,
"text": "[8] Bambi, Multi-level Regression"
},
{
"code": null,
"e": 15660,
"s": 15587,
"text": "[9] Bambi, Logistic Regression and Model Comparison with Bambi and ArviZ"
}
] |
Distilling BERT — How to achieve BERT performance using Logistic Regression | by Dima Shulga | Towards Data Science
|
BERT is awesome, and it’s everywhere. It looks like any NLP task can benefit from utilizing BERT. The authors showed that this is indeed the case, and from my experience, it works like magic. It’s easy to use, works on a small amount of data and supports many different languages. It seems like there’s no single reason not to use it everywhere. But actually, there is. Unfortunately, in practice, it is not so trivial. BERT is a huge model, more than 100 million parameters. Not only we need a GPU to fine tune it, but also in inference time, a CPU (or even many of them) is not enough. It means that if we really want to use BERT everywhere, we need to install a GPU everywhere. This is impractical in most cases. In 2015, this paper (by Hinton et al.,) introduced a way to distill the knowledge of a very big neural network into a much smaller one, like teacher and student. The method is very simple. We use the big neural network predictions to train the small one. The main idea is to use raw predictions, i.e, predictions before the final activation function (usually softmax or sigmoid). The assumption is that by using raw values, the model is able to learn inner representations better than by using “hard” predictions. Sotmax normalizes the values to 1 while keeping the maximum value high and decreases other values to something very close to zero. There’s little information in zeros, so by using raw predictions, we also learn from the not-predicted classes. The authors show good results in several tasks including MNIST and speech recognition.
Not so long ago, the authors of this paper applied the same method to ... BERT! They show that we can get the same performance (or even better) on a specific task by distilling the information from BERT into a much smaller BiLSTM neural network. You can see their results in the table below. The best performance was achieved using BiLSTM-Soft, which means “soft predictions”, i.e, training on the raw logits and not the “hard” predictions. The datasets are: SST-2 is Stanford Sentiment Treebank 2, QQP is Quora Question Pairs, MNLI is The Multi-genre Natural Language Inference.
In this post, I want to distill BERT into a much simpler Logistic Regression model. Assuming you have a relatively small labeled dataset and a much bigger non-labeled dataset, the general framework for building the model is:
Create some baseline on the labeled datasetBuild a big model by fine-tuning BERT on the labeled setIf you got good results (better than your baseline), calculate the raw logits for your unlabeled set using the big modelTrain a much smaller model (Logistic Regression) on the now pseudo-labeled setIf you got good results, deploy the small model anywhere!
Create some baseline on the labeled dataset
Build a big model by fine-tuning BERT on the labeled set
If you got good results (better than your baseline), calculate the raw logits for your unlabeled set using the big model
Train a much smaller model (Logistic Regression) on the now pseudo-labeled set
If you got good results, deploy the small model anywhere!
If you’re interested in a more basic tutorial on fine-tuning BERT, please checkout out my previous post:
towardsdatascience.com
I want to solve the same task (IMDB Reviews Sentiment Classification) but with Logistic Regression. You can find all the code in this notebook.
As before, I’ll use torchnlp to load the data and the excellent PyTorch-Pretrained-BERT to build the model.
There are 25,000 reviews in the train set, we’ll use only 1000 as a labeled set and another 5,000 as an unlabeled set (I also choose only 1000 reviews from the test set to speed things up):
train_data_full, test_data_full = imdb_dataset(train=True, test=True)rn.shuffle(train_data_full)rn.shuffle(test_data_full)train_data = train_data_full[:1000]test_data = test_data_full[:1000]
The first thing we do is create a baseline using logistic regression:
We get not so great results:
precision recall f1-score supportneg 0.80 0.80 0.80 522pos 0.78 0.79 0.78 478accuracy 0.79 1000
Next step, is to fine-tune BERT, I will skip the code here, you can see it the notebook or a more detailed tutorial in my previous post. The result is a trained model called BertBinaryClassifier which uses BERT and then a linear layer to provide the pos/neg classification. The performance of this model is:
precision recall f1-score supportneg 0.88 0.91 0.89 522pos 0.89 0.86 0.88 478accuracy 0.89 1000
Much much better! As I said — Magic :)
Now to the interesting part, we use the unlabeled set and “label” it using our fine-tuned BERT model:
We get:
precision recall f1-score supportneg 0.87 0.89 0.88 522pos 0.87 0.85 0.86 478accuracy 0.87 1000
Not as great as the original fine-tuned BERT, but it’s much better than the baseline! Now we are ready to deploy this small model to production and enjoy both good quality and inference speed.
Here’s another reason to 5 Reasons “Logistic Regression” should be the first thing you learn when becoming a Data Scientist :)
|
[
{
"code": null,
"e": 1607,
"s": 47,
"text": "BERT is awesome, and it’s everywhere. It looks like any NLP task can benefit from utilizing BERT. The authors showed that this is indeed the case, and from my experience, it works like magic. It’s easy to use, works on a small amount of data and supports many different languages. It seems like there’s no single reason not to use it everywhere. But actually, there is. Unfortunately, in practice, it is not so trivial. BERT is a huge model, more than 100 million parameters. Not only we need a GPU to fine tune it, but also in inference time, a CPU (or even many of them) is not enough. It means that if we really want to use BERT everywhere, we need to install a GPU everywhere. This is impractical in most cases. In 2015, this paper (by Hinton et al.,) introduced a way to distill the knowledge of a very big neural network into a much smaller one, like teacher and student. The method is very simple. We use the big neural network predictions to train the small one. The main idea is to use raw predictions, i.e, predictions before the final activation function (usually softmax or sigmoid). The assumption is that by using raw values, the model is able to learn inner representations better than by using “hard” predictions. Sotmax normalizes the values to 1 while keeping the maximum value high and decreases other values to something very close to zero. There’s little information in zeros, so by using raw predictions, we also learn from the not-predicted classes. The authors show good results in several tasks including MNIST and speech recognition."
},
{
"code": null,
"e": 2187,
"s": 1607,
"text": "Not so long ago, the authors of this paper applied the same method to ... BERT! They show that we can get the same performance (or even better) on a specific task by distilling the information from BERT into a much smaller BiLSTM neural network. You can see their results in the table below. The best performance was achieved using BiLSTM-Soft, which means “soft predictions”, i.e, training on the raw logits and not the “hard” predictions. The datasets are: SST-2 is Stanford Sentiment Treebank 2, QQP is Quora Question Pairs, MNLI is The Multi-genre Natural Language Inference."
},
{
"code": null,
"e": 2412,
"s": 2187,
"text": "In this post, I want to distill BERT into a much simpler Logistic Regression model. Assuming you have a relatively small labeled dataset and a much bigger non-labeled dataset, the general framework for building the model is:"
},
{
"code": null,
"e": 2767,
"s": 2412,
"text": "Create some baseline on the labeled datasetBuild a big model by fine-tuning BERT on the labeled setIf you got good results (better than your baseline), calculate the raw logits for your unlabeled set using the big modelTrain a much smaller model (Logistic Regression) on the now pseudo-labeled setIf you got good results, deploy the small model anywhere!"
},
{
"code": null,
"e": 2811,
"s": 2767,
"text": "Create some baseline on the labeled dataset"
},
{
"code": null,
"e": 2868,
"s": 2811,
"text": "Build a big model by fine-tuning BERT on the labeled set"
},
{
"code": null,
"e": 2989,
"s": 2868,
"text": "If you got good results (better than your baseline), calculate the raw logits for your unlabeled set using the big model"
},
{
"code": null,
"e": 3068,
"s": 2989,
"text": "Train a much smaller model (Logistic Regression) on the now pseudo-labeled set"
},
{
"code": null,
"e": 3126,
"s": 3068,
"text": "If you got good results, deploy the small model anywhere!"
},
{
"code": null,
"e": 3231,
"s": 3126,
"text": "If you’re interested in a more basic tutorial on fine-tuning BERT, please checkout out my previous post:"
},
{
"code": null,
"e": 3254,
"s": 3231,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3398,
"s": 3254,
"text": "I want to solve the same task (IMDB Reviews Sentiment Classification) but with Logistic Regression. You can find all the code in this notebook."
},
{
"code": null,
"e": 3506,
"s": 3398,
"text": "As before, I’ll use torchnlp to load the data and the excellent PyTorch-Pretrained-BERT to build the model."
},
{
"code": null,
"e": 3696,
"s": 3506,
"text": "There are 25,000 reviews in the train set, we’ll use only 1000 as a labeled set and another 5,000 as an unlabeled set (I also choose only 1000 reviews from the test set to speed things up):"
},
{
"code": null,
"e": 3887,
"s": 3696,
"text": "train_data_full, test_data_full = imdb_dataset(train=True, test=True)rn.shuffle(train_data_full)rn.shuffle(test_data_full)train_data = train_data_full[:1000]test_data = test_data_full[:1000]"
},
{
"code": null,
"e": 3957,
"s": 3887,
"text": "The first thing we do is create a baseline using logistic regression:"
},
{
"code": null,
"e": 3986,
"s": 3957,
"text": "We get not so great results:"
},
{
"code": null,
"e": 4164,
"s": 3986,
"text": " precision recall f1-score supportneg 0.80 0.80 0.80 522pos 0.78 0.79 0.78 478accuracy 0.79 1000"
},
{
"code": null,
"e": 4472,
"s": 4164,
"text": "Next step, is to fine-tune BERT, I will skip the code here, you can see it the notebook or a more detailed tutorial in my previous post. The result is a trained model called BertBinaryClassifier which uses BERT and then a linear layer to provide the pos/neg classification. The performance of this model is:"
},
{
"code": null,
"e": 4651,
"s": 4472,
"text": " precision recall f1-score supportneg 0.88 0.91 0.89 522pos 0.89 0.86 0.88 478accuracy 0.89 1000"
},
{
"code": null,
"e": 4690,
"s": 4651,
"text": "Much much better! As I said — Magic :)"
},
{
"code": null,
"e": 4792,
"s": 4690,
"text": "Now to the interesting part, we use the unlabeled set and “label” it using our fine-tuned BERT model:"
},
{
"code": null,
"e": 4800,
"s": 4792,
"text": "We get:"
},
{
"code": null,
"e": 4980,
"s": 4800,
"text": " precision recall f1-score supportneg 0.87 0.89 0.88 522pos 0.87 0.85 0.86 478accuracy 0.87 1000"
},
{
"code": null,
"e": 5173,
"s": 4980,
"text": "Not as great as the original fine-tuned BERT, but it’s much better than the baseline! Now we are ready to deploy this small model to production and enjoy both good quality and inference speed."
}
] |
Stack designer | Practice | GeeksforGeeks
|
You are given an array arr of size N. You need to push the elements of the array into a stack and then print them while popping.
Example 1:
Input:
n = 5
arr = {1 2 3 4 5}
Output:
5 4 3 2 1
Example 2:
Input:
n = 7
arr = {1 6 43 1 2 0 5}
Output:
5 0 2 1 43 6 1
Your Task:
Since this is a function problem, you don't need to take any input. Just complete the provided functions _push() and _pop().
Constraints:
1 <= Ai <= 107
0
mayank180919992 weeks ago
stack<int>_push(int arr[],int n)
{
stack<int>s;
for(int i=0;i<n;i++){
s.push(arr[i]);
}
return s;
}
void _pop(stack<int> s)
{
while(!s.empty()){
cout<<s.top()<<" ";
s.pop();
}
}
0
0niharika22 months ago
stack<int>_push(int arr[],int n){ stack<int> s; for(int i=0; i<n; i++) s.push(arr[i]); return s;}
void _pop(stack<int> s){ while(!s.empty()) { cout << s.top() << " "; s.pop(); }}
0
surabhichoubey552 months ago
stack<int>_push(int arr[],int n){ //return a stack with all elements of arr inserted in it stack<int>s; for(int i = 0;i<n;i++) { s.push(arr[i]); } return s; }
/* _pop function to print elements of the stack remove as well*/void _pop(stack<int> s){ //print top and pop for each element until it becomes empty while(!s.empty()) { int top = s.top(); s.pop(); cout<<top<<" "; }}
0
princejee20192 months ago
c++ code !!
stack<int>_push(int arr[],int n){ //return a stack with all elements of arr inserted in it stack<int>s; for(int i =0;i<n;i++){ s.push(arr[i]); } return s;}
/* _pop function to print elements of the stack remove as well*/void _pop(stack<int> s){ //print top and pop for each element until it becomes empty while(!s.empty()){ cout<<s.top()<<" "; s.pop(); } }
+1
ayushvats9522 months ago
stack<int>_push(int arr[],int n){ //return a stack with all elements of arr inserted in it stack<int> s; for(int i=0; i<n; i++) s.push(arr[i]); return s;}
void _pop(stack<int> s){ //print top and pop for each element until it becomes empty while(!s.empty()){ cout<<s.top()<<" "; s.pop(); } }
0
madhukartemba3 months ago
SIMPLE JAVA SOLUTION:
public static Stack<Integer>_push(ArrayList<Integer> arr,int n)
{
//Your code here
Stack<Integer> st = new Stack<>();
for(int i=0; i<n; i++)
{
st.push(arr.get(i));
}
return st;
}
public static void _pop(Stack<Integer>s)
{
while(s.isEmpty()==false)
{
System.out.print(s.pop() + " ");
}
}
0
prashspp3 months ago
from collections import dequedef _push(arr): stack=deque() for i in arr: stack.append(i) return stackdef _pop(stack): #print top and pop for each element until it becomes empty while(len(stack)>0): print(stack.pop(),end=' ')
the code is correct but the test cases are not passing i dont know what is th error in the code
0
ayushnautiyal11103 months ago
stack<int>_push(int arr[],int n){ stack<int>s; for(int i=0;i<n;i++){ s.push(arr[i]); } return s;}
/* _pop function to print elements of the stack remove as well*/void _pop(stack<int> s){ while(s.empty()==false){ cout<<s.top()<<" "; s.pop(); } }
0
s87646 months ago
@mod @geeksforgeeks please active python for this problem...
0
imranwahid6 months ago
Easy C++ solution
https://ide.geeksforgeeks.org/RFnAhbMjkK
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": 356,
"s": 226,
"text": "You are given an array arr of size N. You need to push the elements of the array into a stack and then print them while popping. "
},
{
"code": null,
"e": 368,
"s": 356,
"text": "Example 1: "
},
{
"code": null,
"e": 418,
"s": 368,
"text": "Input:\nn = 5\narr = {1 2 3 4 5}\nOutput:\n5 4 3 2 1\n"
},
{
"code": null,
"e": 430,
"s": 418,
"text": "Example 2: "
},
{
"code": null,
"e": 491,
"s": 430,
"text": "Input: \nn = 7\narr = {1 6 43 1 2 0 5}\nOutput: \n5 0 2 1 43 6 1"
},
{
"code": null,
"e": 629,
"s": 493,
"text": "Your Task:\nSince this is a function problem, you don't need to take any input. Just complete the provided functions _push() and _pop()."
},
{
"code": null,
"e": 657,
"s": 629,
"text": "Constraints:\n1 <= Ai <= 107"
},
{
"code": null,
"e": 659,
"s": 657,
"text": "0"
},
{
"code": null,
"e": 685,
"s": 659,
"text": "mayank180919992 weeks ago"
},
{
"code": null,
"e": 906,
"s": 685,
"text": "stack<int>_push(int arr[],int n)\n{\n stack<int>s;\n for(int i=0;i<n;i++){\n s.push(arr[i]);\n }\n return s;\n}\nvoid _pop(stack<int> s)\n{\n while(!s.empty()){\n cout<<s.top()<<\" \";\n s.pop();\n }\n}"
},
{
"code": null,
"e": 908,
"s": 906,
"text": "0"
},
{
"code": null,
"e": 931,
"s": 908,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 1039,
"s": 931,
"text": "stack<int>_push(int arr[],int n){ stack<int> s; for(int i=0; i<n; i++) s.push(arr[i]); return s;}"
},
{
"code": null,
"e": 1138,
"s": 1039,
"text": "void _pop(stack<int> s){ while(!s.empty()) { cout << s.top() << \" \"; s.pop(); }}"
},
{
"code": null,
"e": 1140,
"s": 1138,
"text": "0"
},
{
"code": null,
"e": 1169,
"s": 1140,
"text": "surabhichoubey552 months ago"
},
{
"code": null,
"e": 1340,
"s": 1169,
"text": "stack<int>_push(int arr[],int n){ //return a stack with all elements of arr inserted in it stack<int>s; for(int i = 0;i<n;i++) { s.push(arr[i]); } return s; }"
},
{
"code": null,
"e": 1583,
"s": 1340,
"text": "/* _pop function to print elements of the stack remove as well*/void _pop(stack<int> s){ //print top and pop for each element until it becomes empty while(!s.empty()) { int top = s.top(); s.pop(); cout<<top<<\" \"; }}"
},
{
"code": null,
"e": 1585,
"s": 1583,
"text": "0"
},
{
"code": null,
"e": 1611,
"s": 1585,
"text": "princejee20192 months ago"
},
{
"code": null,
"e": 1623,
"s": 1611,
"text": "c++ code !!"
},
{
"code": null,
"e": 1789,
"s": 1623,
"text": "stack<int>_push(int arr[],int n){ //return a stack with all elements of arr inserted in it stack<int>s; for(int i =0;i<n;i++){ s.push(arr[i]); } return s;}"
},
{
"code": null,
"e": 2012,
"s": 1789,
"text": "/* _pop function to print elements of the stack remove as well*/void _pop(stack<int> s){ //print top and pop for each element until it becomes empty while(!s.empty()){ cout<<s.top()<<\" \"; s.pop(); } } "
},
{
"code": null,
"e": 2015,
"s": 2012,
"text": "+1"
},
{
"code": null,
"e": 2040,
"s": 2015,
"text": "ayushvats9522 months ago"
},
{
"code": null,
"e": 2202,
"s": 2040,
"text": "stack<int>_push(int arr[],int n){ //return a stack with all elements of arr inserted in it stack<int> s; for(int i=0; i<n; i++) s.push(arr[i]); return s;}"
},
{
"code": null,
"e": 2368,
"s": 2204,
"text": "void _pop(stack<int> s){ //print top and pop for each element until it becomes empty while(!s.empty()){ cout<<s.top()<<\" \"; s.pop(); } }"
},
{
"code": null,
"e": 2370,
"s": 2368,
"text": "0"
},
{
"code": null,
"e": 2396,
"s": 2370,
"text": "madhukartemba3 months ago"
},
{
"code": null,
"e": 2418,
"s": 2396,
"text": "SIMPLE JAVA SOLUTION:"
},
{
"code": null,
"e": 2765,
"s": 2420,
"text": "public static Stack<Integer>_push(ArrayList<Integer> arr,int n)\n{\n //Your code here\n Stack<Integer> st = new Stack<>();\n for(int i=0; i<n; i++)\n {\n st.push(arr.get(i));\n }\n \n return st;\n}\n\npublic static void _pop(Stack<Integer>s)\n{\n while(s.isEmpty()==false)\n {\n System.out.print(s.pop() + \" \");\n }\n}"
},
{
"code": null,
"e": 2767,
"s": 2765,
"text": "0"
},
{
"code": null,
"e": 2788,
"s": 2767,
"text": "prashspp3 months ago"
},
{
"code": null,
"e": 3039,
"s": 2788,
"text": "from collections import dequedef _push(arr): stack=deque() for i in arr: stack.append(i) return stackdef _pop(stack): #print top and pop for each element until it becomes empty while(len(stack)>0): print(stack.pop(),end=' ')"
},
{
"code": null,
"e": 3135,
"s": 3039,
"text": "the code is correct but the test cases are not passing i dont know what is th error in the code"
},
{
"code": null,
"e": 3139,
"s": 3137,
"text": "0"
},
{
"code": null,
"e": 3169,
"s": 3139,
"text": "ayushnautiyal11103 months ago"
},
{
"code": null,
"e": 3277,
"s": 3169,
"text": "stack<int>_push(int arr[],int n){ stack<int>s; for(int i=0;i<n;i++){ s.push(arr[i]); } return s;}"
},
{
"code": null,
"e": 3443,
"s": 3277,
"text": "/* _pop function to print elements of the stack remove as well*/void _pop(stack<int> s){ while(s.empty()==false){ cout<<s.top()<<\" \"; s.pop(); } }"
},
{
"code": null,
"e": 3445,
"s": 3443,
"text": "0"
},
{
"code": null,
"e": 3463,
"s": 3445,
"text": "s87646 months ago"
},
{
"code": null,
"e": 3526,
"s": 3463,
"text": "@mod @geeksforgeeks please active python for this problem..."
},
{
"code": null,
"e": 3528,
"s": 3526,
"text": "0"
},
{
"code": null,
"e": 3551,
"s": 3528,
"text": "imranwahid6 months ago"
},
{
"code": null,
"e": 3569,
"s": 3551,
"text": "Easy C++ solution"
},
{
"code": null,
"e": 3610,
"s": 3569,
"text": "https://ide.geeksforgeeks.org/RFnAhbMjkK"
},
{
"code": null,
"e": 3756,
"s": 3610,
"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": 3792,
"s": 3756,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3802,
"s": 3792,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3812,
"s": 3802,
"text": "\nContest\n"
},
{
"code": null,
"e": 3875,
"s": 3812,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4023,
"s": 3875,
"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": 4231,
"s": 4023,
"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": 4337,
"s": 4231,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Call methods of an object using reflection in Java
|
The methods of an object can be called using the java.lang.Class.getDeclaredMethods() method. This method returns an array that contains all the Method objects with public, private, protected and default access. However, the inherited methods are not included.
Also, the getDeclaredMethods() method returns a zero length array if the class or interface has no methods or if a primitive type, array class or void is represented in the Class object.
A program that demonstrates this is given as follows −
Live Demo
import java.lang.reflect.Method;
class ClassA {
private String name = "John";
public String returnName() {
return name;
}
}
public class Demo {
public static void main(String[] args) throws Exception {
Class c = ClassA.class;
Method[] methods = c.getDeclaredMethods();
ClassA obj = new ClassA();
for (Method m : methods) {
Object result = m.invoke(obj, new Object[0]);
System.out.println(m.getName() + ": " + result);
}
}
}
returnName: John
|
[
{
"code": null,
"e": 1323,
"s": 1062,
"text": "The methods of an object can be called using the java.lang.Class.getDeclaredMethods() method. This method returns an array that contains all the Method objects with public, private, protected and default access. However, the inherited methods are not included."
},
{
"code": null,
"e": 1510,
"s": 1323,
"text": "Also, the getDeclaredMethods() method returns a zero length array if the class or interface has no methods or if a primitive type, array class or void is represented in the Class object."
},
{
"code": null,
"e": 1565,
"s": 1510,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1576,
"s": 1565,
"text": " Live Demo"
},
{
"code": null,
"e": 2069,
"s": 1576,
"text": "import java.lang.reflect.Method;\nclass ClassA {\n private String name = \"John\";\n public String returnName() {\n return name;\n }\n}\npublic class Demo {\n public static void main(String[] args) throws Exception {\n Class c = ClassA.class;\n Method[] methods = c.getDeclaredMethods();\n ClassA obj = new ClassA();\n for (Method m : methods) {\n Object result = m.invoke(obj, new Object[0]);\n System.out.println(m.getName() + \": \" + result);\n }\n }\n}"
},
{
"code": null,
"e": 2086,
"s": 2069,
"text": "returnName: John"
}
] |
Word2Vec For Phrases — Learning Embeddings For More Than One Word | by Moshe Hazoom | Towards Data Science
|
When it comes to semantics, we all know and love the famous Word2Vec [1] algorithm for creating word embeddings by distributional semantic representations in many NLP applications, like NER, Semantic Analysis, Text Classification and many more.
However, the limitation of the current implementation of Word2Vec algorithm is its uni-gram natural behavior. In Word2Vec, we are trying to predict a given word based on its context (CBOW), or predicting a surrounding context based on a given word (Skip-Gram). But what if we would like to embed the term “American Airlines” as its whole? In this post I will explain how to create embeddings for more than uni grams using unsupervised text corpus. If you are familiar with Word2Vec algorithm and word embeddings, you can skip the first part of this post.
Specifically, we will cover:
Introduction on words representation in NLP tasks.The Distributional Hypothesis [2] and Word2Vec algorithm.Learning phrases from unsupervised text.How to extract similar phrases to a given phrase.
Introduction on words representation in NLP tasks.
The Distributional Hypothesis [2] and Word2Vec algorithm.
Learning phrases from unsupervised text.
How to extract similar phrases to a given phrase.
The current company I work for, Amenity Analytics, is building Text Analytics products while focusing on the Finance domain. It helps businesses get actionable insights on huge scale. Recently, we release a new search engine based on Elastic Search to help our clients get a more precise and focused view on their data. After looking into users’ queries in the search engine, we noticed that many clients are searching for financial terms, while naively performing a Full Text Search with the query is not good enough. For example, one term that came up many times in users’ searches is “Inflection Point”.
Looking for the definition of “Inflection Point” in Investopedia:
“An inflection point is an event that results in a significant change in the progress of a company, industry, sector, economy or geopolitical situation and can be considered a turning point after which a dramatic change, with either positive or negative results, is expected to result”
Our clients want to see significant events in the companies they are following, thus, we need to search for more terms with the same meaning as “Inflection Point”, like “Turning Point”, “Tipping point”, etc.
Words Representation
The most granular objects in language are characters, which forms words, or tokens. Words (and character) are discrete and symbolic. There is no way to tell that “Labrador” and “dog” are somehow related to each other just by looking on the words as is, or looking on the characters that compose them.
Bag of Words (BOW)
The most common feature extraction for NLP tasks is bag-of-words (BOW) approach. In bag-of-words, we look at the histogram of word occurrences in a given corpus, without considering the order. Often, we look for more than just one word, but also on bi-grams (“I want”), tri-gram (“I want to”), or n-grams in the general case. It’s a common approach to normalize the counts for each word because the documents can differ in length (in most cases).
One of the main drawbacks of BOW representation is that it’s discrete and cannot capture semantic relationship between words.
Term Frequency — Document Inverse Frequency (TF-IDF)
One of the outcomes of BOW representation is that it gives a score for words that appeared many times, but many of them don’t give any meaningful information, like “to” and “from”. We want to distinguish between words that appear many times and are commons words to words that appear many times but gives information about the specific document. Weighting the BOW vectors is a common practice and one of the most used weighting approach is TF-IDF (Manning et al., 2008).
However, both BOW and TF-IDF cannot capture the semantic meaning of words, because they represents words, or n-grams, in a discrete way.
The Distributional Hypothesis is that words that occur in the same contexts tend to have similar meanings [2]. It’s the basis for semantic analysis of text. The idea behind the hypothesis, is that we can learn words meaning by looking on the context they appear at. One can easily tell that the word “play” in the sentence “The boy loves to play outside” has a different meaning than the word “play” in the sentence “The play was fantastic”. In general, words that are close to the target word are more informative, but in some cases there are long dependencies in the sentences between the target word and words that “far” from it. Many approaches for learning word from its context have been developed during the years, among them the famous Word2Vec, which will be covered in this post because its massive popularity both in the academia and the industry.
Word2Vec
The Distributional Hypothesis is the main idea behind Word2Vec. In Word2Vec, we have a large unsupervised corpus and for each word in the corpus, we try to predict it by its given context (CBOW), or trying to predict the context given a specific word (Skip-Gram). Word2Vec is a (shallow) neural network with one hidden layer (with dimension d) and optimization function of Negative-Sampling or Hierarchical Softmax (One can read this paper for more details). The training phase we iterate through the tokens in the corpus (the target word) and look at a window of size k (k words to each side of the target word, with the values between 2–10 in general).
At the end of the training, we will get from the network the following embedding matrix:
Now, each word will not be represented by a discrete and sparse vector, but by a d-dimension continuous vector, and the meaning of each word will be captured by its relation to other words [5]. The reason behind this is that in training time, if two target words share the some context, intuitively the weight of the network for this two target words will be close to each other and thus their matching vectors. Thus, we get a distributional representation for each word in the corpus, in contrast to count based approaches (like BOW and TF-IDF). Because of the distributional behavior, a specific dimension in the vector doesn’t give any valuable information, but looking the (distributional) vector as a whole, one can perform many similarity tasks. For example, we get that V(“King”)-V(“Man”)+V(“Woman) ~= V(“Queen”) and V(“Paris”)-V(“France)+V(“Spain”) ~= V(“Madrid”). In addition, we can perform similarity measures, like cosine-similarity, between the vectors and get that the vector of the word “president” will be close to “Obame”, “Trump”, “CEO”, “chairman”, etc.
As seen above, we can perform many similarity tasks on words using Word2Vec. But, as we mentioned above, we want to do the same for more than one word.
We can easily create bi-grams with our unsupervised corpus and take it as an input to Word2Vec. For example, the sentence “I walked today to the park” will be converted to “I_walked walked_today today_to to_the the_park” and each bi-gram will be treated as a uni-gram in the Word2Vec training phrase. It will work, but there are some problems with this approach:
It will learn embeddings only for bi-grams, while many of this bi-grams are not really meaningful (for example, “walked_today”) and we will miss embeddings for uni-gram, like “walked” and “today”.Working only with bi-grams creates a very sparse corpus. Think for example about the above sentence “I walked today to the park”. Let’s say the target word is “walked_today”, this term is not very common in the corpus and we will not have many context examples to learn a representative vector for this term.
It will learn embeddings only for bi-grams, while many of this bi-grams are not really meaningful (for example, “walked_today”) and we will miss embeddings for uni-gram, like “walked” and “today”.
Working only with bi-grams creates a very sparse corpus. Think for example about the above sentence “I walked today to the park”. Let’s say the target word is “walked_today”, this term is not very common in the corpus and we will not have many context examples to learn a representative vector for this term.
So, how we overcome this problem? how do we extract only meaningful terms while keeping words as uni-gram if their mutual information is strong enough? As always, the answer is inside the question — mutual information.
Mutual Information (MI)
Mutual information between two random variables X and Y is a measure of the dependence between X and Y. Formally:
In our case, X and Y represents all bi-grams in corpus such that y comes right after x.
Pointwise Mutual Information (PMI)
PMI is a measure of the dependence between a concrete occurrences of x of y. For example: x=walked, y=today. Formally:
It’s easy to see that when two words x and y appear together many times, but not alone, PMI(x;y) will have a high value, while it will have a value of 0 if x and y are completely independent.
Normalized Pointwise Mutual Information (NPMI)
While PMI is a measure for the dependence of occurrences of x and y, we don’t have an upper bound on its values [3]. We want a measure that can be compared between all bi-grams, thus we can choose only bi-grams above a certain threshold. We want the PMI measure to have a maximum value of 1 on perfectly correlated words x and y. Formally:
Data-driven Approach
Another way to extract phrases from text is by using the next formula [4] that takes into account the uni-grams and bi-grams count and a discounting coefficient for preventing of creation of bi-grams of too rare words. Formally:
Now that we have a way to extract meaningful bi-grams from out large unsupervised corpus, we can replace bi-grams with a NPMI above a certain threshold to one uni-gram, for example: “inflection point” will be transformed to “inflection_point”. It’s easy to create tri-grams by using the transformed corpus with bi-grams and running again the process (with a lower threshold) for form tri-grams. Similarly, we can continue this process to n-grams with a decreasing threshold.
Our corpus consists of ~60 million sentences that contain 1.6 billion words in total. It took us 1 hour to construct bi-grams using the data-driven approach. Best results achieved with a threshold of 7 and a minimum term count of 5.
We measured the results using an evaluation set that contains important bi-grams that we want to identify, like financial terms, people names (mostly CEOs and CFOs) cities, countries, etc. The metric we used is a simple recall: from our extracted bi-grams, what is the coverage in the evaluation test. In this specific task, we care more about the recall instead of the precision so we allowed our self to use a relatively small threshold when extracting the bi-grams. We do take in consider that our precision might get worse when lowering the threshold and in turn we might extract bi-grams that are not very valuable, but that’s preferable than missing important bi-grams, when performing Query Expansion task.
Example Code
Reading corpus line by line (we assume each line contain one sentence) in a memory efficient approach:
def get_sentences(input_file_pointer): while True: line = input_file_pointer.readline() if not line: break yield line
Clean sentences by trimming leading and trailing spaces, lower case, remove punctuation, remove unnecessary characters and reduce duplicate space into a single space (note that this is not really necessary because we later on tokenize our sentence by space character):
import redef clean_sentence(sentence): sentence = sentence.lower().strip() sentence = re.sub(r’[^a-z0-9\s]’, '’, sentence) return re.sub(r’\s{2,}’, ' ', sentence)
Tokenize each line by a simple space delimiter (more advanced techniques for tokenization exist, but tokenize by a simple space gave us good results and works well n practice), and remove stop-words. Removing stop-words is task dependent and in some NLP tasks, keeping the stop-words yields better results. One should evaluate both approaches. For this task, we used Spacy’s stop-word set.
from spacy.lang.en.stop_words import STOP_WORDSdef tokenize(sentence): return [token for token in sentence.split() if token not in STOP_WORDS]
Now, that we have a representations of our sentences by a 2-d matrix of cleaned tokens, we can build bi-grams. We will use Gensim library that is really recommended for NLP semantic tasks. Fortunately, Genim has an implementation for phrases extraction, both with NPMI and the above data-driven approach of Mikolov et al. One can control the hyperparameters easily, like determining the minimum term count, threshold and scoring (‘default’ for data-driven approach and ‘npmi’ for NPMI). Note that values are different between the two approaches and one needs to take it into account.
from gensim.models.phrases import Phrases, Phraserdef build_phrases(sentences): phrases = Phrases(sentences, min_count=5, threshold=7, progress_per=1000) return Phraser(phrases)
After we finish building the phrases model, we can save it easily and load it later:
phrases_model.save('phrases_model.txt')phrases_model= Phraser.load('phrases_model.txt')
Now that we have a phrases model, we can use it to extract bi-grams for a given sentence:
def sentence_to_bi_grams(phrases_model, sentence): return ' '.join(phrases_model[sentence])
We want to create, based on our corpus, a new corpus with meaningful bi-grams concatenated together for later use:
def sentences_to_bi_grams(n_grams, input_file_name, output_file_name): with open(input_file_name, 'r') as input_file_pointer: with open(output_file_name, 'w+') as out_file: for sentence in get_sentences(input_file_pointer): cleaned_sentence = clean_sentence(sentence) tokenized_sentence = tokenize(cleaned_sentence) parsed_sentence = sentence_to_bi_grams(n_grams, tokenized_sentence) out_file.write(parsed_sentence + '\n')
After this above phrase, our corpus contains phrases and we can use it as input into Word2Vec training (maybe changing hyper-parameters will be necessary) , same like before. The training phrase will consider “inflection_point” as one word and will learn a distributed d-dimensional vector that will be close to the vectors of terms like “tipping_point” or “inflection”, which is our goal!
On our 1.6 billion words corpus, it took us 1 hour to construct bi-grams and another 2 hours to train Word2Vec (with batch Skip-Gram, 300 dimension, 10 epochs, context of k=5 , negative sampling of 5, learning rate of 0.01 and minimum word count of 5) on a machine with 16 CPUs and 64 RAM using AWS Sagemaker service. A great Notebook example of how to use AWS Sagemaker service to train Word2Vec can be found here.
One can also use Gensim library to train Word2Vec model, for example here.
For example, when giving the term “Inflection Point”, we get back the following related terms, ordered by their cosine-similarity score from their represented vector and the vector of “inflection_point”:
"terms": [ { "term": "inflection", "score": 0.741 }, { "term": "tipping_point", "score": 0.667 }, { "term": "inflexion_point", "score": 0.637 }, { "term": "hit_inflection", "score": 0.624 }, { "term": "inflection_points", "score": 0.606 }, { "term": "reached_inflection", "score": 0.583 }, { "term": "cusp", "score": 0.567 }, { "term": "reaching_inflection", "score": 0.546 }, { "term": "reached_tipping", "score": 0.518 }, { "term": "hitting_inflection", "score": 0.501 } ]
Some of our clients wanted to see the affect of Black Friday on companies’ sales, so when giving the term “Black Friday” we get:
"terms": [ { "term": "cyber_monday", "score": 0.815 }, { "term": "thanksgiving_weekend", "score": 0.679 }, { "term": "holiday_season", "score": 0.645 }, { "term": "thanksgiving_holiday", "score": 0.643 }, { "term": "valentine_day", "score": 0.628 }, { "term": "mother_day", "score": 0.628 }, { "term": "christmas", "score": 0.627 }, { "term": "shopping_cyber", "score": 0.612 }, { "term": "holiday_shopping", "score": 0.608 }, { "term": "holiday", "score": 0.605 } ]
Pretty cool, isn’t it?
In this post we covered different approaches for word representation in NLP tasks (BOW, TF-IDF and Word Embeddings), learnt how to learn word representation from its context using Word2Vec, saw how we can extract meaningful phrases from a given corpus (NPMI and data-driven approach) and how to transform a given corpus in order to learn similar terms/words for each one of extracted terms/words using Word2Vec algorithm. The results of this process can be used in a downstream task, like Query Expansion in Information Extraction tasks, Document Classification, Clustering, Question-Answering and many more.
Thanks for reading!
[1] Mikolov, T., Chen, K., Corrado, G.S., & Dean, J. (2013). Efficient Estimation of Word Representations in Vector Space. CoRR, abs/1301.3781.
[2] Harris, Z. (1954). Distributional structure. Word, 10(23): 146–162.
[3] Bouma, G. (2009). Normalized ( Pointwise ) Mutual Information in Collocation Extraction.
[4] Mikolov, T., Sutskever, I., Chen, K., Corrado, G.S., & Dean, J. (2013). Distributed Representations of Words and Phrases and their Compositionality. NIPS.
[5] Goldberg, Y., Hirst, G., Liu, Y., & Zhang, M. (2017). Neural Network Methods for Natural Language Processing. Computational Linguistics, 44, 193–195.
|
[
{
"code": null,
"e": 417,
"s": 172,
"text": "When it comes to semantics, we all know and love the famous Word2Vec [1] algorithm for creating word embeddings by distributional semantic representations in many NLP applications, like NER, Semantic Analysis, Text Classification and many more."
},
{
"code": null,
"e": 972,
"s": 417,
"text": "However, the limitation of the current implementation of Word2Vec algorithm is its uni-gram natural behavior. In Word2Vec, we are trying to predict a given word based on its context (CBOW), or predicting a surrounding context based on a given word (Skip-Gram). But what if we would like to embed the term “American Airlines” as its whole? In this post I will explain how to create embeddings for more than uni grams using unsupervised text corpus. If you are familiar with Word2Vec algorithm and word embeddings, you can skip the first part of this post."
},
{
"code": null,
"e": 1001,
"s": 972,
"text": "Specifically, we will cover:"
},
{
"code": null,
"e": 1198,
"s": 1001,
"text": "Introduction on words representation in NLP tasks.The Distributional Hypothesis [2] and Word2Vec algorithm.Learning phrases from unsupervised text.How to extract similar phrases to a given phrase."
},
{
"code": null,
"e": 1249,
"s": 1198,
"text": "Introduction on words representation in NLP tasks."
},
{
"code": null,
"e": 1307,
"s": 1249,
"text": "The Distributional Hypothesis [2] and Word2Vec algorithm."
},
{
"code": null,
"e": 1348,
"s": 1307,
"text": "Learning phrases from unsupervised text."
},
{
"code": null,
"e": 1398,
"s": 1348,
"text": "How to extract similar phrases to a given phrase."
},
{
"code": null,
"e": 2005,
"s": 1398,
"text": "The current company I work for, Amenity Analytics, is building Text Analytics products while focusing on the Finance domain. It helps businesses get actionable insights on huge scale. Recently, we release a new search engine based on Elastic Search to help our clients get a more precise and focused view on their data. After looking into users’ queries in the search engine, we noticed that many clients are searching for financial terms, while naively performing a Full Text Search with the query is not good enough. For example, one term that came up many times in users’ searches is “Inflection Point”."
},
{
"code": null,
"e": 2071,
"s": 2005,
"text": "Looking for the definition of “Inflection Point” in Investopedia:"
},
{
"code": null,
"e": 2357,
"s": 2071,
"text": "“An inflection point is an event that results in a significant change in the progress of a company, industry, sector, economy or geopolitical situation and can be considered a turning point after which a dramatic change, with either positive or negative results, is expected to result”"
},
{
"code": null,
"e": 2565,
"s": 2357,
"text": "Our clients want to see significant events in the companies they are following, thus, we need to search for more terms with the same meaning as “Inflection Point”, like “Turning Point”, “Tipping point”, etc."
},
{
"code": null,
"e": 2586,
"s": 2565,
"text": "Words Representation"
},
{
"code": null,
"e": 2887,
"s": 2586,
"text": "The most granular objects in language are characters, which forms words, or tokens. Words (and character) are discrete and symbolic. There is no way to tell that “Labrador” and “dog” are somehow related to each other just by looking on the words as is, or looking on the characters that compose them."
},
{
"code": null,
"e": 2906,
"s": 2887,
"text": "Bag of Words (BOW)"
},
{
"code": null,
"e": 3353,
"s": 2906,
"text": "The most common feature extraction for NLP tasks is bag-of-words (BOW) approach. In bag-of-words, we look at the histogram of word occurrences in a given corpus, without considering the order. Often, we look for more than just one word, but also on bi-grams (“I want”), tri-gram (“I want to”), or n-grams in the general case. It’s a common approach to normalize the counts for each word because the documents can differ in length (in most cases)."
},
{
"code": null,
"e": 3479,
"s": 3353,
"text": "One of the main drawbacks of BOW representation is that it’s discrete and cannot capture semantic relationship between words."
},
{
"code": null,
"e": 3532,
"s": 3479,
"text": "Term Frequency — Document Inverse Frequency (TF-IDF)"
},
{
"code": null,
"e": 4003,
"s": 3532,
"text": "One of the outcomes of BOW representation is that it gives a score for words that appeared many times, but many of them don’t give any meaningful information, like “to” and “from”. We want to distinguish between words that appear many times and are commons words to words that appear many times but gives information about the specific document. Weighting the BOW vectors is a common practice and one of the most used weighting approach is TF-IDF (Manning et al., 2008)."
},
{
"code": null,
"e": 4140,
"s": 4003,
"text": "However, both BOW and TF-IDF cannot capture the semantic meaning of words, because they represents words, or n-grams, in a discrete way."
},
{
"code": null,
"e": 4999,
"s": 4140,
"text": "The Distributional Hypothesis is that words that occur in the same contexts tend to have similar meanings [2]. It’s the basis for semantic analysis of text. The idea behind the hypothesis, is that we can learn words meaning by looking on the context they appear at. One can easily tell that the word “play” in the sentence “The boy loves to play outside” has a different meaning than the word “play” in the sentence “The play was fantastic”. In general, words that are close to the target word are more informative, but in some cases there are long dependencies in the sentences between the target word and words that “far” from it. Many approaches for learning word from its context have been developed during the years, among them the famous Word2Vec, which will be covered in this post because its massive popularity both in the academia and the industry."
},
{
"code": null,
"e": 5008,
"s": 4999,
"text": "Word2Vec"
},
{
"code": null,
"e": 5663,
"s": 5008,
"text": "The Distributional Hypothesis is the main idea behind Word2Vec. In Word2Vec, we have a large unsupervised corpus and for each word in the corpus, we try to predict it by its given context (CBOW), or trying to predict the context given a specific word (Skip-Gram). Word2Vec is a (shallow) neural network with one hidden layer (with dimension d) and optimization function of Negative-Sampling or Hierarchical Softmax (One can read this paper for more details). The training phase we iterate through the tokens in the corpus (the target word) and look at a window of size k (k words to each side of the target word, with the values between 2–10 in general)."
},
{
"code": null,
"e": 5752,
"s": 5663,
"text": "At the end of the training, we will get from the network the following embedding matrix:"
},
{
"code": null,
"e": 6825,
"s": 5752,
"text": "Now, each word will not be represented by a discrete and sparse vector, but by a d-dimension continuous vector, and the meaning of each word will be captured by its relation to other words [5]. The reason behind this is that in training time, if two target words share the some context, intuitively the weight of the network for this two target words will be close to each other and thus their matching vectors. Thus, we get a distributional representation for each word in the corpus, in contrast to count based approaches (like BOW and TF-IDF). Because of the distributional behavior, a specific dimension in the vector doesn’t give any valuable information, but looking the (distributional) vector as a whole, one can perform many similarity tasks. For example, we get that V(“King”)-V(“Man”)+V(“Woman) ~= V(“Queen”) and V(“Paris”)-V(“France)+V(“Spain”) ~= V(“Madrid”). In addition, we can perform similarity measures, like cosine-similarity, between the vectors and get that the vector of the word “president” will be close to “Obame”, “Trump”, “CEO”, “chairman”, etc."
},
{
"code": null,
"e": 6977,
"s": 6825,
"text": "As seen above, we can perform many similarity tasks on words using Word2Vec. But, as we mentioned above, we want to do the same for more than one word."
},
{
"code": null,
"e": 7340,
"s": 6977,
"text": "We can easily create bi-grams with our unsupervised corpus and take it as an input to Word2Vec. For example, the sentence “I walked today to the park” will be converted to “I_walked walked_today today_to to_the the_park” and each bi-gram will be treated as a uni-gram in the Word2Vec training phrase. It will work, but there are some problems with this approach:"
},
{
"code": null,
"e": 7845,
"s": 7340,
"text": "It will learn embeddings only for bi-grams, while many of this bi-grams are not really meaningful (for example, “walked_today”) and we will miss embeddings for uni-gram, like “walked” and “today”.Working only with bi-grams creates a very sparse corpus. Think for example about the above sentence “I walked today to the park”. Let’s say the target word is “walked_today”, this term is not very common in the corpus and we will not have many context examples to learn a representative vector for this term."
},
{
"code": null,
"e": 8042,
"s": 7845,
"text": "It will learn embeddings only for bi-grams, while many of this bi-grams are not really meaningful (for example, “walked_today”) and we will miss embeddings for uni-gram, like “walked” and “today”."
},
{
"code": null,
"e": 8351,
"s": 8042,
"text": "Working only with bi-grams creates a very sparse corpus. Think for example about the above sentence “I walked today to the park”. Let’s say the target word is “walked_today”, this term is not very common in the corpus and we will not have many context examples to learn a representative vector for this term."
},
{
"code": null,
"e": 8570,
"s": 8351,
"text": "So, how we overcome this problem? how do we extract only meaningful terms while keeping words as uni-gram if their mutual information is strong enough? As always, the answer is inside the question — mutual information."
},
{
"code": null,
"e": 8594,
"s": 8570,
"text": "Mutual Information (MI)"
},
{
"code": null,
"e": 8708,
"s": 8594,
"text": "Mutual information between two random variables X and Y is a measure of the dependence between X and Y. Formally:"
},
{
"code": null,
"e": 8796,
"s": 8708,
"text": "In our case, X and Y represents all bi-grams in corpus such that y comes right after x."
},
{
"code": null,
"e": 8831,
"s": 8796,
"text": "Pointwise Mutual Information (PMI)"
},
{
"code": null,
"e": 8950,
"s": 8831,
"text": "PMI is a measure of the dependence between a concrete occurrences of x of y. For example: x=walked, y=today. Formally:"
},
{
"code": null,
"e": 9142,
"s": 8950,
"text": "It’s easy to see that when two words x and y appear together many times, but not alone, PMI(x;y) will have a high value, while it will have a value of 0 if x and y are completely independent."
},
{
"code": null,
"e": 9189,
"s": 9142,
"text": "Normalized Pointwise Mutual Information (NPMI)"
},
{
"code": null,
"e": 9529,
"s": 9189,
"text": "While PMI is a measure for the dependence of occurrences of x and y, we don’t have an upper bound on its values [3]. We want a measure that can be compared between all bi-grams, thus we can choose only bi-grams above a certain threshold. We want the PMI measure to have a maximum value of 1 on perfectly correlated words x and y. Formally:"
},
{
"code": null,
"e": 9550,
"s": 9529,
"text": "Data-driven Approach"
},
{
"code": null,
"e": 9779,
"s": 9550,
"text": "Another way to extract phrases from text is by using the next formula [4] that takes into account the uni-grams and bi-grams count and a discounting coefficient for preventing of creation of bi-grams of too rare words. Formally:"
},
{
"code": null,
"e": 10254,
"s": 9779,
"text": "Now that we have a way to extract meaningful bi-grams from out large unsupervised corpus, we can replace bi-grams with a NPMI above a certain threshold to one uni-gram, for example: “inflection point” will be transformed to “inflection_point”. It’s easy to create tri-grams by using the transformed corpus with bi-grams and running again the process (with a lower threshold) for form tri-grams. Similarly, we can continue this process to n-grams with a decreasing threshold."
},
{
"code": null,
"e": 10487,
"s": 10254,
"text": "Our corpus consists of ~60 million sentences that contain 1.6 billion words in total. It took us 1 hour to construct bi-grams using the data-driven approach. Best results achieved with a threshold of 7 and a minimum term count of 5."
},
{
"code": null,
"e": 11201,
"s": 10487,
"text": "We measured the results using an evaluation set that contains important bi-grams that we want to identify, like financial terms, people names (mostly CEOs and CFOs) cities, countries, etc. The metric we used is a simple recall: from our extracted bi-grams, what is the coverage in the evaluation test. In this specific task, we care more about the recall instead of the precision so we allowed our self to use a relatively small threshold when extracting the bi-grams. We do take in consider that our precision might get worse when lowering the threshold and in turn we might extract bi-grams that are not very valuable, but that’s preferable than missing important bi-grams, when performing Query Expansion task."
},
{
"code": null,
"e": 11214,
"s": 11201,
"text": "Example Code"
},
{
"code": null,
"e": 11317,
"s": 11214,
"text": "Reading corpus line by line (we assume each line contain one sentence) in a memory efficient approach:"
},
{
"code": null,
"e": 11470,
"s": 11317,
"text": "def get_sentences(input_file_pointer): while True: line = input_file_pointer.readline() if not line: break yield line"
},
{
"code": null,
"e": 11739,
"s": 11470,
"text": "Clean sentences by trimming leading and trailing spaces, lower case, remove punctuation, remove unnecessary characters and reduce duplicate space into a single space (note that this is not really necessary because we later on tokenize our sentence by space character):"
},
{
"code": null,
"e": 11911,
"s": 11739,
"text": "import redef clean_sentence(sentence): sentence = sentence.lower().strip() sentence = re.sub(r’[^a-z0-9\\s]’, '’, sentence) return re.sub(r’\\s{2,}’, ' ', sentence)"
},
{
"code": null,
"e": 12301,
"s": 11911,
"text": "Tokenize each line by a simple space delimiter (more advanced techniques for tokenization exist, but tokenize by a simple space gave us good results and works well n practice), and remove stop-words. Removing stop-words is task dependent and in some NLP tasks, keeping the stop-words yields better results. One should evaluate both approaches. For this task, we used Spacy’s stop-word set."
},
{
"code": null,
"e": 12447,
"s": 12301,
"text": "from spacy.lang.en.stop_words import STOP_WORDSdef tokenize(sentence): return [token for token in sentence.split() if token not in STOP_WORDS]"
},
{
"code": null,
"e": 13031,
"s": 12447,
"text": "Now, that we have a representations of our sentences by a 2-d matrix of cleaned tokens, we can build bi-grams. We will use Gensim library that is really recommended for NLP semantic tasks. Fortunately, Genim has an implementation for phrases extraction, both with NPMI and the above data-driven approach of Mikolov et al. One can control the hyperparameters easily, like determining the minimum term count, threshold and scoring (‘default’ for data-driven approach and ‘npmi’ for NPMI). Note that values are different between the two approaches and one needs to take it into account."
},
{
"code": null,
"e": 13278,
"s": 13031,
"text": "from gensim.models.phrases import Phrases, Phraserdef build_phrases(sentences): phrases = Phrases(sentences, min_count=5, threshold=7, progress_per=1000) return Phraser(phrases)"
},
{
"code": null,
"e": 13363,
"s": 13278,
"text": "After we finish building the phrases model, we can save it easily and load it later:"
},
{
"code": null,
"e": 13451,
"s": 13363,
"text": "phrases_model.save('phrases_model.txt')phrases_model= Phraser.load('phrases_model.txt')"
},
{
"code": null,
"e": 13541,
"s": 13451,
"text": "Now that we have a phrases model, we can use it to extract bi-grams for a given sentence:"
},
{
"code": null,
"e": 13636,
"s": 13541,
"text": "def sentence_to_bi_grams(phrases_model, sentence): return ' '.join(phrases_model[sentence])"
},
{
"code": null,
"e": 13751,
"s": 13636,
"text": "We want to create, based on our corpus, a new corpus with meaningful bi-grams concatenated together for later use:"
},
{
"code": null,
"e": 14255,
"s": 13751,
"text": "def sentences_to_bi_grams(n_grams, input_file_name, output_file_name): with open(input_file_name, 'r') as input_file_pointer: with open(output_file_name, 'w+') as out_file: for sentence in get_sentences(input_file_pointer): cleaned_sentence = clean_sentence(sentence) tokenized_sentence = tokenize(cleaned_sentence) parsed_sentence = sentence_to_bi_grams(n_grams, tokenized_sentence) out_file.write(parsed_sentence + '\\n')"
},
{
"code": null,
"e": 14645,
"s": 14255,
"text": "After this above phrase, our corpus contains phrases and we can use it as input into Word2Vec training (maybe changing hyper-parameters will be necessary) , same like before. The training phrase will consider “inflection_point” as one word and will learn a distributed d-dimensional vector that will be close to the vectors of terms like “tipping_point” or “inflection”, which is our goal!"
},
{
"code": null,
"e": 15061,
"s": 14645,
"text": "On our 1.6 billion words corpus, it took us 1 hour to construct bi-grams and another 2 hours to train Word2Vec (with batch Skip-Gram, 300 dimension, 10 epochs, context of k=5 , negative sampling of 5, learning rate of 0.01 and minimum word count of 5) on a machine with 16 CPUs and 64 RAM using AWS Sagemaker service. A great Notebook example of how to use AWS Sagemaker service to train Word2Vec can be found here."
},
{
"code": null,
"e": 15136,
"s": 15061,
"text": "One can also use Gensim library to train Word2Vec model, for example here."
},
{
"code": null,
"e": 15340,
"s": 15136,
"text": "For example, when giving the term “Inflection Point”, we get back the following related terms, ordered by their cosine-similarity score from their represented vector and the vector of “inflection_point”:"
},
{
"code": null,
"e": 16140,
"s": 15340,
"text": "\"terms\": [ { \"term\": \"inflection\", \"score\": 0.741 }, { \"term\": \"tipping_point\", \"score\": 0.667 }, { \"term\": \"inflexion_point\", \"score\": 0.637 }, { \"term\": \"hit_inflection\", \"score\": 0.624 }, { \"term\": \"inflection_points\", \"score\": 0.606 }, { \"term\": \"reached_inflection\", \"score\": 0.583 }, { \"term\": \"cusp\", \"score\": 0.567 }, { \"term\": \"reaching_inflection\", \"score\": 0.546 }, { \"term\": \"reached_tipping\", \"score\": 0.518 }, { \"term\": \"hitting_inflection\", \"score\": 0.501 } ]"
},
{
"code": null,
"e": 16269,
"s": 16140,
"text": "Some of our clients wanted to see the affect of Black Friday on companies’ sales, so when giving the term “Black Friday” we get:"
},
{
"code": null,
"e": 17061,
"s": 16269,
"text": "\"terms\": [ { \"term\": \"cyber_monday\", \"score\": 0.815 }, { \"term\": \"thanksgiving_weekend\", \"score\": 0.679 }, { \"term\": \"holiday_season\", \"score\": 0.645 }, { \"term\": \"thanksgiving_holiday\", \"score\": 0.643 }, { \"term\": \"valentine_day\", \"score\": 0.628 }, { \"term\": \"mother_day\", \"score\": 0.628 }, { \"term\": \"christmas\", \"score\": 0.627 }, { \"term\": \"shopping_cyber\", \"score\": 0.612 }, { \"term\": \"holiday_shopping\", \"score\": 0.608 }, { \"term\": \"holiday\", \"score\": 0.605 } ]"
},
{
"code": null,
"e": 17084,
"s": 17061,
"text": "Pretty cool, isn’t it?"
},
{
"code": null,
"e": 17693,
"s": 17084,
"text": "In this post we covered different approaches for word representation in NLP tasks (BOW, TF-IDF and Word Embeddings), learnt how to learn word representation from its context using Word2Vec, saw how we can extract meaningful phrases from a given corpus (NPMI and data-driven approach) and how to transform a given corpus in order to learn similar terms/words for each one of extracted terms/words using Word2Vec algorithm. The results of this process can be used in a downstream task, like Query Expansion in Information Extraction tasks, Document Classification, Clustering, Question-Answering and many more."
},
{
"code": null,
"e": 17713,
"s": 17693,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 17857,
"s": 17713,
"text": "[1] Mikolov, T., Chen, K., Corrado, G.S., & Dean, J. (2013). Efficient Estimation of Word Representations in Vector Space. CoRR, abs/1301.3781."
},
{
"code": null,
"e": 17929,
"s": 17857,
"text": "[2] Harris, Z. (1954). Distributional structure. Word, 10(23): 146–162."
},
{
"code": null,
"e": 18022,
"s": 17929,
"text": "[3] Bouma, G. (2009). Normalized ( Pointwise ) Mutual Information in Collocation Extraction."
},
{
"code": null,
"e": 18181,
"s": 18022,
"text": "[4] Mikolov, T., Sutskever, I., Chen, K., Corrado, G.S., & Dean, J. (2013). Distributed Representations of Words and Phrases and their Compositionality. NIPS."
}
] |
How To Install Go (Golang) 1.7 on CentOS 7
|
In this article, we will learn about how to install and configure Go (golang) which is developed by Google and its open source programming language. It’s a simple, efficient and reliable programming language for development with minimalist.
A CentOS machine installed.
A non-root user with Sudo permission on the CentOS machine.
The Go (golang) is not up to date on the CentOS repository, so we will manually download and install the package directly from the Go lang website and also make sure that we have the latest version which is compatible with our system architecture.
Let’s move to the writable and temporary directory where we can download the package from the Go website and install.
$ cd /tmp
We will use the curl command to download the Go with the below link
$ curl -LO https://storage.googleapis.com/golang/go1.7.linux-amd64.tar.gz
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
84 77.7M 84 65.5M 0 0 493k 0 0:02:41 0:02:15 0:00:26 0
curl: (56) TCP connection reset by peer
Once the package is downloaded from the site, we will extract the package to /usr/local and install the package.
Below is the command to extract the package to /usr/local
$ tar -C /usr/local/ -xvf go1.7.linux-amd64.tar.gz
Once the packages are extracted in /usr/local we needed to create a workspace with three sub-directories, we consider the parent directory as ~/myproject, below is the command to create the three sub-directories.
$ mkdir –p ~/myproject/{bin,pkg,src}
If we want to execute the Go like the other command we needed to all the paths to the $PATH variables for that we needed to create a file path.sh to /etc/profile.d folder using any text editor
$ sudo nano /etc/profiled/path.sh
Export PATH=$PATH:/usr/local/go/bin
We have to define the GOPATH and GOBIN which are GO environment variable on the .bash_profile for pointing the workspace. Where are GOPATH will show the location of the source files and GOBIN will stores the binary files which are created and is compiled.
Edit the .bash_profile with any of your choice editor using the below command
$ nano ~/.bash_profile
export GOBIN="$HOME/myprojects/bin"
export GOPATH="$HOME/myprojects/src"
To apply the changes made in the .bash_profile we needed to run the below command
$ source /etc/profile && source ~/.bash_profile
As the Go (golang) environment is ready, we needed to test our environment, we will write one simple Go program.
$ nano ~/myprojects/src/welcome.go
Below is the code which will print Welcome to the Go (golang) .
Package main
Import “fmt”
Func main()
{
Fmt.Printf(“Welcome to the Go (golang) \n “)
}
As we have written a simple code for testing the Go environment, we have to compile the ‘welcome.go’ with go install command, bellow is the full command to compile the file.
$ go install $GOPATH/welcome.go
Once the program is compiled, we can test the program with the below command –
$ $GOBIN/welcome
Welcome to the Go (golang)
In the above article we have learned how to install the Go (golang) programming language which is from Google and we have written a simple program and executed to test the environment to confirm the installation is successful.
|
[
{
"code": null,
"e": 1303,
"s": 1062,
"text": "In this article, we will learn about how to install and configure Go (golang) which is developed by Google and its open source programming language. It’s a simple, efficient and reliable programming language for development with minimalist."
},
{
"code": null,
"e": 1331,
"s": 1303,
"text": "A CentOS machine installed."
},
{
"code": null,
"e": 1391,
"s": 1331,
"text": "A non-root user with Sudo permission on the CentOS machine."
},
{
"code": null,
"e": 1639,
"s": 1391,
"text": "The Go (golang) is not up to date on the CentOS repository, so we will manually download and install the package directly from the Go lang website and also make sure that we have the latest version which is compatible with our system architecture."
},
{
"code": null,
"e": 1757,
"s": 1639,
"text": "Let’s move to the writable and temporary directory where we can download the package from the Go website and install."
},
{
"code": null,
"e": 1767,
"s": 1757,
"text": "$ cd /tmp"
},
{
"code": null,
"e": 1835,
"s": 1767,
"text": "We will use the curl command to download the Go with the below link"
},
{
"code": null,
"e": 2104,
"s": 1835,
"text": "$ curl -LO https://storage.googleapis.com/golang/go1.7.linux-amd64.tar.gz\n% Total % Received % Xferd Average Speed Time Time Time Current\nDload Upload Total Spent Left Speed\n84 77.7M 84 65.5M 0 0 493k 0 0:02:41 0:02:15 0:00:26 0\ncurl: (56) TCP connection reset by peer"
},
{
"code": null,
"e": 2217,
"s": 2104,
"text": "Once the package is downloaded from the site, we will extract the package to /usr/local and install the package."
},
{
"code": null,
"e": 2275,
"s": 2217,
"text": "Below is the command to extract the package to /usr/local"
},
{
"code": null,
"e": 2326,
"s": 2275,
"text": "$ tar -C /usr/local/ -xvf go1.7.linux-amd64.tar.gz"
},
{
"code": null,
"e": 2539,
"s": 2326,
"text": "Once the packages are extracted in /usr/local we needed to create a workspace with three sub-directories, we consider the parent directory as ~/myproject, below is the command to create the three sub-directories."
},
{
"code": null,
"e": 2576,
"s": 2539,
"text": "$ mkdir –p ~/myproject/{bin,pkg,src}"
},
{
"code": null,
"e": 2769,
"s": 2576,
"text": "If we want to execute the Go like the other command we needed to all the paths to the $PATH variables for that we needed to create a file path.sh to /etc/profile.d folder using any text editor"
},
{
"code": null,
"e": 2839,
"s": 2769,
"text": "$ sudo nano /etc/profiled/path.sh\nExport PATH=$PATH:/usr/local/go/bin"
},
{
"code": null,
"e": 3095,
"s": 2839,
"text": "We have to define the GOPATH and GOBIN which are GO environment variable on the .bash_profile for pointing the workspace. Where are GOPATH will show the location of the source files and GOBIN will stores the binary files which are created and is compiled."
},
{
"code": null,
"e": 3173,
"s": 3095,
"text": "Edit the .bash_profile with any of your choice editor using the below command"
},
{
"code": null,
"e": 3269,
"s": 3173,
"text": "$ nano ~/.bash_profile\nexport GOBIN=\"$HOME/myprojects/bin\"\nexport GOPATH=\"$HOME/myprojects/src\""
},
{
"code": null,
"e": 3351,
"s": 3269,
"text": "To apply the changes made in the .bash_profile we needed to run the below command"
},
{
"code": null,
"e": 3399,
"s": 3351,
"text": "$ source /etc/profile && source ~/.bash_profile"
},
{
"code": null,
"e": 3512,
"s": 3399,
"text": "As the Go (golang) environment is ready, we needed to test our environment, we will write one simple Go program."
},
{
"code": null,
"e": 3547,
"s": 3512,
"text": "$ nano ~/myprojects/src/welcome.go"
},
{
"code": null,
"e": 3611,
"s": 3547,
"text": "Below is the code which will print Welcome to the Go (golang) ."
},
{
"code": null,
"e": 3722,
"s": 3611,
"text": "Package main\nImport “fmt”\n Func main()\n {\n Fmt.Printf(“Welcome to the Go (golang) \\n “)\n }"
},
{
"code": null,
"e": 3896,
"s": 3722,
"text": "As we have written a simple code for testing the Go environment, we have to compile the ‘welcome.go’ with go install command, bellow is the full command to compile the file."
},
{
"code": null,
"e": 3928,
"s": 3896,
"text": "$ go install $GOPATH/welcome.go"
},
{
"code": null,
"e": 4007,
"s": 3928,
"text": "Once the program is compiled, we can test the program with the below command –"
},
{
"code": null,
"e": 4051,
"s": 4007,
"text": "$ $GOBIN/welcome\nWelcome to the Go (golang)"
},
{
"code": null,
"e": 4278,
"s": 4051,
"text": "In the above article we have learned how to install the Go (golang) programming language which is from Google and we have written a simple program and executed to test the environment to confirm the installation is successful."
}
] |
Explain Nested if-else statement in C language
|
A ‘nested if’ is an if statement that is the object of either if (or) an else. ‘if’ is placed inside another if (or) else.
Refer the syntax given below −
if (condition1){
if (condition2)
stmt1;
else
stmt2;
}
else{
if (condition3)
stmt3;
else
stmt4;
}
Given below is the C program to execute Nested If Else conditional operators −
Live Demo
#include<stdio.h>
void main (){
int a,b,c,d;
printf("Enter the values of a,b,c: \n");
scanf("%d,%d,%d",&a,&b,&c);
if((a>b)&&(a>c)){//Work with 4 numbers//
if(a>c){
printf("%d is the largest",a);
} else {
printf("%d is the largest",c);
}
} else {
if(b>c){
printf("%d is the largest",b);
} else {
printf("%d is the largest",c);
}
}
}
You will see the following output −
Enter the values of a,b,c: 3,5,8
8 is the largest
Following is the C program to check the number is positive or negative −
Live Demo
#include <stdio.h>
int main(){
int num;
printf("Enter a number:\n ");
scanf ("%d ", &num);
if(num > 0){
printf("This is positive num:%d\n", num);
}
else if(num < 0){
printf("This is a negative num:%d",num);
} else {
printf("This is a zero:%d",num);
}
return 0;
}
You will see the following output −
Run 1: Enter a number:
23
23=This number is positive
Run 2: Enter a number:
-56
-56=This number is negative
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "A ‘nested if’ is an if statement that is the object of either if (or) an else. ‘if’ is placed inside another if (or) else."
},
{
"code": null,
"e": 1216,
"s": 1185,
"text": "Refer the syntax given below −"
},
{
"code": null,
"e": 1349,
"s": 1216,
"text": "if (condition1){\n if (condition2)\n stmt1;\n else\n stmt2;\n}\nelse{\n if (condition3)\n stmt3;\n else\n stmt4;\n}"
},
{
"code": null,
"e": 1428,
"s": 1349,
"text": "Given below is the C program to execute Nested If Else conditional operators −"
},
{
"code": null,
"e": 1439,
"s": 1428,
"text": " Live Demo"
},
{
"code": null,
"e": 1861,
"s": 1439,
"text": "#include<stdio.h>\nvoid main (){\n int a,b,c,d;\n printf(\"Enter the values of a,b,c: \\n\");\n scanf(\"%d,%d,%d\",&a,&b,&c);\n if((a>b)&&(a>c)){//Work with 4 numbers//\n if(a>c){\n printf(\"%d is the largest\",a);\n } else {\n printf(\"%d is the largest\",c);\n }\n } else {\n if(b>c){\n printf(\"%d is the largest\",b);\n } else {\n printf(\"%d is the largest\",c);\n }\n }\n}"
},
{
"code": null,
"e": 1897,
"s": 1861,
"text": "You will see the following output −"
},
{
"code": null,
"e": 1947,
"s": 1897,
"text": "Enter the values of a,b,c: 3,5,8\n8 is the largest"
},
{
"code": null,
"e": 2020,
"s": 1947,
"text": "Following is the C program to check the number is positive or negative −"
},
{
"code": null,
"e": 2031,
"s": 2020,
"text": " Live Demo"
},
{
"code": null,
"e": 2339,
"s": 2031,
"text": "#include <stdio.h>\nint main(){\n int num;\n printf(\"Enter a number:\\n \");\n scanf (\"%d \", &num);\n if(num > 0){\n printf(\"This is positive num:%d\\n\", num);\n }\n else if(num < 0){\n printf(\"This is a negative num:%d\",num);\n } else {\n printf(\"This is a zero:%d\",num);\n }\n return 0;\n}"
},
{
"code": null,
"e": 2375,
"s": 2339,
"text": "You will see the following output −"
},
{
"code": null,
"e": 2483,
"s": 2375,
"text": "Run 1: Enter a number:\n23\n23=This number is positive\nRun 2: Enter a number:\n-56\n-56=This number is negative"
}
] |
Tk - Menu Widget
|
Tk menu widget is used along with Tk widget menubutton. So, we will see menubutton first. The syntax for menu button widget is shown below −
menubutton menubuttonName options
The options available for the menu button widget are listed below in the following table −
-command action
Sets the command action for button.
-text text
Sets the text for the widget.
-textvariable varName
Variable associated with the widget. When the text of widget changes, the variable is set to text of widget.
-width number
Sets the width for widget.
-menu menuName
Specifies the name of associated menu widget.
-underline charPosition
Sets the position for hotkey.
The syntax for menu is shown below −
menu menuName options
The options available for the menu widget are listed below in the following table −
-font fontDescriptor
Used to set font for widget.
-postcommand action
Sets the command action to be done before a menu is posted.
-menu menuName
Specifies the name of associated menu widget.
-tearoff boolean
Allows or disallows a menu to be removed from the menubutton and displayed in a permanent window. Default is enabled.
The syntax for adding menubutton is shown below −
menuName add type menubuttonType options
The type includes separator, cascade, checkbutton, radiobutton, and command.
The options available for the menuName add are listed below in table −
-command action
Sets the command action for the menubutton.
-menu menuName
Specifies the name of associated menu widget.
-label string
Set the text of the menu.
-variable varName
Sets the variable to be set when this entry is selected.
-value string
The value is set for the variable.
-underline position
Sets the position for hotkey.
A simple Tk menu is shown below −
#!/usr/bin/wish
menubutton .myMenubutton -menu .myMenubutton.myMenu -text "ChangeText"
menu .myMenubutton.myMenu
.myMenubutton.myMenu add command -label Hello -command {set myvariable "Hello"}
.myMenubutton.myMenu add command -label World -command {set myvariable "World"}
pack .myMenubutton
pack [label .myLabel -text "Select An option" -font {Helvetica -18 bold} -height 5
-width 15 -textvariable myvariable]
When we run the above program, we will get the following output −
When we select a menu option, we will get an output as shown below −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2342,
"s": 2201,
"text": "Tk menu widget is used along with Tk widget menubutton. So, we will see menubutton first. The syntax for menu button widget is shown below −"
},
{
"code": null,
"e": 2377,
"s": 2342,
"text": "menubutton menubuttonName options\n"
},
{
"code": null,
"e": 2468,
"s": 2377,
"text": "The options available for the menu button widget are listed below in the following table −"
},
{
"code": null,
"e": 2484,
"s": 2468,
"text": "-command action"
},
{
"code": null,
"e": 2520,
"s": 2484,
"text": "Sets the command action for button."
},
{
"code": null,
"e": 2531,
"s": 2520,
"text": "-text text"
},
{
"code": null,
"e": 2561,
"s": 2531,
"text": "Sets the text for the widget."
},
{
"code": null,
"e": 2583,
"s": 2561,
"text": "-textvariable varName"
},
{
"code": null,
"e": 2692,
"s": 2583,
"text": "Variable associated with the widget. When the text of widget changes, the variable is set to text of widget."
},
{
"code": null,
"e": 2706,
"s": 2692,
"text": "-width number"
},
{
"code": null,
"e": 2733,
"s": 2706,
"text": "Sets the width for widget."
},
{
"code": null,
"e": 2748,
"s": 2733,
"text": "-menu menuName"
},
{
"code": null,
"e": 2794,
"s": 2748,
"text": "Specifies the name of associated menu widget."
},
{
"code": null,
"e": 2818,
"s": 2794,
"text": "-underline charPosition"
},
{
"code": null,
"e": 2848,
"s": 2818,
"text": "Sets the position for hotkey."
},
{
"code": null,
"e": 2885,
"s": 2848,
"text": "The syntax for menu is shown below −"
},
{
"code": null,
"e": 2908,
"s": 2885,
"text": "menu menuName options\n"
},
{
"code": null,
"e": 2992,
"s": 2908,
"text": "The options available for the menu widget are listed below in the following table −"
},
{
"code": null,
"e": 3013,
"s": 2992,
"text": "-font fontDescriptor"
},
{
"code": null,
"e": 3042,
"s": 3013,
"text": "Used to set font for widget."
},
{
"code": null,
"e": 3062,
"s": 3042,
"text": "-postcommand action"
},
{
"code": null,
"e": 3122,
"s": 3062,
"text": "Sets the command action to be done before a menu is posted."
},
{
"code": null,
"e": 3137,
"s": 3122,
"text": "-menu menuName"
},
{
"code": null,
"e": 3183,
"s": 3137,
"text": "Specifies the name of associated menu widget."
},
{
"code": null,
"e": 3200,
"s": 3183,
"text": "-tearoff boolean"
},
{
"code": null,
"e": 3318,
"s": 3200,
"text": "Allows or disallows a menu to be removed from the menubutton and displayed in a permanent window. Default is enabled."
},
{
"code": null,
"e": 3368,
"s": 3318,
"text": "The syntax for adding menubutton is shown below −"
},
{
"code": null,
"e": 3410,
"s": 3368,
"text": "menuName add type menubuttonType options\n"
},
{
"code": null,
"e": 3487,
"s": 3410,
"text": "The type includes separator, cascade, checkbutton, radiobutton, and command."
},
{
"code": null,
"e": 3558,
"s": 3487,
"text": "The options available for the menuName add are listed below in table −"
},
{
"code": null,
"e": 3574,
"s": 3558,
"text": "-command action"
},
{
"code": null,
"e": 3618,
"s": 3574,
"text": "Sets the command action for the menubutton."
},
{
"code": null,
"e": 3633,
"s": 3618,
"text": "-menu menuName"
},
{
"code": null,
"e": 3679,
"s": 3633,
"text": "Specifies the name of associated menu widget."
},
{
"code": null,
"e": 3693,
"s": 3679,
"text": "-label string"
},
{
"code": null,
"e": 3719,
"s": 3693,
"text": "Set the text of the menu."
},
{
"code": null,
"e": 3737,
"s": 3719,
"text": "-variable varName"
},
{
"code": null,
"e": 3794,
"s": 3737,
"text": "Sets the variable to be set when this entry is selected."
},
{
"code": null,
"e": 3808,
"s": 3794,
"text": "-value string"
},
{
"code": null,
"e": 3843,
"s": 3808,
"text": "The value is set for the variable."
},
{
"code": null,
"e": 3863,
"s": 3843,
"text": "-underline position"
},
{
"code": null,
"e": 3893,
"s": 3863,
"text": "Sets the position for hotkey."
},
{
"code": null,
"e": 3927,
"s": 3893,
"text": "A simple Tk menu is shown below −"
},
{
"code": null,
"e": 4343,
"s": 3927,
"text": "#!/usr/bin/wish\n\nmenubutton .myMenubutton -menu .myMenubutton.myMenu -text \"ChangeText\"\nmenu .myMenubutton.myMenu\n.myMenubutton.myMenu add command -label Hello -command {set myvariable \"Hello\"}\n.myMenubutton.myMenu add command -label World -command {set myvariable \"World\"}\npack .myMenubutton\npack [label .myLabel -text \"Select An option\" -font {Helvetica -18 bold} -height 5\n -width 15 -textvariable myvariable]"
},
{
"code": null,
"e": 4409,
"s": 4343,
"text": "When we run the above program, we will get the following output −"
},
{
"code": null,
"e": 4478,
"s": 4409,
"text": "When we select a menu option, we will get an output as shown below −"
},
{
"code": null,
"e": 4485,
"s": 4478,
"text": " Print"
},
{
"code": null,
"e": 4496,
"s": 4485,
"text": " Add Notes"
}
] |
A Tutorial Using Spark for Big Data: An Example to Predict Customer Churn | by Ying Geng | Towards Data Science
|
Apache Spark has become arguably the most popular tool for analyzing large data sets. As my capstone project for Udacity’s Data Science Nanodegree, I’ll demonstrate the use of Spark for scalable data manipulation and machine learning. Context-wise, we use the user log data from a fictitious music streaming company, Sparkify, to predict which customers are at risk to churn.
The full data set is 12GB. we’ll first analyze a mini subset (128MB) and build classification models using Spark Dataframe, Spark SQL, and Spark ML APIs in local mode through the python interface API, PySpark. Then we’ll deploy a Spark cluster on AWS to run the models on the full 12GB of data. Hereafter, we assume that Spark and PySpark are installed (a tutorial for installing PySpark).
Before we are able to read csv, json, or xml data into Spark dataframes, a Spark session needs to be set up. A Spark session is a unified entry point for Spark applications from Spark 2.0. Note that prior to Spark 2.0, various Spark contexts are needed to interact with Spark’s different functionalities (a good Medium article on this).
# Set up a SparkSessionfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName("capstone").getOrCreate()
# Load data and show basic data shapepath = "mini_sparkify_event_data.json"df = spark.read.json(path)
Now that the mini Sparkify user log data set is in the Spark dataframe format, we can do some initial exploration to get familiar with the data. Spark dataframe and Spark SQL modules have methods such as the following: select(), filter(), where(), groupBy(), sort(), dropDuplicates(), count(), avg(), max(), min(). They also have Window functions that are useful for basic analysis (see documentation for syntax). To summarize the data:
The dataset has 286500 rows and 18 columns.It spans the time period from 2018–9–30 to 2018–12–02.It records each event users did during this time period as a row.Column definitions are as follow:
The dataset has 286500 rows and 18 columns.
It spans the time period from 2018–9–30 to 2018–12–02.
It records each event users did during this time period as a row.
Column definitions are as follow:
-- artist (string): artist's name for a song -- auth (string): Logged Out | Cancelled | Guest | Logged In -- firstName (string): user's firstname -- gender (string): Female | Male -- itemInSession (long) : number of items in a session -- lastName (string): user's lastname -- length (double): a song's length in seconds -- level (string): paid | free -- location (string): city and state of the user -- method (string): HTTP method -- page (string): which page a user is on at an event -- registration (long): timestamp of user registration -- sessionId (long): the Id of the session a user is in at an event -- song (string): song name -- status(long): 307 | 404 | 200 -- ts (long): timestamp ateach event -- userAgent (string) : -- userId (string): user ID
5. Some of these columns probably are not very useful for prediction, such as firstName, lastName, method, and userAgent. Categorical features need to be encoded, such as gender and level. Some numerical features will be useful for engineering aggregated behavior features, such as itemInSession, length, page visits, etc.
6. Class is imbalanced; we need to consider stratified sampling when we split training test data. We also should consider the f1 score over the accuracy for our model evaluation metrics.
7. For models, we will try Logistic Regression, Decision Tree, Random Forest, and Gradient Boosted Trees.
With these initial thoughts, let’s proceed with handling missing values.
The seaborn heatmap is a good way to show where missing values are located in the dataset and whether data is missing in some systematic way.
# Let's take a look at where the missing values are located.plt.figure(figsize=(18,6))sns.heatmap(df.toPandas().isnull(),cbar=False)
Note (1): From the heatmap, we can see that firstName, lastName, gender, location, userAgent, and registration are missing at same rows. We can infer that these missing values come from users that are not registered. Usually, users who are not registered would not have a user ID. We’ll explore this further.
df.select(‘userid’).filter(‘registration is null’).show(3)
It turns out that the userId column actually has missing values, but they are coded as just empty, instead of coded as a “NaN”. The number of such null values match the number of missing rows in registration. Since these records do not even have userId information, we’ll go ahead and delete them.
Note (2): Also, artist, length, and song are missing data at the same rows. These records do not have song-related information. We’ll explore what pages users are on for these rows.
print(df_pd[df_pd.artist.isnull()][‘page’].value_counts())print(df_pd[df_pd.artist.isnull()==False][‘page’].value_counts())Thumbs Up 12551Home 10082Add to Playlist 6526Add Friend 4277Roll Advert 3933Logout 3226Thumbs Down 2546Downgrade 2055Settings 1514Help 1454Upgrade 499About 495Save Settings 310Error 252Submit Upgrade 159Submit Downgrade 63Cancel 52Cancellation Confirmation 52Name: page, dtype: int64NextSong 228108Name: page, dtype: int64
Based on intuition and domain knowledge, we decide not to include the columns for firstName, lastName, method, and userAgent in our first-pass modeling for now, since these variables probably do not affect our prediction. We also decide not to include artist, location, song, and status for now. This leaves us with the following columns:
-- gender (string): Female | Male -- itemInSession (long) : number of items in a session -- length (double): a song's length in seconds -- level (string): paid | free -- page (string): which page a user is on at an event -- registration (long): timestamp of user registration -- sessionId (long): the Id of the session a user is in at an event -- ts (long): timestamp ateach event -- userId (string): user ID
1) Define Churned User: We can see that there is approximately a 1:3 class imbalance.
flag_cancellation = udf(lambda x : 1 if x=="Cancellation Confirmation" else 0, IntegerType())df = df.withColumn("churn",flag_cancellation("page"))# Create the cross-sectional data that we’ll use in analysis and modellingw1 = Window.partitionBy(‘userId’)df_user = df.select(‘userId’,’churn’,’gender’,’level’) \ .withColumn(‘churned_user’,Fsum(‘churn’).over(w1)) \ .dropDuplicates([‘userId’]).drop(‘churn’)df_user.groupby(‘churned_user’).count().show()+------------+-----+|churned_user|count|+------------+-----+| 0| 173|| 1| 52|+------------+-----+
2) Categorical features: For categorical features, we need to first label encoding (simply converting each value to a number). Depending on the machine learning models, we may need to further encode these numbers to dummy variables (e.g., one-hot encoding).
In Spark, StringIndexer does the label encoding part:
indexer = StringIndexer(inputCol="gender",outputCol="genderIndex")df_user = indexer.fit(df_user).transform(df_user)indexer = StringIndexer(inputCol="level",outputCol="levelIndex")df_user = indexer.fit(df_user).transform(df_user)df_user.show(3)+------+------+-----+------------+-----------+----------+|userId|gender|level|churned_user|genderIndex|levelIndex|+------+------+-----+------------+-----------+----------+|100010| F| free| 0| 1.0| 0.0||200002| M| free| 0| 0.0| 0.0|| 125| M| free| 1| 0.0| 0.0|+------+------+-----+------------+-----------+----------+only showing top 3 rows
Let’s take a look at how gender and level are related to churn. By looking at the simple statistics, it seems that a larger percentage of male users tend to churn than female users and that a larger percentage of paid users tend to churn than free users.
df_user.groupby(‘genderIndex’).avg(‘churned_user’).show()+-----------+-------------------+|genderIndex| avg(churned_user)|+-----------+-------------------+| 0.0| 0.2644628099173554|| 1.0|0.19230769230769232|+-----------+-------------------+df_user.groupby('churned_user').avg('levelIndex').show()+------------+-------------------+|churned_user| avg(levelIndex)|+------------+-------------------+| 0|0.23121387283236994|| 1|0.15384615384615385|+------------+-------------------+
Since we will utilize Logistic Regression and SVM classifier, we will need to convert label encoding to dummy variables. OneHotEncoderEstimator() does this part:
encoder = OneHotEncoderEstimator(inputCols=[“genderIndex”, “levelIndex”], outputCols=[“genderVector”, “levelVector”])model = encoder.fit(df_user)df_user = model.transform(df_user)df_user.select('genderVector','levelVector').show(3)+------+-------------+-------------+|userId| genderVector| levelVector|+------+-------------+-------------+|100010| (1,[],[])|(1,[0],[1.0])||200002|(1,[0],[1.0])|(1,[0],[1.0])|| 125|(1,[0],[1.0])|(1,[0],[1.0])|+------+-------------+-------------+only showing top 3 rows
The output columns of OneHotEncoderEstimator() is not the same as sklearn’s output. Instead of binary values, it gives this sparse vector format as shown in the above code snippet.
3) General activity aggregates: Based on the columns for sessionId, song, artist, length, and registration, we generate aggregated features including:
numSessions (number of sessions a user had during this period)
numSongs (number of different songs a user listened to)
numArtists (number of different artists a user listened to)
playTime (total time of playing songs measured in seconds)
activeDays (number of days since a user registered)
4) Page visits aggregates: Based on the page column, we generate aggregated page visit behavior features that count how many times a user visited each type of pages during the period.
w2 = Window.partitionBy('userId','page')columns = [str(row.page) for row in df.select('page')\ .dropDuplicates().sort('page').collect()]df_pageVisits = df.select('userId','page')\ .withColumn('pageVisits',count('userId').over(w2))\ .groupby('userId')\ .pivot('page',columns)\ .mean('pageVisits')df_pageVisits = df_pageVisits.na.fill(0).drop(['Cancel','Cancellation Confirmation'],axis=1)
5) Check for multicollinearity: Tree-based models would not be affected by multicollinearity, but, since we are also testing linear models (logistic regression and svm), we’ll go ahead and remove highly correlated features.
6) Vector Assembling and Feature Scaling: In Spark, machine learning models require features to be a vector type. The VectorAssembler() method converts all the feature columns into one vector, as shown in the following code snippet.
# Vector Assemblercols = df_inuse.drop('userID','churned_user').columnsassembler=VectorAssembler(inputCols=cols,outputCol='feature_vector')df_inuse=assembler.transform(df_inuse).select('userId','churned_user','feature_vector')df_inuse.take(1)[Row(userId='100010', churned_user=0, feature_vector=SparseVector(13, {0: 1.0, 2: 52.0, 6: 2.0, 7: 7.0, 8: 11.4259, 9: 1.0, 12: 1.0}))]
The scaled data looks like this:
df_inuse_scaled.take(1)[Row(userId='100010', label=0, feature_vector=SparseVector(13, {0: 1.0, 2: 52.0, 6: 2.0, 7: 7.0, 8: 11.4259, 9: 1.0, 12: 1.0}), features=SparseVector(13, {0: 0.3205, 2: 2.413, 6: 0.7817, 7: 0.4779, 8: 0.3488, 9: 2.0013, 12: 2.4356}))]
7) Split data into training and testing sets:
ratio = 0.8train = df_inuse_scaled.sampleBy(‘churned_user’,fractions={0:ratio,1:ratio}, seed = 42)test = df_inuse_scaled.subtract(train)
We will compare five baseline models: Logistic Regression, Linear SVM Classifier, Decision Tree, Random Forests, and Gradient Boosted Tree Classifier.
# initiate the modelslr = LogisticRegression()svc = LinearSVC()dtc = DecisionTreeClassifier()rfc = RandomForestClassifier()gbt = GBTClassifier()
The ParaGridBuilder() class can be used to construct a grid of hyper-parameters to search over. However, since the purpose here is to show Spark’s ML methods, we will not do an in-depth tuning of the model here.
# this line will keep the default hyper-parameters of a modelparamGrid = ParamGridBuilder().build()# to search over more parameters, we can use the ,,addGrid() method, for example:paramGrid = ParamGridBuilder()\ .addGrid(lr.regParam, [0.1, 0.01]) \ .addGrid(lr.fitIntercept, [False, True])\ .addGrid(lr.elasticNetParam, [0.0, 0.5, 1.0])\ .build()
We’ll define an evaluation function to run through all five classification models and output their cross validation average metrics (f1).
def evaluate(model_name,train,test): evaluator = MulticlassClassificationEvaluator(metricName=’f1') paramGrid = ParamGridBuilder().build() crossval = CrossValidator(estimator=model_name,\ evaluator=evaluator, \ estimatorParamMaps=paramGrid,\ numFolds=3) cvModel = crossval.fit(train) cvModel_metrics = cvModel.avgMetrics transformed_data = cvModel.transform(test) test_metrics = evaluator.evaluate(transformed_data) return (cvModel_metrics, test_metrics)
Finally, the performance of the five baseline models are as shown in the following code snippet. As we can see, the f1 scores for all of the models are unsatisfactory. We certainly need finer tuning to search for optimized hyper-parameters for these models!
However, if we were to choose from these baseline models, the cross validation models’ f1 score should be the criterion. In this case, the LinearSVC model will be the model of choice. (Note that the test score is worse than the score on the training data, indicating over-fitting).
model_names = [lr,svc,dtc,rfc,gbt]for model in model_names: a = evaluate(model,train,test) print(model,a)LogisticRegression ([0.6705811320138374], 0.6320191158900836)LinearSVC ([0.6765153189823112], 0.6320191158900836)DecisionTreeClassifier ([0.6382104034150818], 0.684376432033105)RandomForestClassifier ([0.666026954511646], 0.6682863679086347)GBTClassifier([0.6525712756381464], 0.6576482830385015)
To run the model on the full 12GB data on AWS, we’ll use basically the same codes, except the plotting portion done by Pandas is removed. There is one point that is worth noting though: following the Spark course’s instruction on configuring the cluster in the Nanodegree’s extracurricular material, I was able to run the codes; however, the session goes inactive after a while. This is likely due to insufficient spark driver memory. Therefore, we need to go with the advanced option in configuring a cluster and increase the driver memory.
This project provides an excellent opportunity to learn manipulating large datasets with Spark as well as AWS, which are among the highest-demand skills in the field of data science.
Topic-wise, predicting customer churn is a challenging and common problem that data scientists and analysts face in any customer-facing business. The analysis and modeling completed here is to highlight the process of a machine learning project using Spark. There is certainly large room to improve the model performance:
1) The aggregated behavior features are simply summations and averages. Weighted averages could be used to emphasize more recent behaviors. Diversity measurements can also be included. Finer hyper-parameter tuning are needed.
2) Since the dataset is longitudinal, we could potentially use survival models or time series models. Here are some articles on the these strategies for modeling customer churn.
|
[
{
"code": null,
"e": 547,
"s": 171,
"text": "Apache Spark has become arguably the most popular tool for analyzing large data sets. As my capstone project for Udacity’s Data Science Nanodegree, I’ll demonstrate the use of Spark for scalable data manipulation and machine learning. Context-wise, we use the user log data from a fictitious music streaming company, Sparkify, to predict which customers are at risk to churn."
},
{
"code": null,
"e": 937,
"s": 547,
"text": "The full data set is 12GB. we’ll first analyze a mini subset (128MB) and build classification models using Spark Dataframe, Spark SQL, and Spark ML APIs in local mode through the python interface API, PySpark. Then we’ll deploy a Spark cluster on AWS to run the models on the full 12GB of data. Hereafter, we assume that Spark and PySpark are installed (a tutorial for installing PySpark)."
},
{
"code": null,
"e": 1274,
"s": 937,
"text": "Before we are able to read csv, json, or xml data into Spark dataframes, a Spark session needs to be set up. A Spark session is a unified entry point for Spark applications from Spark 2.0. Note that prior to Spark 2.0, various Spark contexts are needed to interact with Spark’s different functionalities (a good Medium article on this)."
},
{
"code": null,
"e": 1396,
"s": 1274,
"text": "# Set up a SparkSessionfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName(\"capstone\").getOrCreate()"
},
{
"code": null,
"e": 1498,
"s": 1396,
"text": "# Load data and show basic data shapepath = \"mini_sparkify_event_data.json\"df = spark.read.json(path)"
},
{
"code": null,
"e": 1935,
"s": 1498,
"text": "Now that the mini Sparkify user log data set is in the Spark dataframe format, we can do some initial exploration to get familiar with the data. Spark dataframe and Spark SQL modules have methods such as the following: select(), filter(), where(), groupBy(), sort(), dropDuplicates(), count(), avg(), max(), min(). They also have Window functions that are useful for basic analysis (see documentation for syntax). To summarize the data:"
},
{
"code": null,
"e": 2131,
"s": 1935,
"text": "The dataset has 286500 rows and 18 columns.It spans the time period from 2018–9–30 to 2018–12–02.It records each event users did during this time period as a row.Column definitions are as follow:"
},
{
"code": null,
"e": 2175,
"s": 2131,
"text": "The dataset has 286500 rows and 18 columns."
},
{
"code": null,
"e": 2230,
"s": 2175,
"text": "It spans the time period from 2018–9–30 to 2018–12–02."
},
{
"code": null,
"e": 2296,
"s": 2230,
"text": "It records each event users did during this time period as a row."
},
{
"code": null,
"e": 2330,
"s": 2296,
"text": "Column definitions are as follow:"
},
{
"code": null,
"e": 3091,
"s": 2330,
"text": " -- artist (string): artist's name for a song -- auth (string): Logged Out | Cancelled | Guest | Logged In -- firstName (string): user's firstname -- gender (string): Female | Male -- itemInSession (long) : number of items in a session -- lastName (string): user's lastname -- length (double): a song's length in seconds -- level (string): paid | free -- location (string): city and state of the user -- method (string): HTTP method -- page (string): which page a user is on at an event -- registration (long): timestamp of user registration -- sessionId (long): the Id of the session a user is in at an event -- song (string): song name -- status(long): 307 | 404 | 200 -- ts (long): timestamp ateach event -- userAgent (string) : -- userId (string): user ID"
},
{
"code": null,
"e": 3414,
"s": 3091,
"text": "5. Some of these columns probably are not very useful for prediction, such as firstName, lastName, method, and userAgent. Categorical features need to be encoded, such as gender and level. Some numerical features will be useful for engineering aggregated behavior features, such as itemInSession, length, page visits, etc."
},
{
"code": null,
"e": 3601,
"s": 3414,
"text": "6. Class is imbalanced; we need to consider stratified sampling when we split training test data. We also should consider the f1 score over the accuracy for our model evaluation metrics."
},
{
"code": null,
"e": 3707,
"s": 3601,
"text": "7. For models, we will try Logistic Regression, Decision Tree, Random Forest, and Gradient Boosted Trees."
},
{
"code": null,
"e": 3780,
"s": 3707,
"text": "With these initial thoughts, let’s proceed with handling missing values."
},
{
"code": null,
"e": 3922,
"s": 3780,
"text": "The seaborn heatmap is a good way to show where missing values are located in the dataset and whether data is missing in some systematic way."
},
{
"code": null,
"e": 4055,
"s": 3922,
"text": "# Let's take a look at where the missing values are located.plt.figure(figsize=(18,6))sns.heatmap(df.toPandas().isnull(),cbar=False)"
},
{
"code": null,
"e": 4364,
"s": 4055,
"text": "Note (1): From the heatmap, we can see that firstName, lastName, gender, location, userAgent, and registration are missing at same rows. We can infer that these missing values come from users that are not registered. Usually, users who are not registered would not have a user ID. We’ll explore this further."
},
{
"code": null,
"e": 4423,
"s": 4364,
"text": "df.select(‘userid’).filter(‘registration is null’).show(3)"
},
{
"code": null,
"e": 4721,
"s": 4423,
"text": "It turns out that the userId column actually has missing values, but they are coded as just empty, instead of coded as a “NaN”. The number of such null values match the number of missing rows in registration. Since these records do not even have userId information, we’ll go ahead and delete them."
},
{
"code": null,
"e": 4903,
"s": 4721,
"text": "Note (2): Also, artist, length, and song are missing data at the same rows. These records do not have song-related information. We’ll explore what pages users are on for these rows."
},
{
"code": null,
"e": 5705,
"s": 4903,
"text": "print(df_pd[df_pd.artist.isnull()][‘page’].value_counts())print(df_pd[df_pd.artist.isnull()==False][‘page’].value_counts())Thumbs Up 12551Home 10082Add to Playlist 6526Add Friend 4277Roll Advert 3933Logout 3226Thumbs Down 2546Downgrade 2055Settings 1514Help 1454Upgrade 499About 495Save Settings 310Error 252Submit Upgrade 159Submit Downgrade 63Cancel 52Cancellation Confirmation 52Name: page, dtype: int64NextSong 228108Name: page, dtype: int64"
},
{
"code": null,
"e": 6044,
"s": 5705,
"text": "Based on intuition and domain knowledge, we decide not to include the columns for firstName, lastName, method, and userAgent in our first-pass modeling for now, since these variables probably do not affect our prediction. We also decide not to include artist, location, song, and status for now. This leaves us with the following columns:"
},
{
"code": null,
"e": 6454,
"s": 6044,
"text": " -- gender (string): Female | Male -- itemInSession (long) : number of items in a session -- length (double): a song's length in seconds -- level (string): paid | free -- page (string): which page a user is on at an event -- registration (long): timestamp of user registration -- sessionId (long): the Id of the session a user is in at an event -- ts (long): timestamp ateach event -- userId (string): user ID"
},
{
"code": null,
"e": 6540,
"s": 6454,
"text": "1) Define Churned User: We can see that there is approximately a 1:3 class imbalance."
},
{
"code": null,
"e": 7111,
"s": 6540,
"text": "flag_cancellation = udf(lambda x : 1 if x==\"Cancellation Confirmation\" else 0, IntegerType())df = df.withColumn(\"churn\",flag_cancellation(\"page\"))# Create the cross-sectional data that we’ll use in analysis and modellingw1 = Window.partitionBy(‘userId’)df_user = df.select(‘userId’,’churn’,’gender’,’level’) \\ .withColumn(‘churned_user’,Fsum(‘churn’).over(w1)) \\ .dropDuplicates([‘userId’]).drop(‘churn’)df_user.groupby(‘churned_user’).count().show()+------------+-----+|churned_user|count|+------------+-----+| 0| 173|| 1| 52|+------------+-----+"
},
{
"code": null,
"e": 7369,
"s": 7111,
"text": "2) Categorical features: For categorical features, we need to first label encoding (simply converting each value to a number). Depending on the machine learning models, we may need to further encode these numbers to dummy variables (e.g., one-hot encoding)."
},
{
"code": null,
"e": 7423,
"s": 7369,
"text": "In Spark, StringIndexer does the label encoding part:"
},
{
"code": null,
"e": 8089,
"s": 7423,
"text": "indexer = StringIndexer(inputCol=\"gender\",outputCol=\"genderIndex\")df_user = indexer.fit(df_user).transform(df_user)indexer = StringIndexer(inputCol=\"level\",outputCol=\"levelIndex\")df_user = indexer.fit(df_user).transform(df_user)df_user.show(3)+------+------+-----+------------+-----------+----------+|userId|gender|level|churned_user|genderIndex|levelIndex|+------+------+-----+------------+-----------+----------+|100010| F| free| 0| 1.0| 0.0||200002| M| free| 0| 0.0| 0.0|| 125| M| free| 1| 0.0| 0.0|+------+------+-----+------------+-----------+----------+only showing top 3 rows"
},
{
"code": null,
"e": 8344,
"s": 8089,
"text": "Let’s take a look at how gender and level are related to churn. By looking at the simple statistics, it seems that a larger percentage of male users tend to churn than female users and that a larger percentage of paid users tend to churn than free users."
},
{
"code": null,
"e": 8860,
"s": 8344,
"text": "df_user.groupby(‘genderIndex’).avg(‘churned_user’).show()+-----------+-------------------+|genderIndex| avg(churned_user)|+-----------+-------------------+| 0.0| 0.2644628099173554|| 1.0|0.19230769230769232|+-----------+-------------------+df_user.groupby('churned_user').avg('levelIndex').show()+------------+-------------------+|churned_user| avg(levelIndex)|+------------+-------------------+| 0|0.23121387283236994|| 1|0.15384615384615385|+------------+-------------------+"
},
{
"code": null,
"e": 9022,
"s": 8860,
"text": "Since we will utilize Logistic Regression and SVM classifier, we will need to convert label encoding to dummy variables. OneHotEncoderEstimator() does this part:"
},
{
"code": null,
"e": 9529,
"s": 9022,
"text": "encoder = OneHotEncoderEstimator(inputCols=[“genderIndex”, “levelIndex”], outputCols=[“genderVector”, “levelVector”])model = encoder.fit(df_user)df_user = model.transform(df_user)df_user.select('genderVector','levelVector').show(3)+------+-------------+-------------+|userId| genderVector| levelVector|+------+-------------+-------------+|100010| (1,[],[])|(1,[0],[1.0])||200002|(1,[0],[1.0])|(1,[0],[1.0])|| 125|(1,[0],[1.0])|(1,[0],[1.0])|+------+-------------+-------------+only showing top 3 rows"
},
{
"code": null,
"e": 9710,
"s": 9529,
"text": "The output columns of OneHotEncoderEstimator() is not the same as sklearn’s output. Instead of binary values, it gives this sparse vector format as shown in the above code snippet."
},
{
"code": null,
"e": 9861,
"s": 9710,
"text": "3) General activity aggregates: Based on the columns for sessionId, song, artist, length, and registration, we generate aggregated features including:"
},
{
"code": null,
"e": 9924,
"s": 9861,
"text": "numSessions (number of sessions a user had during this period)"
},
{
"code": null,
"e": 9980,
"s": 9924,
"text": "numSongs (number of different songs a user listened to)"
},
{
"code": null,
"e": 10040,
"s": 9980,
"text": "numArtists (number of different artists a user listened to)"
},
{
"code": null,
"e": 10099,
"s": 10040,
"text": "playTime (total time of playing songs measured in seconds)"
},
{
"code": null,
"e": 10151,
"s": 10099,
"text": "activeDays (number of days since a user registered)"
},
{
"code": null,
"e": 10335,
"s": 10151,
"text": "4) Page visits aggregates: Based on the page column, we generate aggregated page visit behavior features that count how many times a user visited each type of pages during the period."
},
{
"code": null,
"e": 10745,
"s": 10335,
"text": "w2 = Window.partitionBy('userId','page')columns = [str(row.page) for row in df.select('page')\\ .dropDuplicates().sort('page').collect()]df_pageVisits = df.select('userId','page')\\ .withColumn('pageVisits',count('userId').over(w2))\\ .groupby('userId')\\ .pivot('page',columns)\\ .mean('pageVisits')df_pageVisits = df_pageVisits.na.fill(0).drop(['Cancel','Cancellation Confirmation'],axis=1)"
},
{
"code": null,
"e": 10969,
"s": 10745,
"text": "5) Check for multicollinearity: Tree-based models would not be affected by multicollinearity, but, since we are also testing linear models (logistic regression and svm), we’ll go ahead and remove highly correlated features."
},
{
"code": null,
"e": 11202,
"s": 10969,
"text": "6) Vector Assembling and Feature Scaling: In Spark, machine learning models require features to be a vector type. The VectorAssembler() method converts all the feature columns into one vector, as shown in the following code snippet."
},
{
"code": null,
"e": 11580,
"s": 11202,
"text": "# Vector Assemblercols = df_inuse.drop('userID','churned_user').columnsassembler=VectorAssembler(inputCols=cols,outputCol='feature_vector')df_inuse=assembler.transform(df_inuse).select('userId','churned_user','feature_vector')df_inuse.take(1)[Row(userId='100010', churned_user=0, feature_vector=SparseVector(13, {0: 1.0, 2: 52.0, 6: 2.0, 7: 7.0, 8: 11.4259, 9: 1.0, 12: 1.0}))]"
},
{
"code": null,
"e": 11613,
"s": 11580,
"text": "The scaled data looks like this:"
},
{
"code": null,
"e": 11871,
"s": 11613,
"text": "df_inuse_scaled.take(1)[Row(userId='100010', label=0, feature_vector=SparseVector(13, {0: 1.0, 2: 52.0, 6: 2.0, 7: 7.0, 8: 11.4259, 9: 1.0, 12: 1.0}), features=SparseVector(13, {0: 0.3205, 2: 2.413, 6: 0.7817, 7: 0.4779, 8: 0.3488, 9: 2.0013, 12: 2.4356}))]"
},
{
"code": null,
"e": 11917,
"s": 11871,
"text": "7) Split data into training and testing sets:"
},
{
"code": null,
"e": 12054,
"s": 11917,
"text": "ratio = 0.8train = df_inuse_scaled.sampleBy(‘churned_user’,fractions={0:ratio,1:ratio}, seed = 42)test = df_inuse_scaled.subtract(train)"
},
{
"code": null,
"e": 12205,
"s": 12054,
"text": "We will compare five baseline models: Logistic Regression, Linear SVM Classifier, Decision Tree, Random Forests, and Gradient Boosted Tree Classifier."
},
{
"code": null,
"e": 12350,
"s": 12205,
"text": "# initiate the modelslr = LogisticRegression()svc = LinearSVC()dtc = DecisionTreeClassifier()rfc = RandomForestClassifier()gbt = GBTClassifier()"
},
{
"code": null,
"e": 12562,
"s": 12350,
"text": "The ParaGridBuilder() class can be used to construct a grid of hyper-parameters to search over. However, since the purpose here is to show Spark’s ML methods, we will not do an in-depth tuning of the model here."
},
{
"code": null,
"e": 12921,
"s": 12562,
"text": "# this line will keep the default hyper-parameters of a modelparamGrid = ParamGridBuilder().build()# to search over more parameters, we can use the ,,addGrid() method, for example:paramGrid = ParamGridBuilder()\\ .addGrid(lr.regParam, [0.1, 0.01]) \\ .addGrid(lr.fitIntercept, [False, True])\\ .addGrid(lr.elasticNetParam, [0.0, 0.5, 1.0])\\ .build()"
},
{
"code": null,
"e": 13059,
"s": 12921,
"text": "We’ll define an evaluation function to run through all five classification models and output their cross validation average metrics (f1)."
},
{
"code": null,
"e": 13525,
"s": 13059,
"text": "def evaluate(model_name,train,test): evaluator = MulticlassClassificationEvaluator(metricName=’f1') paramGrid = ParamGridBuilder().build() crossval = CrossValidator(estimator=model_name,\\ evaluator=evaluator, \\ estimatorParamMaps=paramGrid,\\ numFolds=3) cvModel = crossval.fit(train) cvModel_metrics = cvModel.avgMetrics transformed_data = cvModel.transform(test) test_metrics = evaluator.evaluate(transformed_data) return (cvModel_metrics, test_metrics)"
},
{
"code": null,
"e": 13783,
"s": 13525,
"text": "Finally, the performance of the five baseline models are as shown in the following code snippet. As we can see, the f1 scores for all of the models are unsatisfactory. We certainly need finer tuning to search for optimized hyper-parameters for these models!"
},
{
"code": null,
"e": 14065,
"s": 13783,
"text": "However, if we were to choose from these baseline models, the cross validation models’ f1 score should be the criterion. In this case, the LinearSVC model will be the model of choice. (Note that the test score is worse than the score on the training data, indicating over-fitting)."
},
{
"code": null,
"e": 14469,
"s": 14065,
"text": "model_names = [lr,svc,dtc,rfc,gbt]for model in model_names: a = evaluate(model,train,test) print(model,a)LogisticRegression ([0.6705811320138374], 0.6320191158900836)LinearSVC ([0.6765153189823112], 0.6320191158900836)DecisionTreeClassifier ([0.6382104034150818], 0.684376432033105)RandomForestClassifier ([0.666026954511646], 0.6682863679086347)GBTClassifier([0.6525712756381464], 0.6576482830385015)"
},
{
"code": null,
"e": 15011,
"s": 14469,
"text": "To run the model on the full 12GB data on AWS, we’ll use basically the same codes, except the plotting portion done by Pandas is removed. There is one point that is worth noting though: following the Spark course’s instruction on configuring the cluster in the Nanodegree’s extracurricular material, I was able to run the codes; however, the session goes inactive after a while. This is likely due to insufficient spark driver memory. Therefore, we need to go with the advanced option in configuring a cluster and increase the driver memory."
},
{
"code": null,
"e": 15194,
"s": 15011,
"text": "This project provides an excellent opportunity to learn manipulating large datasets with Spark as well as AWS, which are among the highest-demand skills in the field of data science."
},
{
"code": null,
"e": 15516,
"s": 15194,
"text": "Topic-wise, predicting customer churn is a challenging and common problem that data scientists and analysts face in any customer-facing business. The analysis and modeling completed here is to highlight the process of a machine learning project using Spark. There is certainly large room to improve the model performance:"
},
{
"code": null,
"e": 15742,
"s": 15516,
"text": "1) The aggregated behavior features are simply summations and averages. Weighted averages could be used to emphasize more recent behaviors. Diversity measurements can also be included. Finer hyper-parameter tuning are needed."
}
] |
VBA - Instr
|
The InStr Function returns the first occurrence of one string within another string. The search happens from the left to the right.
InStr([start,]string1,string2[,compare])
Start − An optional parameter. Specifies the starting position for the search. The search begins at the first position from the left to the right.
Start − An optional parameter. Specifies the starting position for the search. The search begins at the first position from the left to the right.
String1 − A required parameter. String to be searched.
String1 − A required parameter. String to be searched.
String2 − A required parameter. String against which String1 is searched.
String2 − A required parameter. String against which String1 is searched.
Compare − An optional parameter. Specifies the string comparison to be used. It can take the following mentioned values.
0 = vbBinaryCompare - Performs Binary Comparison (Default)
1 = vbTextCompare - Performs Text Comparison
Compare − An optional parameter. Specifies the string comparison to be used. It can take the following mentioned values.
0 = vbBinaryCompare - Performs Binary Comparison (Default)
0 = vbBinaryCompare - Performs Binary Comparison (Default)
1 = vbTextCompare - Performs Text Comparison
1 = vbTextCompare - Performs Text Comparison
Add a button and add the following function.
Private Sub Constant_demo_Click()
Dim Var As Variant
Var = "Microsoft VBScript"
MsgBox ("Line 1 : " & InStr(1, Var, "s"))
MsgBox ("Line 2 : " & InStr(7, Var, "s"))
MsgBox ("Line 3 : " & InStr(1, Var, "f", 1))
MsgBox ("Line 4 : " & InStr(1, Var, "t", 0))
MsgBox ("Line 5 : " & InStr(1, Var, "i"))
MsgBox ("Line 6 : " & InStr(7, Var, "i"))
MsgBox ("Line 7 : " & InStr(Var, "VB"))
End Sub
When you execute the above function, it produces the following output.
Line 1 : 6
Line 2 : 0
Line 3 : 8
Line 4 : 9
Line 5 : 2
Line 6 : 16
Line 7 : 11
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2067,
"s": 1935,
"text": "The InStr Function returns the first occurrence of one string within another string. The search happens from the left to the right."
},
{
"code": null,
"e": 2109,
"s": 2067,
"text": "InStr([start,]string1,string2[,compare])\n"
},
{
"code": null,
"e": 2256,
"s": 2109,
"text": "Start − An optional parameter. Specifies the starting position for the search. The search begins at the first position from the left to the right."
},
{
"code": null,
"e": 2403,
"s": 2256,
"text": "Start − An optional parameter. Specifies the starting position for the search. The search begins at the first position from the left to the right."
},
{
"code": null,
"e": 2458,
"s": 2403,
"text": "String1 − A required parameter. String to be searched."
},
{
"code": null,
"e": 2513,
"s": 2458,
"text": "String1 − A required parameter. String to be searched."
},
{
"code": null,
"e": 2587,
"s": 2513,
"text": "String2 − A required parameter. String against which String1 is searched."
},
{
"code": null,
"e": 2661,
"s": 2587,
"text": "String2 − A required parameter. String against which String1 is searched."
},
{
"code": null,
"e": 2889,
"s": 2661,
"text": "Compare − An optional parameter. Specifies the string comparison to be used. It can take the following mentioned values.\n\n0 = vbBinaryCompare - Performs Binary Comparison (Default)\n1 = vbTextCompare - Performs Text Comparison\n\n"
},
{
"code": null,
"e": 3010,
"s": 2889,
"text": "Compare − An optional parameter. Specifies the string comparison to be used. It can take the following mentioned values."
},
{
"code": null,
"e": 3069,
"s": 3010,
"text": "0 = vbBinaryCompare - Performs Binary Comparison (Default)"
},
{
"code": null,
"e": 3128,
"s": 3069,
"text": "0 = vbBinaryCompare - Performs Binary Comparison (Default)"
},
{
"code": null,
"e": 3173,
"s": 3128,
"text": "1 = vbTextCompare - Performs Text Comparison"
},
{
"code": null,
"e": 3218,
"s": 3173,
"text": "1 = vbTextCompare - Performs Text Comparison"
},
{
"code": null,
"e": 3263,
"s": 3218,
"text": "Add a button and add the following function."
},
{
"code": null,
"e": 3687,
"s": 3263,
"text": "Private Sub Constant_demo_Click() \n Dim Var As Variant \n Var = \"Microsoft VBScript\" \n MsgBox (\"Line 1 : \" & InStr(1, Var, \"s\")) \n MsgBox (\"Line 2 : \" & InStr(7, Var, \"s\")) \n MsgBox (\"Line 3 : \" & InStr(1, Var, \"f\", 1)) \n MsgBox (\"Line 4 : \" & InStr(1, Var, \"t\", 0)) \n MsgBox (\"Line 5 : \" & InStr(1, Var, \"i\")) \n MsgBox (\"Line 6 : \" & InStr(7, Var, \"i\")) \n MsgBox (\"Line 7 : \" & InStr(Var, \"VB\")) \nEnd Sub "
},
{
"code": null,
"e": 3758,
"s": 3687,
"text": "When you execute the above function, it produces the following output."
},
{
"code": null,
"e": 3838,
"s": 3758,
"text": "Line 1 : 6\nLine 2 : 0\nLine 3 : 8\nLine 4 : 9\nLine 5 : 2\nLine 6 : 16\nLine 7 : 11\n"
},
{
"code": null,
"e": 3872,
"s": 3838,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3887,
"s": 3872,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3920,
"s": 3887,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3935,
"s": 3920,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3970,
"s": 3935,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3988,
"s": 3970,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 4021,
"s": 3988,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4039,
"s": 4021,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 4072,
"s": 4039,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4087,
"s": 4072,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4123,
"s": 4087,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 4151,
"s": 4123,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4158,
"s": 4151,
"text": " Print"
},
{
"code": null,
"e": 4169,
"s": 4158,
"text": " Add Notes"
}
] |
C++ Program to Concatenate Two Strings
|
A string is a one dimensional character array that is terminated by a null character. Concatenation of two strings is the joining of them to form a new string. For example.
String 1: Mangoes are
String 2: tasty
Concatenation of 2 strings: Mangoes are tasty
A program to concatenate two strings is given as follows.
Live Demo
#include <iostream>
using namespace std;
int main() {
char str1[100] = "Hi...";
char str2[100] = "How are you";
int i,j;
cout<<"String 1: "<<str1<<endl;
cout<<"String 2: "<<str2<<endl;
for(i = 0; str1[i] != '\0'; ++i);
j=0;
while(str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';
cout<<"String after concatenation: "<<str1;
return 0;
}
String 1: Hi...
String 2: How are you
String after concatenation: Hi...How are you
In the above program, there are two strings str1 and str2. A for loop is used to reach the end of str1. At the end of the for loop, i contains the index of the null value in the str1. The following code snippet demonstrates this.
for(i = 0; str1[i] != '\0'; ++i);
A while loop is used to transfer the value of str2 to str1. Variable j starts from 0 and copies the character in str2 into str1 at the position pointed by i. This loop runs till value of str2[j] is not null. This is demonstrated as follows.
j=0;
while(str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
After the strings are concatenated in str1, null is added to the end. Then the concatenated string is displayed. The code snippet for this is as follows −
str1[i] = '\0';
cout<<"String after concatenation: "<<str1;
|
[
{
"code": null,
"e": 1235,
"s": 1062,
"text": "A string is a one dimensional character array that is terminated by a null character. Concatenation of two strings is the joining of them to form a new string. For example."
},
{
"code": null,
"e": 1319,
"s": 1235,
"text": "String 1: Mangoes are\nString 2: tasty\nConcatenation of 2 strings: Mangoes are tasty"
},
{
"code": null,
"e": 1377,
"s": 1319,
"text": "A program to concatenate two strings is given as follows."
},
{
"code": null,
"e": 1388,
"s": 1377,
"text": " Live Demo"
},
{
"code": null,
"e": 1794,
"s": 1388,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n char str1[100] = \"Hi...\";\n char str2[100] = \"How are you\";\n int i,j;\n cout<<\"String 1: \"<<str1<<endl;\n cout<<\"String 2: \"<<str2<<endl;\n for(i = 0; str1[i] != '\\0'; ++i);\n j=0;\n while(str2[j] != '\\0') {\n str1[i] = str2[j];\n i++;\n j++;\n }\n str1[i] = '\\0';\n cout<<\"String after concatenation: \"<<str1;\n return 0;\n}"
},
{
"code": null,
"e": 1877,
"s": 1794,
"text": "String 1: Hi...\nString 2: How are you\nString after concatenation: Hi...How are you"
},
{
"code": null,
"e": 2107,
"s": 1877,
"text": "In the above program, there are two strings str1 and str2. A for loop is used to reach the end of str1. At the end of the for loop, i contains the index of the null value in the str1. The following code snippet demonstrates this."
},
{
"code": null,
"e": 2141,
"s": 2107,
"text": "for(i = 0; str1[i] != '\\0'; ++i);"
},
{
"code": null,
"e": 2382,
"s": 2141,
"text": "A while loop is used to transfer the value of str2 to str1. Variable j starts from 0 and copies the character in str2 into str1 at the position pointed by i. This loop runs till value of str2[j] is not null. This is demonstrated as follows."
},
{
"code": null,
"e": 2452,
"s": 2382,
"text": "j=0;\nwhile(str2[j] != '\\0') {\n str1[i] = str2[j];\n i++;\n j++;\n}"
},
{
"code": null,
"e": 2607,
"s": 2452,
"text": "After the strings are concatenated in str1, null is added to the end. Then the concatenated string is displayed. The code snippet for this is as follows −"
},
{
"code": null,
"e": 2667,
"s": 2607,
"text": "str1[i] = '\\0';\ncout<<\"String after concatenation: \"<<str1;"
}
] |
K Means Clustering Without Libraries | by Rob LeCheminant | Towards Data Science
|
Kmeans is a widely used clustering tool for analyzing and classifying data. Often times, however, I suspect, it is not fully understood what is happening under the hood. This isn’t necessarily a bad thing if you understand what the end product conveys, but learning what happens by building the algorithm from scratch can certainly lead to a deeper understanding of the reasoning behind it.
I want to start out by emphasizing that the internet is an excellent place for coders and engineers. Answers and resources are widely available and merely a Google search away. To pretend I figured all of this out on my own would be silly. I readily acknowledge that there are times that it takes reading through others’ work on algorithms to understand how to approach it better. The beauty of code is that it can be written in many different ways, each emphasizing a slightly different quality. Utilize that in your learning.
Now that I’ve touched on that point, let’s dive in!
K Means Clustering is, in it’s simplest form, an algorithm that finds close relationships in clusters of data and puts them into groups for easier classification.
What you see here is an algorithm sorting different points of data into groups or segments based on a specific quality... proximity (or closeness) to a center point.
Most often, Scikit-Learn’s algorithm for KMeans, which looks something like this:
from sklearn.cluster import KMeanskm = KMeans( n_clusters=3, init='random', n_init=10, max_iter=300, random_state=42 )y_km = km.fit_predict(X)
You may not understand the parts super well, but it’s fairly simple in its approach. What it basically does is it says we want 3 clusters, start with 10 iterations (or run-throughs, each one refining the clusters and positions), initialization for the 3 center points is random, maximum iterations is 300, and random state just means every time we run it, it will be the same. We then run the prediction. More can be read here on the different parameters that can be used.
So, how do we go about creating this code from scratch... especially if we’re not sure what’s going on? Let’s figure it out!
The first step is to think through and describe what is happening. First of all, this article does an excellent job describing each step. In summary, we plot k number of points (also called centroids) on a scatter plot, usually random, and find the data closest to those points. We then recalculate the average distance from the data to the centroids and the centroid position over and over until there are clear groups of data surrounding each of those k centroids.
Have I lost you yet? Hopefully not. Let’s walk through each process to see what is happening:
The first step is we need to decide how many clusters we want to segment the data into. There is a method to this, but for simplicity’s sake, we’ll say that we’ll use 3 clusters, or, k = 3. The code looks something like this:
k = 3clusters = {}for i in range(k):clusters[i] = []
That look you see above just creates 3 empty clusters. It looks like this...
{0: [], 1: [], 2: []}
Simple enough, right?
We then set up the centroids in a similar fashion, but this time we use the data we are using. In my case, I’m using the Boston housing dataset. X, in this case, is an array of two points of data I’ve chosen from the dataset.
for i in range(k): centroids[i] = X[i]
Next, we need to find the distance from each point of data to the centroid. The concept is simple enough, but this next chunk is a little confusing to look at initially. I recommend googling and reading through different parts of this to get a better idea of what is going on. For example, if you were to google “np.linalg.norm” you would find this page describing what it is and what it does.
for data in X: euc_dist = [] for j in range(k): euc_dist.append(np.linalg.norm(data - centroids[j])) clusters[euc_dist.index(min(euc_dist))].append(data)
After we have initialized the centroids and clusters, we want to recalculate both of those values! Why? Because they are somewhat randomly initialized so we need to slowly move them toward the most ideal way that the data is naturally segmented (if at all, but that’s another discussion).
I have two functions written that do just that. Let’s take a look:
def recalculate_clusters(X, centroids, k): """ Recalculates the clusters """ # Initiate empty clusters clusters = {} # Set the range for value of k (number of centroids) for i in range(k): clusters[i] = [] for data in X: euc_dist = [] for j in range(k): euc_dist.append(np.linalg.norm(data - centroids[j])) # Append the cluster of data to the dictionary clusters[euc_dist.index(min(euc_dist))].append(data) return clustersdef recalculate_centroids(centroids, clusters, k): """ Recalculates the centroid position based on the plot """ for i in range(k): centroids[i] = np.average(clusters[i], axis=0) return centroids
I hope you recognized some of the same code in those two functions. Pay close attention to the different parts and pieces. One of the best ways to learn something is to dissect what is going on inside. Again, I challenge you to google individual parts of this code. It’s like taking apart the radio and putting it back together. Bring out that inner engineer!
From there we would put together a plotting function that plots each cluster and assigns it a different color. It’s like feeding the data through a sorting machine that color codes the different pieces based on where they go. What comes out looks something like this:
We can see that the data is clearly segmented into different parts, though they aren’t distributed fairly well. That’s because this is merely the first iteration of the data! I should also mention that this shape doesn’t fully lend itself to clustering, which is a lesson in and of itself of both the strengths and weaknesses of an algorithm.
So what do we do when we want to have better distribution among the clusters?... Recalculate, recalculate, recalculate! In this case, if we ran it, say, 10 times, it would subsequently look like this:
There’s a little bit better distribution now, isn’t there. What we see is 3 different unsupervised classifications in the data. The algorithm is telling us that these 3 colors may mean something in the data that is at least worth looking into. Note that it doesn’t mean that it actually is significant. That’s the funny thing about data. Computers work hard to augment our abilities to find relationships in the data, but ultimately it is up to us to decide what those relationships (if any) mean. Your data science job is likely to stick around for at least a little while. Phew!
One of the more interesting sidenotes... when deciding how many iterations to run (or in other words, how many times you want to recalculate), you can put together what’s often called an “elbow plot” to see where the iterations really start to lose their ability to differentiate. Mine looked something like this:
You can see that around 3 to 4 repetitions is where it started losing that momentum that each iteration gave in adjusting those clusters and centroids. It’s a nice check on how many calculations you really want to run. After all, if this is for a company, time is money and resources are generally finite! Of course, this is pretty low-level stuff, so it’s not a big deal, but it’s always a conversation worth having with yourself and/or a team on projects and analyses.
To view the entire (in progress) notebook, navigate over to my GitHub repository, here! You’ll see some of the details in how I went about not only choosing a dataset but in initially exploring the dataset as well.
I hope you enjoyed this overview of K Means Clustering! Please note, I’m still fairly new to the world of data science, so I am absolutely open to the correction of ideas and methods detailed in this article. After all, I feel learning is continual and I don’t mind at all improving my abilities to explain and utilize these methods. We all learn through mistakes! Please reach out if you do feel there are any errors or points of clarity needed. Thank you!
|
[
{
"code": null,
"e": 563,
"s": 172,
"text": "Kmeans is a widely used clustering tool for analyzing and classifying data. Often times, however, I suspect, it is not fully understood what is happening under the hood. This isn’t necessarily a bad thing if you understand what the end product conveys, but learning what happens by building the algorithm from scratch can certainly lead to a deeper understanding of the reasoning behind it."
},
{
"code": null,
"e": 1091,
"s": 563,
"text": "I want to start out by emphasizing that the internet is an excellent place for coders and engineers. Answers and resources are widely available and merely a Google search away. To pretend I figured all of this out on my own would be silly. I readily acknowledge that there are times that it takes reading through others’ work on algorithms to understand how to approach it better. The beauty of code is that it can be written in many different ways, each emphasizing a slightly different quality. Utilize that in your learning."
},
{
"code": null,
"e": 1143,
"s": 1091,
"text": "Now that I’ve touched on that point, let’s dive in!"
},
{
"code": null,
"e": 1306,
"s": 1143,
"text": "K Means Clustering is, in it’s simplest form, an algorithm that finds close relationships in clusters of data and puts them into groups for easier classification."
},
{
"code": null,
"e": 1472,
"s": 1306,
"text": "What you see here is an algorithm sorting different points of data into groups or segments based on a specific quality... proximity (or closeness) to a center point."
},
{
"code": null,
"e": 1554,
"s": 1472,
"text": "Most often, Scikit-Learn’s algorithm for KMeans, which looks something like this:"
},
{
"code": null,
"e": 1721,
"s": 1554,
"text": "from sklearn.cluster import KMeanskm = KMeans( n_clusters=3, init='random', n_init=10, max_iter=300, random_state=42 )y_km = km.fit_predict(X)"
},
{
"code": null,
"e": 2194,
"s": 1721,
"text": "You may not understand the parts super well, but it’s fairly simple in its approach. What it basically does is it says we want 3 clusters, start with 10 iterations (or run-throughs, each one refining the clusters and positions), initialization for the 3 center points is random, maximum iterations is 300, and random state just means every time we run it, it will be the same. We then run the prediction. More can be read here on the different parameters that can be used."
},
{
"code": null,
"e": 2319,
"s": 2194,
"text": "So, how do we go about creating this code from scratch... especially if we’re not sure what’s going on? Let’s figure it out!"
},
{
"code": null,
"e": 2786,
"s": 2319,
"text": "The first step is to think through and describe what is happening. First of all, this article does an excellent job describing each step. In summary, we plot k number of points (also called centroids) on a scatter plot, usually random, and find the data closest to those points. We then recalculate the average distance from the data to the centroids and the centroid position over and over until there are clear groups of data surrounding each of those k centroids."
},
{
"code": null,
"e": 2880,
"s": 2786,
"text": "Have I lost you yet? Hopefully not. Let’s walk through each process to see what is happening:"
},
{
"code": null,
"e": 3106,
"s": 2880,
"text": "The first step is we need to decide how many clusters we want to segment the data into. There is a method to this, but for simplicity’s sake, we’ll say that we’ll use 3 clusters, or, k = 3. The code looks something like this:"
},
{
"code": null,
"e": 3159,
"s": 3106,
"text": "k = 3clusters = {}for i in range(k):clusters[i] = []"
},
{
"code": null,
"e": 3236,
"s": 3159,
"text": "That look you see above just creates 3 empty clusters. It looks like this..."
},
{
"code": null,
"e": 3258,
"s": 3236,
"text": "{0: [], 1: [], 2: []}"
},
{
"code": null,
"e": 3280,
"s": 3258,
"text": "Simple enough, right?"
},
{
"code": null,
"e": 3506,
"s": 3280,
"text": "We then set up the centroids in a similar fashion, but this time we use the data we are using. In my case, I’m using the Boston housing dataset. X, in this case, is an array of two points of data I’ve chosen from the dataset."
},
{
"code": null,
"e": 3548,
"s": 3506,
"text": "for i in range(k): centroids[i] = X[i]"
},
{
"code": null,
"e": 3942,
"s": 3548,
"text": "Next, we need to find the distance from each point of data to the centroid. The concept is simple enough, but this next chunk is a little confusing to look at initially. I recommend googling and reading through different parts of this to get a better idea of what is going on. For example, if you were to google “np.linalg.norm” you would find this page describing what it is and what it does."
},
{
"code": null,
"e": 4112,
"s": 3942,
"text": "for data in X: euc_dist = [] for j in range(k): euc_dist.append(np.linalg.norm(data - centroids[j])) clusters[euc_dist.index(min(euc_dist))].append(data)"
},
{
"code": null,
"e": 4401,
"s": 4112,
"text": "After we have initialized the centroids and clusters, we want to recalculate both of those values! Why? Because they are somewhat randomly initialized so we need to slowly move them toward the most ideal way that the data is naturally segmented (if at all, but that’s another discussion)."
},
{
"code": null,
"e": 4468,
"s": 4401,
"text": "I have two functions written that do just that. Let’s take a look:"
},
{
"code": null,
"e": 5168,
"s": 4468,
"text": "def recalculate_clusters(X, centroids, k): \"\"\" Recalculates the clusters \"\"\" # Initiate empty clusters clusters = {} # Set the range for value of k (number of centroids) for i in range(k): clusters[i] = [] for data in X: euc_dist = [] for j in range(k): euc_dist.append(np.linalg.norm(data - centroids[j])) # Append the cluster of data to the dictionary clusters[euc_dist.index(min(euc_dist))].append(data) return clustersdef recalculate_centroids(centroids, clusters, k): \"\"\" Recalculates the centroid position based on the plot \"\"\" for i in range(k): centroids[i] = np.average(clusters[i], axis=0) return centroids"
},
{
"code": null,
"e": 5528,
"s": 5168,
"text": "I hope you recognized some of the same code in those two functions. Pay close attention to the different parts and pieces. One of the best ways to learn something is to dissect what is going on inside. Again, I challenge you to google individual parts of this code. It’s like taking apart the radio and putting it back together. Bring out that inner engineer!"
},
{
"code": null,
"e": 5796,
"s": 5528,
"text": "From there we would put together a plotting function that plots each cluster and assigns it a different color. It’s like feeding the data through a sorting machine that color codes the different pieces based on where they go. What comes out looks something like this:"
},
{
"code": null,
"e": 6139,
"s": 5796,
"text": "We can see that the data is clearly segmented into different parts, though they aren’t distributed fairly well. That’s because this is merely the first iteration of the data! I should also mention that this shape doesn’t fully lend itself to clustering, which is a lesson in and of itself of both the strengths and weaknesses of an algorithm."
},
{
"code": null,
"e": 6340,
"s": 6139,
"text": "So what do we do when we want to have better distribution among the clusters?... Recalculate, recalculate, recalculate! In this case, if we ran it, say, 10 times, it would subsequently look like this:"
},
{
"code": null,
"e": 6921,
"s": 6340,
"text": "There’s a little bit better distribution now, isn’t there. What we see is 3 different unsupervised classifications in the data. The algorithm is telling us that these 3 colors may mean something in the data that is at least worth looking into. Note that it doesn’t mean that it actually is significant. That’s the funny thing about data. Computers work hard to augment our abilities to find relationships in the data, but ultimately it is up to us to decide what those relationships (if any) mean. Your data science job is likely to stick around for at least a little while. Phew!"
},
{
"code": null,
"e": 7235,
"s": 6921,
"text": "One of the more interesting sidenotes... when deciding how many iterations to run (or in other words, how many times you want to recalculate), you can put together what’s often called an “elbow plot” to see where the iterations really start to lose their ability to differentiate. Mine looked something like this:"
},
{
"code": null,
"e": 7706,
"s": 7235,
"text": "You can see that around 3 to 4 repetitions is where it started losing that momentum that each iteration gave in adjusting those clusters and centroids. It’s a nice check on how many calculations you really want to run. After all, if this is for a company, time is money and resources are generally finite! Of course, this is pretty low-level stuff, so it’s not a big deal, but it’s always a conversation worth having with yourself and/or a team on projects and analyses."
},
{
"code": null,
"e": 7921,
"s": 7706,
"text": "To view the entire (in progress) notebook, navigate over to my GitHub repository, here! You’ll see some of the details in how I went about not only choosing a dataset but in initially exploring the dataset as well."
}
] |
CRM - Building Value for Customers
|
“Your relationship with the customers, not the customer’s relationship with your product, is the conduit through which the value flows.”
− Bill Quiseng, Customer Service Speaker and Blogger
The terms cost and value are often misunderstood as same, though these two terms are poles apart in their meaning. The cost of a product is nothing but the amount a customer pays to the seller to avail the product. When the customer says a product is “value for money”, it means the product delivers what it is supposed to in the exchange of a reasonable cost.
The value of a product or a service is nothing but the customer’s perception of the ratio of benefits received to the sacrifices made while purchasing a product or service from a business.
Value = Benefits / Sacrifices
Value is directly affected by customer’s perception, which can be altered positively by increasing benefits and decreasing sacrifices.
The customers make the following sacrifices when it comes to buying from a business −
This is the time taken to physically arrive at the business outlet or to search for the required product online, and to compare various similar products with respect to specifications and costs. It also includes waiting time to avail the required product and extended time when a business delivers a product with incorrect specification.
It is the primary concern. Apart from the cost of product or services the business offers, it may be the cost of Value Addition Tax (VAT), surcharge, interest on the late payments, etc. Similarly, there can be discounts for first few customers or under any other schemes.
The customers invest energy to get ready, step out for shopping, to drive or to travel from home to the business outlet. The energy also includes fuel consumption for transport.
Purchasing a product can be a very hectic, frustrating, and at times annoying experience for the customers. Right from planning what and when to purchase, budgeting, getting ready and stepping out of the house for shopping, being through the crowd on the road, arriving at the store, dealing with the business staff who don’t possess adequate knowledge of the product or schemes, paying exaggerated prices, carrying heavy packages, exchanging faulty or outdated products, etc. At times the customers need to travel in bad weather only to find out that the last piece of the required product was just picked by some other customer.
While buying the product, the customer has to deal with various risks such as financial (regarding product price), physical (possibility of the product turning harmful to customer’s body), and performance (possibility of the product failure).
There are various sources of creating value for the products the customer purchases −
It involves the following −
Being innovative in product design.
Following rigorous quality while manufacturing.
Keeping a golden mean of price and quality.
Handling efficient supply chains.
Cooperating closely among suppliers.
Satisfying customers’ expectations.
It involves the engagement of the business in continuous product innovation for improvement, large share of investment in product research and development along with the risk. The business creates value by providing the best quality product or service solution in adequate time.
Customer intimacy is generated and developed by understanding customer requirements, offering customized products, creating best outlet ambience, the warmth and interest of business staff while communicating with customers, and putting the customer first.
The marketing force of a business combines various components of marketing mix (Product, Price, Place, and Promotion) together to create the best value for the customer. In case of services, as they are intangible unlike products, three more components are considered namely process, physical evidence, and people.
The marketing mix is planned such that is strikes a good balance among customer and business entities, to satisfy the both.
12 Lectures
2 hours
Richa Maheshwari
15 Lectures
2 hours
Prof. Paul Cline, Ed.D
10 Lectures
35 mins
Venu Gopal
69 Lectures
6 hours
Ivan Chagas
28 Lectures
2 hours
Rob Cubbon
15 Lectures
1 hours
The Click Reader
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2071,
"s": 1934,
"text": "“Your relationship with the customers, not the customer’s relationship with your product, is the conduit through which the value flows.”"
},
{
"code": null,
"e": 2124,
"s": 2071,
"text": "− Bill Quiseng, Customer Service Speaker and Blogger"
},
{
"code": null,
"e": 2485,
"s": 2124,
"text": "The terms cost and value are often misunderstood as same, though these two terms are poles apart in their meaning. The cost of a product is nothing but the amount a customer pays to the seller to avail the product. When the customer says a product is “value for money”, it means the product delivers what it is supposed to in the exchange of a reasonable cost."
},
{
"code": null,
"e": 2674,
"s": 2485,
"text": "The value of a product or a service is nothing but the customer’s perception of the ratio of benefits received to the sacrifices made while purchasing a product or service from a business."
},
{
"code": null,
"e": 2705,
"s": 2674,
"text": "Value = Benefits / Sacrifices\n"
},
{
"code": null,
"e": 2840,
"s": 2705,
"text": "Value is directly affected by customer’s perception, which can be altered positively by increasing benefits and decreasing sacrifices."
},
{
"code": null,
"e": 2926,
"s": 2840,
"text": "The customers make the following sacrifices when it comes to buying from a business −"
},
{
"code": null,
"e": 3264,
"s": 2926,
"text": "This is the time taken to physically arrive at the business outlet or to search for the required product online, and to compare various similar products with respect to specifications and costs. It also includes waiting time to avail the required product and extended time when a business delivers a product with incorrect specification."
},
{
"code": null,
"e": 3536,
"s": 3264,
"text": "It is the primary concern. Apart from the cost of product or services the business offers, it may be the cost of Value Addition Tax (VAT), surcharge, interest on the late payments, etc. Similarly, there can be discounts for first few customers or under any other schemes."
},
{
"code": null,
"e": 3714,
"s": 3536,
"text": "The customers invest energy to get ready, step out for shopping, to drive or to travel from home to the business outlet. The energy also includes fuel consumption for transport."
},
{
"code": null,
"e": 4345,
"s": 3714,
"text": "Purchasing a product can be a very hectic, frustrating, and at times annoying experience for the customers. Right from planning what and when to purchase, budgeting, getting ready and stepping out of the house for shopping, being through the crowd on the road, arriving at the store, dealing with the business staff who don’t possess adequate knowledge of the product or schemes, paying exaggerated prices, carrying heavy packages, exchanging faulty or outdated products, etc. At times the customers need to travel in bad weather only to find out that the last piece of the required product was just picked by some other customer."
},
{
"code": null,
"e": 4588,
"s": 4345,
"text": "While buying the product, the customer has to deal with various risks such as financial (regarding product price), physical (possibility of the product turning harmful to customer’s body), and performance (possibility of the product failure)."
},
{
"code": null,
"e": 4674,
"s": 4588,
"text": "There are various sources of creating value for the products the customer purchases −"
},
{
"code": null,
"e": 4702,
"s": 4674,
"text": "It involves the following −"
},
{
"code": null,
"e": 4738,
"s": 4702,
"text": "Being innovative in product design."
},
{
"code": null,
"e": 4786,
"s": 4738,
"text": "Following rigorous quality while manufacturing."
},
{
"code": null,
"e": 4830,
"s": 4786,
"text": "Keeping a golden mean of price and quality."
},
{
"code": null,
"e": 4864,
"s": 4830,
"text": "Handling efficient supply chains."
},
{
"code": null,
"e": 4901,
"s": 4864,
"text": "Cooperating closely among suppliers."
},
{
"code": null,
"e": 4937,
"s": 4901,
"text": "Satisfying customers’ expectations."
},
{
"code": null,
"e": 5216,
"s": 4937,
"text": "It involves the engagement of the business in continuous product innovation for improvement, large share of investment in product research and development along with the risk. The business creates value by providing the best quality product or service solution in adequate time."
},
{
"code": null,
"e": 5472,
"s": 5216,
"text": "Customer intimacy is generated and developed by understanding customer requirements, offering customized products, creating best outlet ambience, the warmth and interest of business staff while communicating with customers, and putting the customer first."
},
{
"code": null,
"e": 5787,
"s": 5472,
"text": "The marketing force of a business combines various components of marketing mix (Product, Price, Place, and Promotion) together to create the best value for the customer. In case of services, as they are intangible unlike products, three more components are considered namely process, physical evidence, and people."
},
{
"code": null,
"e": 5911,
"s": 5787,
"text": "The marketing mix is planned such that is strikes a good balance among customer and business entities, to satisfy the both."
},
{
"code": null,
"e": 5944,
"s": 5911,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5962,
"s": 5944,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 5995,
"s": 5962,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6019,
"s": 5995,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 6051,
"s": 6019,
"text": "\n 10 Lectures \n 35 mins\n"
},
{
"code": null,
"e": 6063,
"s": 6051,
"text": " Venu Gopal"
},
{
"code": null,
"e": 6096,
"s": 6063,
"text": "\n 69 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6109,
"s": 6096,
"text": " Ivan Chagas"
},
{
"code": null,
"e": 6142,
"s": 6109,
"text": "\n 28 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6154,
"s": 6142,
"text": " Rob Cubbon"
},
{
"code": null,
"e": 6187,
"s": 6154,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6205,
"s": 6187,
"text": " The Click Reader"
},
{
"code": null,
"e": 6212,
"s": 6205,
"text": " Print"
},
{
"code": null,
"e": 6223,
"s": 6212,
"text": " Add Notes"
}
] |
AWK - Relational Operators
|
AWK supports the following relational operators −
It is represented by ==. It returns true if both operands are equal, otherwise it returns false. The following example demonstrates this −
awk 'BEGIN { a = 10; b = 10; if (a == b) print "a == b" }'
On executing this code, you get the following result −
a == b
It is represented by !=. It returns true if both operands are unequal, otherwise it returns false.
[jerry]$ awk 'BEGIN { a = 10; b = 20; if (a != b) print "a != b" }'
On executing this code, you get the following result −
a != b
It is represented by <. It returns true if the left-side operand is less than the right-side operand; otherwise it returns false.
[jerry]$ awk 'BEGIN { a = 10; b = 20; if (a < b) print "a < b" }'
On executing this code, you get the following result −
a < b
It is represented by <=. It returns true if the left-side operand is less than or equal to the right-side operand; otherwise it returns false.
[jerry]$ awk 'BEGIN { a = 10; b = 10; if (a <= b) print "a <= b" }'
On executing this code, you get the following result −
a <= b
It is represented by >. It returns true if the left-side operand is greater than the right-side operand, otherwise it returns false.
[jerry]$ awk 'BEGIN { a = 10; b = 20; if (b > a ) print "b > a" }'
On executing the above code, you get the following result −
b > a
It is represented by >=. It returns true if the left-side operand is greater than or equal to the right-side operand; otherwise it returns false.
b >= a
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1907,
"s": 1857,
"text": "AWK supports the following relational operators −"
},
{
"code": null,
"e": 2046,
"s": 1907,
"text": "It is represented by ==. It returns true if both operands are equal, otherwise it returns false. The following example demonstrates this −"
},
{
"code": null,
"e": 2105,
"s": 2046,
"text": "awk 'BEGIN { a = 10; b = 10; if (a == b) print \"a == b\" }'"
},
{
"code": null,
"e": 2160,
"s": 2105,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2168,
"s": 2160,
"text": "a == b\n"
},
{
"code": null,
"e": 2267,
"s": 2168,
"text": "It is represented by !=. It returns true if both operands are unequal, otherwise it returns false."
},
{
"code": null,
"e": 2335,
"s": 2267,
"text": "[jerry]$ awk 'BEGIN { a = 10; b = 20; if (a != b) print \"a != b\" }'"
},
{
"code": null,
"e": 2390,
"s": 2335,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2398,
"s": 2390,
"text": "a != b\n"
},
{
"code": null,
"e": 2528,
"s": 2398,
"text": "It is represented by <. It returns true if the left-side operand is less than the right-side operand; otherwise it returns false."
},
{
"code": null,
"e": 2595,
"s": 2528,
"text": "[jerry]$ awk 'BEGIN { a = 10; b = 20; if (a < b) print \"a < b\" }'"
},
{
"code": null,
"e": 2650,
"s": 2595,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2657,
"s": 2650,
"text": "a < b\n"
},
{
"code": null,
"e": 2800,
"s": 2657,
"text": "It is represented by <=. It returns true if the left-side operand is less than or equal to the right-side operand; otherwise it returns false."
},
{
"code": null,
"e": 2868,
"s": 2800,
"text": "[jerry]$ awk 'BEGIN { a = 10; b = 10; if (a <= b) print \"a <= b\" }'"
},
{
"code": null,
"e": 2923,
"s": 2868,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2931,
"s": 2923,
"text": "a <= b\n"
},
{
"code": null,
"e": 3064,
"s": 2931,
"text": "It is represented by >. It returns true if the left-side operand is greater than the right-side operand, otherwise it returns false."
},
{
"code": null,
"e": 3131,
"s": 3064,
"text": "[jerry]$ awk 'BEGIN { a = 10; b = 20; if (b > a ) print \"b > a\" }'"
},
{
"code": null,
"e": 3191,
"s": 3131,
"text": "On executing the above code, you get the following result −"
},
{
"code": null,
"e": 3198,
"s": 3191,
"text": "b > a\n"
},
{
"code": null,
"e": 3344,
"s": 3198,
"text": "It is represented by >=. It returns true if the left-side operand is greater than or equal to the right-side operand; otherwise it returns false."
},
{
"code": null,
"e": 3352,
"s": 3344,
"text": "b >= a\n"
},
{
"code": null,
"e": 3359,
"s": 3352,
"text": " Print"
},
{
"code": null,
"e": 3370,
"s": 3359,
"text": " Add Notes"
}
] |
Python Tricks: Flattening Lists. Are you still iterating through for... | by Louis Chan | Towards Data Science
|
Welcome to a series of short posts each with handy Python tricks that can help you become a better Python programmer. In this blog, we will look into how to flatten lists.
We have all dealt with lists of lists or even worse: lists of nested lists.
Theoretically, we can peel the list layer by layer like an onion:
l = [0, 1, 2, [3, 4, 5, [6, 7, 8]]]from collections import Iterabledef unwrap(l): flat_list = [] for item in l: if isinstance(item, Iterable): flat_list.extend(item) else: flat_list.append(item) return flat_listl = unwrap(l)# [0, 1, 2, 3, 4, 5, [6, 7, 8]]l = unwrap(l)# [0, 1, 2, 3, 4, 5, 6, 7, 8]
That would also mean that we need to run unwrap for however many nested layers there is.
Is there a more efficient way to flatten nested lists?
itertools is one of Python’s standard libraries that provide handy functions that create iterators for efficient looping. Among them is a function called chain which creates a chain object that concatenates a list of iterables. A chain object can be understood as an iterator that iterates through each of the iterables. Hence, you would need to cast it into a list explicitly if you would need more than just an iterator.
from itertools import chainl = [[0, 1], [2, 3]]list(chain(*l))# [0, 1, 2, 3]list(chain.from_iterable(l))# [0, 1, 2, 3]
However, chain also comes with a couple of limitations: it concatenates a list of iterables but does not unwrap further, and it also requires all elements to be iterables:
from itertools import chainl = [[0, 1], [2, 3, [4, 5]]]list(chain(*l))# [0, 1, 2, 3, [4, 5]]l = [0, 1, [2, 3, [4, 5]]]list(chain(*l))# TypeError: 'int' object is not iterable
As an alternative to itertools.chain, pandas has a flatten function under pandas.core.common. Similar to itertools.chain, flatten returns a generator instead of a list. There are some differences in the implementation and the perks of generators vs iterators. While we will cover that in the future, a simple one-liner for their differences is that generators are iterators that use a yield statement and can only be read once.
from pandas.core.common import flattenl = [0, 1, [2, 3, [4, 5]]]list(flatten(l))# [0, 1, 2, 3, 4, 5]
From the example above, we can see that flatten also takes care of nested lists unlike chain!
So which one should we use?
It depends.
If you have a list of nested lists, either refactor the code to avoid creating that beast or using flatten to completely flatten it in one go.
If you have a list of lists, then chain would suffice. After all, chain is also faster than flatten
l = [[0, 1], [2, 3, 4], [5, 6, 7, 8]]%timeit list(chain(l))# 236 ns ± 7.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)%timeit list(flatten(l))# 5.13 μs ± 164 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
That’s about it for this blog post! I hope you have found this useful. If you are interested in other Python tricks, I have put together a list of these short blogs for you:
Python Tricks: How to Check Table Merging with Pandas
Python Tricks: Simplifying If Statements & Boolean Evaluation
Python Tricks: Check Multiple Variables against Single Value
If you want to read more about Python, Data Science, or Machine Learning, you may want to check out these posts:
7 Easy Ways for Improving Your Data Science Workflow
Efficient Conditional Logic on Pandas DataFrames
Memory Efficiency of Common Python Data Structures
Parallelism with Python
Essential Jupyter Extension for Data Science Set Up
Efficient Root Searching Algorithms in Python
If you would like to read more about how to apply machine learning to trading & investing, here are some other posts that may be of interest:
Genetic Algorithm for Trading Strategy Optimization in Python
Genetic Algorithm — Stop Overfitting Trading Strategies
ANN Recommendation System for Stock Selection
|
[
{
"code": null,
"e": 219,
"s": 47,
"text": "Welcome to a series of short posts each with handy Python tricks that can help you become a better Python programmer. In this blog, we will look into how to flatten lists."
},
{
"code": null,
"e": 295,
"s": 219,
"text": "We have all dealt with lists of lists or even worse: lists of nested lists."
},
{
"code": null,
"e": 361,
"s": 295,
"text": "Theoretically, we can peel the list layer by layer like an onion:"
},
{
"code": null,
"e": 704,
"s": 361,
"text": "l = [0, 1, 2, [3, 4, 5, [6, 7, 8]]]from collections import Iterabledef unwrap(l): flat_list = [] for item in l: if isinstance(item, Iterable): flat_list.extend(item) else: flat_list.append(item) return flat_listl = unwrap(l)# [0, 1, 2, 3, 4, 5, [6, 7, 8]]l = unwrap(l)# [0, 1, 2, 3, 4, 5, 6, 7, 8]"
},
{
"code": null,
"e": 793,
"s": 704,
"text": "That would also mean that we need to run unwrap for however many nested layers there is."
},
{
"code": null,
"e": 848,
"s": 793,
"text": "Is there a more efficient way to flatten nested lists?"
},
{
"code": null,
"e": 1271,
"s": 848,
"text": "itertools is one of Python’s standard libraries that provide handy functions that create iterators for efficient looping. Among them is a function called chain which creates a chain object that concatenates a list of iterables. A chain object can be understood as an iterator that iterates through each of the iterables. Hence, you would need to cast it into a list explicitly if you would need more than just an iterator."
},
{
"code": null,
"e": 1390,
"s": 1271,
"text": "from itertools import chainl = [[0, 1], [2, 3]]list(chain(*l))# [0, 1, 2, 3]list(chain.from_iterable(l))# [0, 1, 2, 3]"
},
{
"code": null,
"e": 1562,
"s": 1390,
"text": "However, chain also comes with a couple of limitations: it concatenates a list of iterables but does not unwrap further, and it also requires all elements to be iterables:"
},
{
"code": null,
"e": 1737,
"s": 1562,
"text": "from itertools import chainl = [[0, 1], [2, 3, [4, 5]]]list(chain(*l))# [0, 1, 2, 3, [4, 5]]l = [0, 1, [2, 3, [4, 5]]]list(chain(*l))# TypeError: 'int' object is not iterable"
},
{
"code": null,
"e": 2165,
"s": 1737,
"text": "As an alternative to itertools.chain, pandas has a flatten function under pandas.core.common. Similar to itertools.chain, flatten returns a generator instead of a list. There are some differences in the implementation and the perks of generators vs iterators. While we will cover that in the future, a simple one-liner for their differences is that generators are iterators that use a yield statement and can only be read once."
},
{
"code": null,
"e": 2266,
"s": 2165,
"text": "from pandas.core.common import flattenl = [0, 1, [2, 3, [4, 5]]]list(flatten(l))# [0, 1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 2360,
"s": 2266,
"text": "From the example above, we can see that flatten also takes care of nested lists unlike chain!"
},
{
"code": null,
"e": 2388,
"s": 2360,
"text": "So which one should we use?"
},
{
"code": null,
"e": 2400,
"s": 2388,
"text": "It depends."
},
{
"code": null,
"e": 2543,
"s": 2400,
"text": "If you have a list of nested lists, either refactor the code to avoid creating that beast or using flatten to completely flatten it in one go."
},
{
"code": null,
"e": 2643,
"s": 2543,
"text": "If you have a list of lists, then chain would suffice. After all, chain is also faster than flatten"
},
{
"code": null,
"e": 2878,
"s": 2643,
"text": "l = [[0, 1], [2, 3, 4], [5, 6, 7, 8]]%timeit list(chain(l))# 236 ns ± 7.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)%timeit list(flatten(l))# 5.13 μs ± 164 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)"
},
{
"code": null,
"e": 3052,
"s": 2878,
"text": "That’s about it for this blog post! I hope you have found this useful. If you are interested in other Python tricks, I have put together a list of these short blogs for you:"
},
{
"code": null,
"e": 3106,
"s": 3052,
"text": "Python Tricks: How to Check Table Merging with Pandas"
},
{
"code": null,
"e": 3168,
"s": 3106,
"text": "Python Tricks: Simplifying If Statements & Boolean Evaluation"
},
{
"code": null,
"e": 3229,
"s": 3168,
"text": "Python Tricks: Check Multiple Variables against Single Value"
},
{
"code": null,
"e": 3342,
"s": 3229,
"text": "If you want to read more about Python, Data Science, or Machine Learning, you may want to check out these posts:"
},
{
"code": null,
"e": 3395,
"s": 3342,
"text": "7 Easy Ways for Improving Your Data Science Workflow"
},
{
"code": null,
"e": 3444,
"s": 3395,
"text": "Efficient Conditional Logic on Pandas DataFrames"
},
{
"code": null,
"e": 3495,
"s": 3444,
"text": "Memory Efficiency of Common Python Data Structures"
},
{
"code": null,
"e": 3519,
"s": 3495,
"text": "Parallelism with Python"
},
{
"code": null,
"e": 3571,
"s": 3519,
"text": "Essential Jupyter Extension for Data Science Set Up"
},
{
"code": null,
"e": 3617,
"s": 3571,
"text": "Efficient Root Searching Algorithms in Python"
},
{
"code": null,
"e": 3759,
"s": 3617,
"text": "If you would like to read more about how to apply machine learning to trading & investing, here are some other posts that may be of interest:"
},
{
"code": null,
"e": 3821,
"s": 3759,
"text": "Genetic Algorithm for Trading Strategy Optimization in Python"
},
{
"code": null,
"e": 3877,
"s": 3821,
"text": "Genetic Algorithm — Stop Overfitting Trading Strategies"
}
] |
Perl | Displaying Variable Values with a Debugger - GeeksforGeeks
|
21 Nov, 2019
Debugger in Perl comes up with various features thus making the debugging process quite simple and effective. One of the most powerful features of Perl Debugger is displaying variable values. This feature allows us to display the value of any variable at any time. There are two basic commands to implement this feature:
‘X’ command
‘V’ command
The ‘X’ command displays the value of the variables in the current package. It returns the value of the variable which is specified in the command. If the X command is called by itself, then it returns a list of all the user-defined variables along with system-defined variables of the current package.
Syntax:
X variablename;
Consider the example given below to have a closer look at the functionality of the command:
DB<5> X geek;
The above statement will return the value of geek variable as $geek = ‘0’. The variable name in the output will always be prefixed by a ‘$‘ symbol.
Generally the current package is main, thus, in that case, the use of this command will return the values of the variables in the main package only.
Note: Never prefix the variable name with a $ sign while using it with ‘X’ command. The debugger returns nothing in the output if it encounters this symbol.
The 'X' command can also be used to display the values of array variables. As you specified earlier the variable name similarly you have to specify the array variable name. Consider the statement given below:
DB<6> X array1;
This statement will return the values of the array variable in the following format:
@array1 = (
0 'Geeks'
1 'for'
2 'Geeks'
)
Sometimes there are conditions that your code may have similar names of scalar variables and array variables. In that, the 'X' command returns the values of both the variables. Consider the example given below:
DB<9> X geeks;
Consider that there are two variables with the name geeks; one being a scalar variable and other being an array variable, then the output will be something like this:
$geeks = '0'
@geeks = (
0 'Geeks'
1 'for'
2 'Geeks'
)
The 'V' command is similar to 'X' command except that it allows you to print the values of variables of any package. If we specify only the package name it returns the values of all the variables in that package else if the name of the variable is specified it returns the value of the specified variable.
Syntax:
V packagename variablename;
Consider the example given below to have a closer look at the functionality of the command:
DB<5> V mygeek geek;
The above statement will return the value of the variable geek of the package mygeek as $mygeek = ‘0’.If no variable name is specified and only the package name is specified, then it returns all the variables of the specified package along with their values. Consider the example given below:
DB<5> V mygeek;
This statement will return all the variables of the package mygeek.
Note:The rest of the functionality of the 'V' command is same to the 'X' command, whether its displaying the value of array variable or displaying the values of variable with similar name.
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Polymorphism in OOPs
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | Data Types
Perl | length() Function
Perl | Arrays (push, pop, shift, unshift)
Perl | sleep() Function
Perl | Multidimensional Hashes
Perl | Boolean Values
Perl | Automatic String to Number Conversion or Casting
|
[
{
"code": null,
"e": 24210,
"s": 24182,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 24531,
"s": 24210,
"text": "Debugger in Perl comes up with various features thus making the debugging process quite simple and effective. One of the most powerful features of Perl Debugger is displaying variable values. This feature allows us to display the value of any variable at any time. There are two basic commands to implement this feature:"
},
{
"code": null,
"e": 24543,
"s": 24531,
"text": "‘X’ command"
},
{
"code": null,
"e": 24555,
"s": 24543,
"text": "‘V’ command"
},
{
"code": null,
"e": 24858,
"s": 24555,
"text": "The ‘X’ command displays the value of the variables in the current package. It returns the value of the variable which is specified in the command. If the X command is called by itself, then it returns a list of all the user-defined variables along with system-defined variables of the current package."
},
{
"code": null,
"e": 24866,
"s": 24858,
"text": "Syntax:"
},
{
"code": null,
"e": 24882,
"s": 24866,
"text": "X variablename;"
},
{
"code": null,
"e": 24974,
"s": 24882,
"text": "Consider the example given below to have a closer look at the functionality of the command:"
},
{
"code": null,
"e": 24988,
"s": 24974,
"text": "DB<5> X geek;"
},
{
"code": null,
"e": 25136,
"s": 24988,
"text": "The above statement will return the value of geek variable as $geek = ‘0’. The variable name in the output will always be prefixed by a ‘$‘ symbol."
},
{
"code": null,
"e": 25285,
"s": 25136,
"text": "Generally the current package is main, thus, in that case, the use of this command will return the values of the variables in the main package only."
},
{
"code": null,
"e": 25442,
"s": 25285,
"text": "Note: Never prefix the variable name with a $ sign while using it with ‘X’ command. The debugger returns nothing in the output if it encounters this symbol."
},
{
"code": null,
"e": 25651,
"s": 25442,
"text": "The 'X' command can also be used to display the values of array variables. As you specified earlier the variable name similarly you have to specify the array variable name. Consider the statement given below:"
},
{
"code": null,
"e": 25668,
"s": 25651,
"text": " DB<6> X array1;"
},
{
"code": null,
"e": 25753,
"s": 25668,
"text": "This statement will return the values of the array variable in the following format:"
},
{
"code": null,
"e": 25818,
"s": 25753,
"text": "@array1 = (\n\n 0 'Geeks'\n\n 1 'for'\n\n 2 'Geeks'\n\n)\n"
},
{
"code": null,
"e": 26029,
"s": 25818,
"text": "Sometimes there are conditions that your code may have similar names of scalar variables and array variables. In that, the 'X' command returns the values of both the variables. Consider the example given below:"
},
{
"code": null,
"e": 26044,
"s": 26029,
"text": "DB<9> X geeks;"
},
{
"code": null,
"e": 26211,
"s": 26044,
"text": "Consider that there are two variables with the name geeks; one being a scalar variable and other being an array variable, then the output will be something like this:"
},
{
"code": null,
"e": 26288,
"s": 26211,
"text": "$geeks = '0'\n@geeks = (\n\n 0 'Geeks'\n\n 1 'for'\n\n 2 'Geeks'\n\n)\n"
},
{
"code": null,
"e": 26594,
"s": 26288,
"text": "The 'V' command is similar to 'X' command except that it allows you to print the values of variables of any package. If we specify only the package name it returns the values of all the variables in that package else if the name of the variable is specified it returns the value of the specified variable."
},
{
"code": null,
"e": 26602,
"s": 26594,
"text": "Syntax:"
},
{
"code": null,
"e": 26630,
"s": 26602,
"text": "V packagename variablename;"
},
{
"code": null,
"e": 26722,
"s": 26630,
"text": "Consider the example given below to have a closer look at the functionality of the command:"
},
{
"code": null,
"e": 26743,
"s": 26722,
"text": "DB<5> V mygeek geek;"
},
{
"code": null,
"e": 27036,
"s": 26743,
"text": "The above statement will return the value of the variable geek of the package mygeek as $mygeek = ‘0’.If no variable name is specified and only the package name is specified, then it returns all the variables of the specified package along with their values. Consider the example given below:"
},
{
"code": null,
"e": 27052,
"s": 27036,
"text": "DB<5> V mygeek;"
},
{
"code": null,
"e": 27120,
"s": 27052,
"text": "This statement will return all the variables of the package mygeek."
},
{
"code": null,
"e": 27309,
"s": 27120,
"text": "Note:The rest of the functionality of the 'V' command is same to the 'X' command, whether its displaying the value of array variable or displaying the values of variable with similar name."
},
{
"code": null,
"e": 27316,
"s": 27309,
"text": "Picked"
},
{
"code": null,
"e": 27321,
"s": 27316,
"text": "Perl"
},
{
"code": null,
"e": 27326,
"s": 27321,
"text": "Perl"
},
{
"code": null,
"e": 27424,
"s": 27326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27433,
"s": 27424,
"text": "Comments"
},
{
"code": null,
"e": 27446,
"s": 27433,
"text": "Old Comments"
},
{
"code": null,
"e": 27474,
"s": 27446,
"text": "Perl | Polymorphism in OOPs"
},
{
"code": null,
"e": 27488,
"s": 27474,
"text": "Perl | Arrays"
},
{
"code": null,
"e": 27529,
"s": 27488,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 27547,
"s": 27529,
"text": "Perl | Data Types"
},
{
"code": null,
"e": 27572,
"s": 27547,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 27614,
"s": 27572,
"text": "Perl | Arrays (push, pop, shift, unshift)"
},
{
"code": null,
"e": 27638,
"s": 27614,
"text": "Perl | sleep() Function"
},
{
"code": null,
"e": 27669,
"s": 27638,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 27691,
"s": 27669,
"text": "Perl | Boolean Values"
}
] |
Count ways to express a number as sum of consecutive numbers - GeeksforGeeks
|
03 Feb, 2022
Given an integer N, the task is to find the number of ways to represent this number as a sum of 2 or more consecutive natural numbers.
Examples:
Input: N = 15 Output: 3 Explanation: 15 can be represented as:
1 + 2 + 3 + 4 + 54 + 5 + 67 + 8
1 + 2 + 3 + 4 + 5
4 + 5 + 6
7 + 8
Input: N = 10 Output: 1
Approach: The idea is to represent N as a sequence of length L+1 as: N = a + (a+1) + (a+2) + .. + (a+L) => N = (L+1)*a + (L*(L+1))/2 => a = (N- L*(L+1)/2)/(L+1) We substitute the values of L starting from 1 till L*(L+1)/2 < N If we get ‘a’ as a natural number then the solution should be counted.
YouTubeGeeksforGeeks Practice25.5K subscribersCount of Sum of Consecutives | Recently asked questions in DE Shaw & Co. InterviewsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 53:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uKcvoXmfXZc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLM68oyaqFM7Q-sv3gA5xbzfgVkoQ0xDrW
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of ways to express// N as sum of consecutive numbers.#include <bits/stdc++.h>using namespace std; long int countConsecutive(long int N){ // constraint on values of L gives us the // time Complexity as O(N^0.5) long int count = 0; for (long int L = 1; L * (L + 1) < 2 * N; L++) { double a = (1.0 * N - (L * (L + 1)) / 2) / (L + 1); if (a - (int)a == 0.0) count++; } return count;} // Driver Codeint main(){ long int N = 15; cout << countConsecutive(N) << endl; N = 10; cout << countConsecutive(N) << endl; return 0;}
// A Java program to count number of ways// to express N as sum of consecutive numbers.public class SumConsecutiveNumber { // Utility method to compute number of ways // in which N can be represented as sum of // consecutive number static int countConsecutive(int N) { // constraint on values of L gives us the // time Complexity as O(N^0.5) int count = 0; for (int L = 1; L * (L + 1) < 2 * N; L++) { double a = (double)((1.0 * N - (L * (L + 1)) / 2) / (L + 1)); if (a - (int)a == 0.0) count++; } return count; } // Driver code to test above function public static void main(String[] args) { int N = 15; System.out.println(countConsecutive(N)); N = 10; System.out.println(countConsecutive(N)); }}// This code is contributed by Sumit Ghosh
# Python program to count number of ways to# express N as sum of consecutive numbers. def countConsecutive(N): # constraint on values of L gives us the # time Complexity as O(N ^ 0.5) count = 0 L = 1 while( L * (L + 1) < 2 * N): a = (1.0 * N - (L * (L + 1) ) / 2) / (L + 1) if (a - int(a) == 0.0): count += 1 L += 1 return count # Driver code N = 15print (countConsecutive(N))N = 10print (countConsecutive(N)) # This code is contributed by Sachin Bisht
// A C# program to count number of// ways to express N as sum of// consecutive numbers.using System; public class GFG { // Utility method to compute // number of ways in which N // can be represented as sum // of consecutive number static int countConsecutive(int N) { // constraint on values of L // gives us the time // Complexity as O(N^0.5) int count = 0; for (int L = 1; L * (L + 1) < 2 * N; L++) { double a = (double)((1.0 * N - (L * (L + 1)) / 2) / (L + 1)); if (a - (int)a == 0.0) count++; } return count; } // Driver code to test above // function public static void Main() { int N = 15; Console.WriteLine( countConsecutive(N)); N = 10; Console.Write( countConsecutive(N)); }} // This code is contributed by// nitin mittal.
<?php// PHP program to count number// of ways to express N as sum// of consecutive numbers. function countConsecutive($N){ // constraint on values // of L gives us the // time Complexity as O(N^0.5) $count = 0; for ($L = 1; $L * ($L + 1) < 2 * $N; $L++) { $a = (int)(1.0 * $N - ($L * (int)($L + 1)) / 2) / ($L + 1); if ($a - (int)$a == 0.0) $count++; } return $count;} // Driver Code$N = 15;echo countConsecutive($N), "\n";$N = 10;echo countConsecutive($N), "\n"; // This code is contributed by ajit?>
<script> // A Javascript program to count number of // ways to express N as sum of // consecutive numbers. // Utility method to compute // number of ways in which N // can be represented as sum // of consecutive number function countConsecutive(N) { // constraint on values of L // gives us the time // Complexity as O(N^0.5) let count = 0; for (let L = 1; L * (L + 1) < 2 * N; L++) { let a = ((1.0 * N-(L * (L + 1)) / 2) / (L + 1)); if (a - parseInt(a, 10) == 0.0) count++; } return count; } let N = 15; document.write(countConsecutive(N) + "</br>"); N = 10; document.write(countConsecutive(N)); </script>
3
1
Time Complexity: O(N^0.5)
This article is contributed by Pranav Marathe. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
nitin mittal
jit_t
rameshtravel07
snape_here
amartyaghoshgfg
Linkedin
Visa
Mathematical
Visa
Linkedin
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++
Program for factorial of a number
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
|
[
{
"code": null,
"e": 26643,
"s": 26615,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 26778,
"s": 26643,
"text": "Given an integer N, the task is to find the number of ways to represent this number as a sum of 2 or more consecutive natural numbers."
},
{
"code": null,
"e": 26790,
"s": 26778,
"text": "Examples: "
},
{
"code": null,
"e": 26855,
"s": 26790,
"text": "Input: N = 15 Output: 3 Explanation: 15 can be represented as: "
},
{
"code": null,
"e": 26887,
"s": 26855,
"text": "1 + 2 + 3 + 4 + 54 + 5 + 67 + 8"
},
{
"code": null,
"e": 26905,
"s": 26887,
"text": "1 + 2 + 3 + 4 + 5"
},
{
"code": null,
"e": 26915,
"s": 26905,
"text": "4 + 5 + 6"
},
{
"code": null,
"e": 26921,
"s": 26915,
"text": "7 + 8"
},
{
"code": null,
"e": 26947,
"s": 26921,
"text": "Input: N = 10 Output: 1 "
},
{
"code": null,
"e": 27249,
"s": 26951,
"text": "Approach: The idea is to represent N as a sequence of length L+1 as: N = a + (a+1) + (a+2) + .. + (a+L) => N = (L+1)*a + (L*(L+1))/2 => a = (N- L*(L+1)/2)/(L+1) We substitute the values of L starting from 1 till L*(L+1)/2 < N If we get ‘a’ as a natural number then the solution should be counted. "
},
{
"code": null,
"e": 28128,
"s": 27251,
"text": "YouTubeGeeksforGeeks Practice25.5K subscribersCount of Sum of Consecutives | Recently asked questions in DE Shaw & Co. InterviewsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 53:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=uKcvoXmfXZc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 28170,
"s": 28128,
"text": "?list=PLM68oyaqFM7Q-sv3gA5xbzfgVkoQ0xDrW "
},
{
"code": null,
"e": 28174,
"s": 28170,
"text": "C++"
},
{
"code": null,
"e": 28179,
"s": 28174,
"text": "Java"
},
{
"code": null,
"e": 28187,
"s": 28179,
"text": "Python3"
},
{
"code": null,
"e": 28190,
"s": 28187,
"text": "C#"
},
{
"code": null,
"e": 28194,
"s": 28190,
"text": "PHP"
},
{
"code": null,
"e": 28205,
"s": 28194,
"text": "Javascript"
},
{
"code": "// C++ program to count number of ways to express// N as sum of consecutive numbers.#include <bits/stdc++.h>using namespace std; long int countConsecutive(long int N){ // constraint on values of L gives us the // time Complexity as O(N^0.5) long int count = 0; for (long int L = 1; L * (L + 1) < 2 * N; L++) { double a = (1.0 * N - (L * (L + 1)) / 2) / (L + 1); if (a - (int)a == 0.0) count++; } return count;} // Driver Codeint main(){ long int N = 15; cout << countConsecutive(N) << endl; N = 10; cout << countConsecutive(N) << endl; return 0;}",
"e": 28810,
"s": 28205,
"text": null
},
{
"code": "// A Java program to count number of ways// to express N as sum of consecutive numbers.public class SumConsecutiveNumber { // Utility method to compute number of ways // in which N can be represented as sum of // consecutive number static int countConsecutive(int N) { // constraint on values of L gives us the // time Complexity as O(N^0.5) int count = 0; for (int L = 1; L * (L + 1) < 2 * N; L++) { double a = (double)((1.0 * N - (L * (L + 1)) / 2) / (L + 1)); if (a - (int)a == 0.0) count++; } return count; } // Driver code to test above function public static void main(String[] args) { int N = 15; System.out.println(countConsecutive(N)); N = 10; System.out.println(countConsecutive(N)); }}// This code is contributed by Sumit Ghosh",
"e": 29687,
"s": 28810,
"text": null
},
{
"code": "# Python program to count number of ways to# express N as sum of consecutive numbers. def countConsecutive(N): # constraint on values of L gives us the # time Complexity as O(N ^ 0.5) count = 0 L = 1 while( L * (L + 1) < 2 * N): a = (1.0 * N - (L * (L + 1) ) / 2) / (L + 1) if (a - int(a) == 0.0): count += 1 L += 1 return count # Driver code N = 15print (countConsecutive(N))N = 10print (countConsecutive(N)) # This code is contributed by Sachin Bisht",
"e": 30195,
"s": 29687,
"text": null
},
{
"code": "// A C# program to count number of// ways to express N as sum of// consecutive numbers.using System; public class GFG { // Utility method to compute // number of ways in which N // can be represented as sum // of consecutive number static int countConsecutive(int N) { // constraint on values of L // gives us the time // Complexity as O(N^0.5) int count = 0; for (int L = 1; L * (L + 1) < 2 * N; L++) { double a = (double)((1.0 * N - (L * (L + 1)) / 2) / (L + 1)); if (a - (int)a == 0.0) count++; } return count; } // Driver code to test above // function public static void Main() { int N = 15; Console.WriteLine( countConsecutive(N)); N = 10; Console.Write( countConsecutive(N)); }} // This code is contributed by// nitin mittal.",
"e": 31270,
"s": 30195,
"text": null
},
{
"code": "<?php// PHP program to count number// of ways to express N as sum// of consecutive numbers. function countConsecutive($N){ // constraint on values // of L gives us the // time Complexity as O(N^0.5) $count = 0; for ($L = 1; $L * ($L + 1) < 2 * $N; $L++) { $a = (int)(1.0 * $N - ($L * (int)($L + 1)) / 2) / ($L + 1); if ($a - (int)$a == 0.0) $count++; } return $count;} // Driver Code$N = 15;echo countConsecutive($N), \"\\n\";$N = 10;echo countConsecutive($N), \"\\n\"; // This code is contributed by ajit?>",
"e": 31841,
"s": 31270,
"text": null
},
{
"code": "<script> // A Javascript program to count number of // ways to express N as sum of // consecutive numbers. // Utility method to compute // number of ways in which N // can be represented as sum // of consecutive number function countConsecutive(N) { // constraint on values of L // gives us the time // Complexity as O(N^0.5) let count = 0; for (let L = 1; L * (L + 1) < 2 * N; L++) { let a = ((1.0 * N-(L * (L + 1)) / 2) / (L + 1)); if (a - parseInt(a, 10) == 0.0) count++; } return count; } let N = 15; document.write(countConsecutive(N) + \"</br>\"); N = 10; document.write(countConsecutive(N)); </script>",
"e": 32648,
"s": 31841,
"text": null
},
{
"code": null,
"e": 32655,
"s": 32651,
"text": "3\n1"
},
{
"code": null,
"e": 32685,
"s": 32659,
"text": "Time Complexity: O(N^0.5)"
},
{
"code": null,
"e": 33115,
"s": 32687,
"text": "This article is contributed by Pranav Marathe. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 33130,
"s": 33117,
"text": "nitin mittal"
},
{
"code": null,
"e": 33136,
"s": 33130,
"text": "jit_t"
},
{
"code": null,
"e": 33151,
"s": 33136,
"text": "rameshtravel07"
},
{
"code": null,
"e": 33162,
"s": 33151,
"text": "snape_here"
},
{
"code": null,
"e": 33178,
"s": 33162,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 33187,
"s": 33178,
"text": "Linkedin"
},
{
"code": null,
"e": 33192,
"s": 33187,
"text": "Visa"
},
{
"code": null,
"e": 33205,
"s": 33192,
"text": "Mathematical"
},
{
"code": null,
"e": 33210,
"s": 33205,
"text": "Visa"
},
{
"code": null,
"e": 33219,
"s": 33210,
"text": "Linkedin"
},
{
"code": null,
"e": 33232,
"s": 33219,
"text": "Mathematical"
},
{
"code": null,
"e": 33330,
"s": 33232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33354,
"s": 33330,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33397,
"s": 33354,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33411,
"s": 33397,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33453,
"s": 33411,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 33526,
"s": 33453,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 33548,
"s": 33526,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 33569,
"s": 33548,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 33603,
"s": 33569,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 33656,
"s": 33603,
"text": "Find minimum number of coins that make a given value"
}
] |
How to write a recursive function in Python?
|
A recursive function is a function that calls itself during its execution. This enables the function to repeat itself several times, outputting the result and the end of each iteration. Recursion has something to do with infinity.
Following is an example of recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 9 (denoted as 9!) is 1*2*3*4*5*6*7*8*9 = 362880.
def factorial(i):
if i == 1:
return 1
else:
return (i * factorial(i-1))
number = 9
print("The factorial of", number, "is", factorial(number))
The factorial of 9 is 362880
In the above program factorial() is a recursive functions as it calls itself. Each function call multiples the number with the factorial of number 1 until the number is equal to one.
For example to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
def Function(x):
if (x < 1):
return
else:
print( x,end = " ")
Function(x-1)
print(x,end = " ")
return
x = 5
Function(x)
5 4 3 2 1 1 2 3 4 5
|
[
{
"code": null,
"e": 1294,
"s": 1062,
"text": "A recursive function is a function that calls itself during its execution. This enables the function to repeat itself several times, outputting the result and the end of each iteration. Recursion has something to do with infinity. "
},
{
"code": null,
"e": 1377,
"s": 1294,
"text": "Following is an example of recursive function to find the factorial of an integer."
},
{
"code": null,
"e": 1458,
"s": 1377,
"text": "Factorial of a number is the product of all the integers from 1 to that number. "
},
{
"code": null,
"e": 1537,
"s": 1458,
"text": "For example, the factorial of 9 (denoted as 9!) is 1*2*3*4*5*6*7*8*9 = 362880."
},
{
"code": null,
"e": 1697,
"s": 1537,
"text": "def factorial(i):\n if i == 1:\n return 1\n else:\n return (i * factorial(i-1))\nnumber = 9\nprint(\"The factorial of\", number, \"is\", factorial(number))"
},
{
"code": null,
"e": 1726,
"s": 1697,
"text": "The factorial of 9 is 362880"
},
{
"code": null,
"e": 1909,
"s": 1726,
"text": "In the above program factorial() is a recursive functions as it calls itself. Each function call multiples the number with the factorial of number 1 until the number is equal to one."
},
{
"code": null,
"e": 2029,
"s": 1909,
"text": "For example to place two parallel mirrors facing each other. Any object in between them would be reflected recursively."
},
{
"code": null,
"e": 2185,
"s": 2029,
"text": "def Function(x):\n if (x < 1):\n return\n else:\n print( x,end = \" \")\n Function(x-1)\n print(x,end = \" \")\n return\nx = 5\nFunction(x)"
},
{
"code": null,
"e": 2205,
"s": 2185,
"text": "5 4 3 2 1 1 2 3 4 5"
}
] |
Latent Dirichlet Allocation: Intuition, math, implementation and visualisation with pyLDAvis | by Ioana | Towards Data Science
|
TL;DR — Latent Dirichlet Allocation (LDA, sometimes LDirA/LDiA) is one of the most popular and interpretable generative models for finding topics in text data. I’ve provided an example notebook based on web-scraped job description data. Although running LDA on a canonical dataset like 20Newsgroups would’ve provided clearer topics , it’s important to witness how difficult topic identification can be “in the wild”, and how you might not actually find clear topics — with unsupervised learning, you are never guaranteed to find an answer!
Acknowledgement: the greatest aid to my understanding was Louis Serrano’s two videos on LDA (2020). A lot of the intuition section is based on his explanation, and I would urge you to visit his video for a more thorough dissection.
Intuition
Maths
Implementation and visualisation
Let’s say that you have a collection of different news articles (your corpus of documents), and you suspect that there are several topics that come up frequently within said corpus — your goal is to find out what they are! To get there you make a few key assumptions:
The distributional hypothesis: Words that appear together frequently are likely to be close in meaning;
each topic is a mixture of different words (Fig 1.1);
each document is a mixture of different topics (Fig 1.2).
In Fig 1.1 you’ll notice that the topic “Health & Medicine” has various words associated with it to varying degrees (“cancer” is more strongly associated than “vascular” or “exercise”). Note that different words can be associated with different topics, as with the word “cardio”.
In Fig 1.2 you’ll see that a single document can pertain to multiple topics (as colour-coded on the left). Words like “injury” and “recovery” might also belong to multiple topics (hence why I’ve coloured them in more than one colour).
Now LDA is a generative model — it tries to determine the underlying mechanism that generates the articles and the topics. Think of it as if there’s a machine with particular settings that spits out articles, but we can’t see the machine’s settings, only what it produces. LDA creates a set of machines with different settings and selects the one that gives the best-fitting results (Serrano, 2020). Once the best one is found, we take a look at its “settings” and we deduce the topics from that.
So what are these settings?
First, we have something called the Dirichlet (pronounced like dee-reesh-lay) prior of the topics. This is a number that says how sparse or how mixed up our topics are. In L Serrano’s video (which I highly recommend!) he illustrates how visually you can think of this as a triangle (Fig 1.3) where the dots represent the documents and their position with respect to the corners (i.e. the topics) represents the how they’re related to each of the topics (2020). So a dot that is very close to the “Sports” vertex will be almost entirely about sport.
In the lefthand triangle the documents are fairly separated, most of them neatly tucked into their corners (this corresponds to a low Dirichlet prior, alpha<1); on the right they are in the middle and represent a more even mix of topics (a higher Dirichlet prior, alpha>1). Look at the document in Fig 1.2 and, given the mix of topics, have a think about where you think it would be placed in the triangle on the right (my answer is that it’d be the dot just above the one closest to the Sports corner).
Second, we have the Dirichlet prior of the terms (all the words in our vocabulary). This number (whose name is beta) has almost exactly the same function as alpha — except that it determines how the topics are distributed amongst the terms.
As we said before, the topics are assumed to be mixtures (more precisely, distributions) of different terms. In Fig 1.4 “Sports” is mostly drawn towards “injury”. “Health&Medicine” is torn between “cardio” and “injury” and has no association with the term “pray”.
But wait, our vocabulary doesn’t consist of just 3 words! You’re right! We could have a vocabulary of 4 words (as shown in Fig 1.5)! Trouble is that visualising a typical vocabulary of N words (where N could be 10'000) would require a generalised version of the triangle shape, but in N — 1 dimensions (the term for this is an n-1 simplex). This is where the visuals stop and we trust that the maths of higher dimensions will function as expected. This also applies to the topics — very often we’ll find ourselves with more than 3 topics.
An important clarification: in LDA we start with values of alpha and beta as hyperparameters, but these numbers only tell us whether our dots (documents / topics) are generally concentrated in the middle of their triangles or closer to the corners. The actual positions within the triangle (simplex) are guessed by the machine — the guesswork is not random, it’s heavily weighted by the Dirichlet priors.
So the machine creates the two Dirichlet distributions, distributes the documents and topics on them and then generates documents based on those distributions (Fig 1.6). So, how does the last step happen, the generation part?
Remember at the start we said that topics are seen as mixtures / distributions of words and documents as mixtures / distributions of topics? Going from left to right in Figure 1.7 we start with a document, somewhere in the triangle, torn between our 3 topics. If it’s near the “Sports” corner, this means that the document will be mostly about Sports, with some mentions of “Religion” and “Health&Medicine”. So we know the topic composition of the document → therefore we can estimate what words will come up. We will be sampling (i.e. randomly pulling out) words mostly from Sports, some from Health&Medicine and a very small amount from Religion (Fig 1.7). Here’s a question for you: looking at the triangle at the bottom of Fig 1.7, do you think word 2 will come up or not?
The answer is that it might: remember that topics are mixtures of words. You might be thinking that word 2 is very strongly related to the yellow (Religion) topic, and since this topic is very sparse in this document word 2 won’t come up as much. But remember that a. word 2 is also associated with the blue, Sports topic and b. the words are sample probabilistically, so every word has some non-zero chance of appearing.
The words in our final, generated document (on the right end of Fig 1.7) will be compared to the words in the original documents. We won’t get the same document, BUT when we compare a range of different LDA “machines” with a range of different distributions, we find that one of them was closer to generating the document than the others were and that’s the LDA model that we choose.
A normal statistical language model assumes that you can generate a document by sampling from a probability distribution over words, i.e. for each word in our vocabulary there is an associated probability of that word appearing.
LDA adds a layer of complexity over this arrangement. It assumes a list of topics, k. Each document m is a probability distribution over these k topics, and each topic is a probability distribution over all the different terms in our vocabulary V. That is to say that each word has various probabilities of appearing in each topic.
The full probability formula that generates a document is in Figure 2.0 below. If we break this down, on the right hand side we have three product sums:
Dirichlet distribution of topics over terms: (corresponds to Fig 1.4 and 1.5) for each topic i amongst K topics, what is the probability distribution of words for i.
Dirichlet distribution of documents over topics: (corresponds to Fig 1.3) for each document j in our corpus of size M, what is the probability distribution of topics for j.
Probability of a topic appearing given a document X the probability of a word appearing given a topic: (corresponding to the two rectangles in Fig 1.7) how likely is it that certain topics, Z, appear in this document and then how likely is that certain words, W, appear given those topics.
The first two sums contain symmetric Dirichlet distributions which are prior probability distributions for our documents and our topics (Fig 2.1 shows a set of general Dirichlet distributions, including symmetric ones).
The 3rd sum contains two multinomial distributions, one over topics and one over words — i.e. we sample topics from a probability distribution of them and then for each topic instance we sample words from a probability distribution of words for that particular topic.
As was mentioned at the end of the Intuition section, using the final probability we try to generate the same distribution of words as the one that we get in our original documents. The probability of achieving this is very, very low, but for some values of alpha and beta the probability will be less low.
What metrics do we use for finding our latent topics? As Shirley and Sievert note:
“To interpret a topic, one typically examines a ranked list of the most probable terms in that topic, [...]. The problem with interpreting topics this way is that common terms in the corpus often appear near the top of such lists for multiple topics, making it hard to differentiate the meanings of these topics.” (2014)
That is exactly the problem we’ve stumbled into in the next section, Implementation. Therefore we use an alternative metric for interpreting our topics — relevance (Shirley and Sievert, 2014).
This is an adjustable metric that balances a term’s frequency in a particular topic against the term’s frequency across the whole corpus of documents.
In other words, if we have a term that’s quite popular in a topic, relevance allows us to gauge how much of its popularity is due to it being very specific to that topic and how much of it is due to it just being a work that appears everywhere. An example of the latter would be “learning” in the job description data. When we adjust relevance with a lower lambda (i.e. penalising terms that just happen to be frequent across all topics), we see that “learning” is not that special a term, and it only comes up frequently because of its prevalence across the corpus.
The mathematical definition of relevance is:
r — relevance
⍵ — a term in our vocabulary
k — a topic amongst the ones our LDA has produced
λ — the adjustable weight parameter
φkw — probability of a term appearing in a particular topic
pw — the probability of a term appearing inside the corpus as a whole
Apart from lambda, λ, all the terms are derived from the LDA data and model. We adjust lambda in the next section to help us derive more useful insights. The original paper authors kept lambda in the range of 0.3 to 0.6 (Shirley and Sievert, 2014).
The implementation of sklearn’s LatentDirichletAllocation model follows the pattern of most sklearn models. In my notebook, I:
Pre-processed my text data,Vectorised it (resulting in a document-term matrix),Fit_transformed it using LDA and thenInspected the results to see if there are any emergent, identifiable topics.
Pre-processed my text data,
Vectorised it (resulting in a document-term matrix),
Fit_transformed it using LDA and then
Inspected the results to see if there are any emergent, identifiable topics.
The last part is highly subjective (remember this is unsupervised learning) and is not guaranteed to reveal anything really interesting. Furthermore the ability to identify topics (like clusters) depends on your domain knowledge of the data. I recommend also altering the alpha and beta parameters to match your expectations of the text data.
The data I’m using is job post description data from indeed.co.uk. The dataframe has many other attributes than text, including whether I used the search terms “data scientist”, “data analyst” or “machine learning engineer”. Can we find some of the original search categories in our LDA topics?
In the gist below you’ll see that I’ve vectorised my data and passed it to an LDA model (this happens under the hood of the data_to_lda function).
Running this code and the print_topics function will produce something like this:
Topics found via LDA on Count Vectorised data for ALL categories:Topic #1:software; experience; amazon; learning; opportunity; team; application; business; work; product; engineer; problem; development; technical; make; personal; process; skill; working; scienceTopic #2:learning; research; experience; science; team; role; work; working; model; skill; deep; please; language; python; nlp; quantitative; technique; candidate; algorithm; researcherTopic #3:learning; work; team; time; company; causalens; business; high; platform; exciting; award; day; development; approach; best; holiday; fund; mission; opportunity; problemTopic #4:client; business; team; work; people; opportunity; service; financial; role; value; investment; experience; firm; market; skill; management; make; global; working; support...
The “print_topics” function gives the terms for each topic in decreasing order of probability, which can be informative. It’s at this stage that we can start trying to label the emergent, latent topics from our model. For instance, Topic 1 seems to be related mildly related to ML engineer skills and requirements (the mention of “amazon” relates to using AWS — this is something I found from the EDA stage of the project in another notebook); meanwhile, Topic 4 clearly has a more client-facing or business-oriented theme, given terms like “market”, “financial”, “global”.
Now those two categories might seem a bit far-fetched to you and that’s a fair criticism. You may also have noticed that using this method for topic determination is hard. So, let’s turn to pyLDAvis!
Using pyLDAvis, the LDA data (which in our case, was 10-dimensional) has been decomposed via PCA (principal component analysis) to be only 2-dimensional. Thus it has been flattened for the purposes of visualisation. We have ten circles and the center of each circle represents the position of our topic in the latent feature space; the distances between topics illustrates how (dis)similar the topics are and the area of the circles is proportional to how many documents feature each topic.
Below I’ve shown how you insert an already trained sklearn LDA model in pyLDAvis. Thankfully the people responsible for adapting the original LDAvis (which was R model) to python made it communicate efficiently with sklearn.
And in Fig 3.0 is the plot we generate:
Interpreting pyLDAvis plots
The LDAvis plot comes in two parts — a 2-dimensional ‘flattened’ replotting of our n-dimensional LDA data and an interactive, varying horizontal bar-chart of term distributions. Both of these are shown in Fig A1.0. One important feature to note is that the right-hand bar chart shows the terms in a topic in decreasing order of relevance, but the bars indicate the frequency of the terms. The red section represents the term frequency purely within the particular topic; the red and blue represent the overall term frequency within the corpus of documents.
Adjusting λ (lambda)
If we set λ equal to 1, then our relevance is given purely by the probability of the word to that topic. Setting it to 0 will result in our relevance being dictated by specificity of that word to the topic — this is because the right hand term divides the probability of a term appearing in a particular topic divided by the probability of the word appearing generally — thus, highly frequent words (such as ‘team’, ‘skill’, ‘business’) will be downgraded heavily in relevance when we have a lower λ value.
In Fig 3.1 λ was set to 1 and you can see that the terms tend to match the ones that dominate across the board generally (i.e. like in our print-outs of the most popular terms for each topic). This was only done for topic 1, but when I changed topic the distribution of top-30 most relevant terms barely changed at all!
Now, in Fig 3.2 λ was set to 0 and the terms changed completely!
Now we have highly specific terms, but pay attention to the scale at the top — the most relevant word appears about 60 times. That’s quite a come down after over 6000! Also, these words won’t necessarily tell us anything interesting. If you select a different topic with this lambda value you will keep getting junk terms that aren’t necessarily that important.
In Fig 3.3 I’ve set lambda to 0.6 and I am exploring topic 2. Right off the bat there is a significant theme here surrounding engineer work, with terms like “aws”, “cloud” and “platform”.
Another great thing that you can do with pyLDAvis is visually inspect the conditional topic distribution given a word, simply by hovering over the word (Fig 3.4). Below we can see just how much “NLP” is split amongst several topics — not a lot! This gives me further reason to believe that topic 6 is focused on NLP and text-based work (terms like “speech”, “language”, “text” also help in that regard). An interesting insight for me is the fact that “research” and “PhD” co-occur so strongly in this topic.
Does this mean that NLP-focussed roles in the industry demand higher education than other roles? Do they demand previous research experience more often than other roles? Are NLP roles perhaps more fixated on experimental techniques and thus require someone with knowledge of the cutting edge?
While the interactive plot generated cannot deliver concrete answers, what it can do is provide us with a starting position for further investigation. If you’re in an organisation where you can run topic modelling, you can use LDA’s latent themes to inform survey-design, A/B testing or even correlate it with other available data to find interesting correlations!
I wish you the best of luck in topic modelling. If you’ve enjoyed this lengthy read, please give me as many claps as you think are appropriate. If you have knowledge of LDA and think I’ve gotten something even partially wrong please leave me a comment (feedback is a gift and all that)!
Serrano L. (2020). Accessed online: Latent Dirichlet Allocation (Part 1 of 2)Sievert C. and Shirley K (2014). LDAvis: A method for visualizing and interpreting topics. Accessed online: Proceedings of the Workshop on Interactive Language Learning, Visualization, and Interfaces
Serrano L. (2020). Accessed online: Latent Dirichlet Allocation (Part 1 of 2)
Sievert C. and Shirley K (2014). LDAvis: A method for visualizing and interpreting topics. Accessed online: Proceedings of the Workshop on Interactive Language Learning, Visualization, and Interfaces
|
[
{
"code": null,
"e": 712,
"s": 172,
"text": "TL;DR — Latent Dirichlet Allocation (LDA, sometimes LDirA/LDiA) is one of the most popular and interpretable generative models for finding topics in text data. I’ve provided an example notebook based on web-scraped job description data. Although running LDA on a canonical dataset like 20Newsgroups would’ve provided clearer topics , it’s important to witness how difficult topic identification can be “in the wild”, and how you might not actually find clear topics — with unsupervised learning, you are never guaranteed to find an answer!"
},
{
"code": null,
"e": 944,
"s": 712,
"text": "Acknowledgement: the greatest aid to my understanding was Louis Serrano’s two videos on LDA (2020). A lot of the intuition section is based on his explanation, and I would urge you to visit his video for a more thorough dissection."
},
{
"code": null,
"e": 954,
"s": 944,
"text": "Intuition"
},
{
"code": null,
"e": 960,
"s": 954,
"text": "Maths"
},
{
"code": null,
"e": 993,
"s": 960,
"text": "Implementation and visualisation"
},
{
"code": null,
"e": 1261,
"s": 993,
"text": "Let’s say that you have a collection of different news articles (your corpus of documents), and you suspect that there are several topics that come up frequently within said corpus — your goal is to find out what they are! To get there you make a few key assumptions:"
},
{
"code": null,
"e": 1365,
"s": 1261,
"text": "The distributional hypothesis: Words that appear together frequently are likely to be close in meaning;"
},
{
"code": null,
"e": 1419,
"s": 1365,
"text": "each topic is a mixture of different words (Fig 1.1);"
},
{
"code": null,
"e": 1477,
"s": 1419,
"text": "each document is a mixture of different topics (Fig 1.2)."
},
{
"code": null,
"e": 1757,
"s": 1477,
"text": "In Fig 1.1 you’ll notice that the topic “Health & Medicine” has various words associated with it to varying degrees (“cancer” is more strongly associated than “vascular” or “exercise”). Note that different words can be associated with different topics, as with the word “cardio”."
},
{
"code": null,
"e": 1992,
"s": 1757,
"text": "In Fig 1.2 you’ll see that a single document can pertain to multiple topics (as colour-coded on the left). Words like “injury” and “recovery” might also belong to multiple topics (hence why I’ve coloured them in more than one colour)."
},
{
"code": null,
"e": 2489,
"s": 1992,
"text": "Now LDA is a generative model — it tries to determine the underlying mechanism that generates the articles and the topics. Think of it as if there’s a machine with particular settings that spits out articles, but we can’t see the machine’s settings, only what it produces. LDA creates a set of machines with different settings and selects the one that gives the best-fitting results (Serrano, 2020). Once the best one is found, we take a look at its “settings” and we deduce the topics from that."
},
{
"code": null,
"e": 2517,
"s": 2489,
"text": "So what are these settings?"
},
{
"code": null,
"e": 3066,
"s": 2517,
"text": "First, we have something called the Dirichlet (pronounced like dee-reesh-lay) prior of the topics. This is a number that says how sparse or how mixed up our topics are. In L Serrano’s video (which I highly recommend!) he illustrates how visually you can think of this as a triangle (Fig 1.3) where the dots represent the documents and their position with respect to the corners (i.e. the topics) represents the how they’re related to each of the topics (2020). So a dot that is very close to the “Sports” vertex will be almost entirely about sport."
},
{
"code": null,
"e": 3570,
"s": 3066,
"text": "In the lefthand triangle the documents are fairly separated, most of them neatly tucked into their corners (this corresponds to a low Dirichlet prior, alpha<1); on the right they are in the middle and represent a more even mix of topics (a higher Dirichlet prior, alpha>1). Look at the document in Fig 1.2 and, given the mix of topics, have a think about where you think it would be placed in the triangle on the right (my answer is that it’d be the dot just above the one closest to the Sports corner)."
},
{
"code": null,
"e": 3811,
"s": 3570,
"text": "Second, we have the Dirichlet prior of the terms (all the words in our vocabulary). This number (whose name is beta) has almost exactly the same function as alpha — except that it determines how the topics are distributed amongst the terms."
},
{
"code": null,
"e": 4075,
"s": 3811,
"text": "As we said before, the topics are assumed to be mixtures (more precisely, distributions) of different terms. In Fig 1.4 “Sports” is mostly drawn towards “injury”. “Health&Medicine” is torn between “cardio” and “injury” and has no association with the term “pray”."
},
{
"code": null,
"e": 4614,
"s": 4075,
"text": "But wait, our vocabulary doesn’t consist of just 3 words! You’re right! We could have a vocabulary of 4 words (as shown in Fig 1.5)! Trouble is that visualising a typical vocabulary of N words (where N could be 10'000) would require a generalised version of the triangle shape, but in N — 1 dimensions (the term for this is an n-1 simplex). This is where the visuals stop and we trust that the maths of higher dimensions will function as expected. This also applies to the topics — very often we’ll find ourselves with more than 3 topics."
},
{
"code": null,
"e": 5019,
"s": 4614,
"text": "An important clarification: in LDA we start with values of alpha and beta as hyperparameters, but these numbers only tell us whether our dots (documents / topics) are generally concentrated in the middle of their triangles or closer to the corners. The actual positions within the triangle (simplex) are guessed by the machine — the guesswork is not random, it’s heavily weighted by the Dirichlet priors."
},
{
"code": null,
"e": 5245,
"s": 5019,
"text": "So the machine creates the two Dirichlet distributions, distributes the documents and topics on them and then generates documents based on those distributions (Fig 1.6). So, how does the last step happen, the generation part?"
},
{
"code": null,
"e": 6022,
"s": 5245,
"text": "Remember at the start we said that topics are seen as mixtures / distributions of words and documents as mixtures / distributions of topics? Going from left to right in Figure 1.7 we start with a document, somewhere in the triangle, torn between our 3 topics. If it’s near the “Sports” corner, this means that the document will be mostly about Sports, with some mentions of “Religion” and “Health&Medicine”. So we know the topic composition of the document → therefore we can estimate what words will come up. We will be sampling (i.e. randomly pulling out) words mostly from Sports, some from Health&Medicine and a very small amount from Religion (Fig 1.7). Here’s a question for you: looking at the triangle at the bottom of Fig 1.7, do you think word 2 will come up or not?"
},
{
"code": null,
"e": 6444,
"s": 6022,
"text": "The answer is that it might: remember that topics are mixtures of words. You might be thinking that word 2 is very strongly related to the yellow (Religion) topic, and since this topic is very sparse in this document word 2 won’t come up as much. But remember that a. word 2 is also associated with the blue, Sports topic and b. the words are sample probabilistically, so every word has some non-zero chance of appearing."
},
{
"code": null,
"e": 6828,
"s": 6444,
"text": "The words in our final, generated document (on the right end of Fig 1.7) will be compared to the words in the original documents. We won’t get the same document, BUT when we compare a range of different LDA “machines” with a range of different distributions, we find that one of them was closer to generating the document than the others were and that’s the LDA model that we choose."
},
{
"code": null,
"e": 7057,
"s": 6828,
"text": "A normal statistical language model assumes that you can generate a document by sampling from a probability distribution over words, i.e. for each word in our vocabulary there is an associated probability of that word appearing."
},
{
"code": null,
"e": 7389,
"s": 7057,
"text": "LDA adds a layer of complexity over this arrangement. It assumes a list of topics, k. Each document m is a probability distribution over these k topics, and each topic is a probability distribution over all the different terms in our vocabulary V. That is to say that each word has various probabilities of appearing in each topic."
},
{
"code": null,
"e": 7542,
"s": 7389,
"text": "The full probability formula that generates a document is in Figure 2.0 below. If we break this down, on the right hand side we have three product sums:"
},
{
"code": null,
"e": 7708,
"s": 7542,
"text": "Dirichlet distribution of topics over terms: (corresponds to Fig 1.4 and 1.5) for each topic i amongst K topics, what is the probability distribution of words for i."
},
{
"code": null,
"e": 7881,
"s": 7708,
"text": "Dirichlet distribution of documents over topics: (corresponds to Fig 1.3) for each document j in our corpus of size M, what is the probability distribution of topics for j."
},
{
"code": null,
"e": 8171,
"s": 7881,
"text": "Probability of a topic appearing given a document X the probability of a word appearing given a topic: (corresponding to the two rectangles in Fig 1.7) how likely is it that certain topics, Z, appear in this document and then how likely is that certain words, W, appear given those topics."
},
{
"code": null,
"e": 8391,
"s": 8171,
"text": "The first two sums contain symmetric Dirichlet distributions which are prior probability distributions for our documents and our topics (Fig 2.1 shows a set of general Dirichlet distributions, including symmetric ones)."
},
{
"code": null,
"e": 8659,
"s": 8391,
"text": "The 3rd sum contains two multinomial distributions, one over topics and one over words — i.e. we sample topics from a probability distribution of them and then for each topic instance we sample words from a probability distribution of words for that particular topic."
},
{
"code": null,
"e": 8966,
"s": 8659,
"text": "As was mentioned at the end of the Intuition section, using the final probability we try to generate the same distribution of words as the one that we get in our original documents. The probability of achieving this is very, very low, but for some values of alpha and beta the probability will be less low."
},
{
"code": null,
"e": 9049,
"s": 8966,
"text": "What metrics do we use for finding our latent topics? As Shirley and Sievert note:"
},
{
"code": null,
"e": 9370,
"s": 9049,
"text": "“To interpret a topic, one typically examines a ranked list of the most probable terms in that topic, [...]. The problem with interpreting topics this way is that common terms in the corpus often appear near the top of such lists for multiple topics, making it hard to differentiate the meanings of these topics.” (2014)"
},
{
"code": null,
"e": 9563,
"s": 9370,
"text": "That is exactly the problem we’ve stumbled into in the next section, Implementation. Therefore we use an alternative metric for interpreting our topics — relevance (Shirley and Sievert, 2014)."
},
{
"code": null,
"e": 9714,
"s": 9563,
"text": "This is an adjustable metric that balances a term’s frequency in a particular topic against the term’s frequency across the whole corpus of documents."
},
{
"code": null,
"e": 10281,
"s": 9714,
"text": "In other words, if we have a term that’s quite popular in a topic, relevance allows us to gauge how much of its popularity is due to it being very specific to that topic and how much of it is due to it just being a work that appears everywhere. An example of the latter would be “learning” in the job description data. When we adjust relevance with a lower lambda (i.e. penalising terms that just happen to be frequent across all topics), we see that “learning” is not that special a term, and it only comes up frequently because of its prevalence across the corpus."
},
{
"code": null,
"e": 10326,
"s": 10281,
"text": "The mathematical definition of relevance is:"
},
{
"code": null,
"e": 10340,
"s": 10326,
"text": "r — relevance"
},
{
"code": null,
"e": 10369,
"s": 10340,
"text": "⍵ — a term in our vocabulary"
},
{
"code": null,
"e": 10419,
"s": 10369,
"text": "k — a topic amongst the ones our LDA has produced"
},
{
"code": null,
"e": 10455,
"s": 10419,
"text": "λ — the adjustable weight parameter"
},
{
"code": null,
"e": 10515,
"s": 10455,
"text": "φkw — probability of a term appearing in a particular topic"
},
{
"code": null,
"e": 10585,
"s": 10515,
"text": "pw — the probability of a term appearing inside the corpus as a whole"
},
{
"code": null,
"e": 10834,
"s": 10585,
"text": "Apart from lambda, λ, all the terms are derived from the LDA data and model. We adjust lambda in the next section to help us derive more useful insights. The original paper authors kept lambda in the range of 0.3 to 0.6 (Shirley and Sievert, 2014)."
},
{
"code": null,
"e": 10961,
"s": 10834,
"text": "The implementation of sklearn’s LatentDirichletAllocation model follows the pattern of most sklearn models. In my notebook, I:"
},
{
"code": null,
"e": 11154,
"s": 10961,
"text": "Pre-processed my text data,Vectorised it (resulting in a document-term matrix),Fit_transformed it using LDA and thenInspected the results to see if there are any emergent, identifiable topics."
},
{
"code": null,
"e": 11182,
"s": 11154,
"text": "Pre-processed my text data,"
},
{
"code": null,
"e": 11235,
"s": 11182,
"text": "Vectorised it (resulting in a document-term matrix),"
},
{
"code": null,
"e": 11273,
"s": 11235,
"text": "Fit_transformed it using LDA and then"
},
{
"code": null,
"e": 11350,
"s": 11273,
"text": "Inspected the results to see if there are any emergent, identifiable topics."
},
{
"code": null,
"e": 11693,
"s": 11350,
"text": "The last part is highly subjective (remember this is unsupervised learning) and is not guaranteed to reveal anything really interesting. Furthermore the ability to identify topics (like clusters) depends on your domain knowledge of the data. I recommend also altering the alpha and beta parameters to match your expectations of the text data."
},
{
"code": null,
"e": 11988,
"s": 11693,
"text": "The data I’m using is job post description data from indeed.co.uk. The dataframe has many other attributes than text, including whether I used the search terms “data scientist”, “data analyst” or “machine learning engineer”. Can we find some of the original search categories in our LDA topics?"
},
{
"code": null,
"e": 12135,
"s": 11988,
"text": "In the gist below you’ll see that I’ve vectorised my data and passed it to an LDA model (this happens under the hood of the data_to_lda function)."
},
{
"code": null,
"e": 12217,
"s": 12135,
"text": "Running this code and the print_topics function will produce something like this:"
},
{
"code": null,
"e": 13026,
"s": 12217,
"text": "Topics found via LDA on Count Vectorised data for ALL categories:Topic #1:software; experience; amazon; learning; opportunity; team; application; business; work; product; engineer; problem; development; technical; make; personal; process; skill; working; scienceTopic #2:learning; research; experience; science; team; role; work; working; model; skill; deep; please; language; python; nlp; quantitative; technique; candidate; algorithm; researcherTopic #3:learning; work; team; time; company; causalens; business; high; platform; exciting; award; day; development; approach; best; holiday; fund; mission; opportunity; problemTopic #4:client; business; team; work; people; opportunity; service; financial; role; value; investment; experience; firm; market; skill; management; make; global; working; support..."
},
{
"code": null,
"e": 13600,
"s": 13026,
"text": "The “print_topics” function gives the terms for each topic in decreasing order of probability, which can be informative. It’s at this stage that we can start trying to label the emergent, latent topics from our model. For instance, Topic 1 seems to be related mildly related to ML engineer skills and requirements (the mention of “amazon” relates to using AWS — this is something I found from the EDA stage of the project in another notebook); meanwhile, Topic 4 clearly has a more client-facing or business-oriented theme, given terms like “market”, “financial”, “global”."
},
{
"code": null,
"e": 13800,
"s": 13600,
"text": "Now those two categories might seem a bit far-fetched to you and that’s a fair criticism. You may also have noticed that using this method for topic determination is hard. So, let’s turn to pyLDAvis!"
},
{
"code": null,
"e": 14291,
"s": 13800,
"text": "Using pyLDAvis, the LDA data (which in our case, was 10-dimensional) has been decomposed via PCA (principal component analysis) to be only 2-dimensional. Thus it has been flattened for the purposes of visualisation. We have ten circles and the center of each circle represents the position of our topic in the latent feature space; the distances between topics illustrates how (dis)similar the topics are and the area of the circles is proportional to how many documents feature each topic."
},
{
"code": null,
"e": 14516,
"s": 14291,
"text": "Below I’ve shown how you insert an already trained sklearn LDA model in pyLDAvis. Thankfully the people responsible for adapting the original LDAvis (which was R model) to python made it communicate efficiently with sklearn."
},
{
"code": null,
"e": 14556,
"s": 14516,
"text": "And in Fig 3.0 is the plot we generate:"
},
{
"code": null,
"e": 14584,
"s": 14556,
"text": "Interpreting pyLDAvis plots"
},
{
"code": null,
"e": 15141,
"s": 14584,
"text": "The LDAvis plot comes in two parts — a 2-dimensional ‘flattened’ replotting of our n-dimensional LDA data and an interactive, varying horizontal bar-chart of term distributions. Both of these are shown in Fig A1.0. One important feature to note is that the right-hand bar chart shows the terms in a topic in decreasing order of relevance, but the bars indicate the frequency of the terms. The red section represents the term frequency purely within the particular topic; the red and blue represent the overall term frequency within the corpus of documents."
},
{
"code": null,
"e": 15162,
"s": 15141,
"text": "Adjusting λ (lambda)"
},
{
"code": null,
"e": 15669,
"s": 15162,
"text": "If we set λ equal to 1, then our relevance is given purely by the probability of the word to that topic. Setting it to 0 will result in our relevance being dictated by specificity of that word to the topic — this is because the right hand term divides the probability of a term appearing in a particular topic divided by the probability of the word appearing generally — thus, highly frequent words (such as ‘team’, ‘skill’, ‘business’) will be downgraded heavily in relevance when we have a lower λ value."
},
{
"code": null,
"e": 15989,
"s": 15669,
"text": "In Fig 3.1 λ was set to 1 and you can see that the terms tend to match the ones that dominate across the board generally (i.e. like in our print-outs of the most popular terms for each topic). This was only done for topic 1, but when I changed topic the distribution of top-30 most relevant terms barely changed at all!"
},
{
"code": null,
"e": 16054,
"s": 15989,
"text": "Now, in Fig 3.2 λ was set to 0 and the terms changed completely!"
},
{
"code": null,
"e": 16416,
"s": 16054,
"text": "Now we have highly specific terms, but pay attention to the scale at the top — the most relevant word appears about 60 times. That’s quite a come down after over 6000! Also, these words won’t necessarily tell us anything interesting. If you select a different topic with this lambda value you will keep getting junk terms that aren’t necessarily that important."
},
{
"code": null,
"e": 16604,
"s": 16416,
"text": "In Fig 3.3 I’ve set lambda to 0.6 and I am exploring topic 2. Right off the bat there is a significant theme here surrounding engineer work, with terms like “aws”, “cloud” and “platform”."
},
{
"code": null,
"e": 17112,
"s": 16604,
"text": "Another great thing that you can do with pyLDAvis is visually inspect the conditional topic distribution given a word, simply by hovering over the word (Fig 3.4). Below we can see just how much “NLP” is split amongst several topics — not a lot! This gives me further reason to believe that topic 6 is focused on NLP and text-based work (terms like “speech”, “language”, “text” also help in that regard). An interesting insight for me is the fact that “research” and “PhD” co-occur so strongly in this topic."
},
{
"code": null,
"e": 17405,
"s": 17112,
"text": "Does this mean that NLP-focussed roles in the industry demand higher education than other roles? Do they demand previous research experience more often than other roles? Are NLP roles perhaps more fixated on experimental techniques and thus require someone with knowledge of the cutting edge?"
},
{
"code": null,
"e": 17770,
"s": 17405,
"text": "While the interactive plot generated cannot deliver concrete answers, what it can do is provide us with a starting position for further investigation. If you’re in an organisation where you can run topic modelling, you can use LDA’s latent themes to inform survey-design, A/B testing or even correlate it with other available data to find interesting correlations!"
},
{
"code": null,
"e": 18057,
"s": 17770,
"text": "I wish you the best of luck in topic modelling. If you’ve enjoyed this lengthy read, please give me as many claps as you think are appropriate. If you have knowledge of LDA and think I’ve gotten something even partially wrong please leave me a comment (feedback is a gift and all that)!"
},
{
"code": null,
"e": 18334,
"s": 18057,
"text": "Serrano L. (2020). Accessed online: Latent Dirichlet Allocation (Part 1 of 2)Sievert C. and Shirley K (2014). LDAvis: A method for visualizing and interpreting topics. Accessed online: Proceedings of the Workshop on Interactive Language Learning, Visualization, and Interfaces"
},
{
"code": null,
"e": 18412,
"s": 18334,
"text": "Serrano L. (2020). Accessed online: Latent Dirichlet Allocation (Part 1 of 2)"
}
] |
Matplotlib.figure.Figure.clf() in Python - GeeksforGeeks
|
30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The clf() method of figure module of matplotlib library is used to Clear the figure.
Syntax: clf(self, keep_observers=False)
Parameters: This accept the following parameters that are described below:
keep_observers: This parameter is the boolean value.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.figure.Figure.clf() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_xlabel('x-axis')ax.set_ylabel('y-axis') ax.plot([1, 2, 3])ax.grid(True) fig.clf(True) fig.suptitle('matplotlib.figure.Figure.clf() \function Example\n\n', fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, [ax, ax1] = plt.subplots(2, 1, sharex = True) ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('Sample Example', fontsize = 12, fontweight ='bold') ax1.set_ylabel('y-axis')ax1.plot(t, s)ax1.grid(True) fig.clf(False) fig.suptitle('matplotlib.figure.Figure.clf() \function Example\n\n', fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
|
[
{
"code": null,
"e": 24390,
"s": 24362,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 24701,
"s": 24390,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 24786,
"s": 24701,
"text": "The clf() method of figure module of matplotlib library is used to Clear the figure."
},
{
"code": null,
"e": 24826,
"s": 24786,
"text": "Syntax: clf(self, keep_observers=False)"
},
{
"code": null,
"e": 24901,
"s": 24826,
"text": "Parameters: This accept the following parameters that are described below:"
},
{
"code": null,
"e": 24954,
"s": 24901,
"text": "keep_observers: This parameter is the boolean value."
},
{
"code": null,
"e": 25002,
"s": 24954,
"text": "Returns: This method does not return any value."
},
{
"code": null,
"e": 25094,
"s": 25002,
"text": "Below examples illustrate the matplotlib.figure.Figure.clf() function in matplotlib.figure:"
},
{
"code": null,
"e": 25105,
"s": 25094,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_xlabel('x-axis')ax.set_ylabel('y-axis') ax.plot([1, 2, 3])ax.grid(True) fig.clf(True) fig.suptitle('matplotlib.figure.Figure.clf() \\function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 25423,
"s": 25105,
"text": null
},
{
"code": null,
"e": 25431,
"s": 25423,
"text": "Output:"
},
{
"code": null,
"e": 25442,
"s": 25431,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, [ax, ax1] = plt.subplots(2, 1, sharex = True) ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('Sample Example', fontsize = 12, fontweight ='bold') ax1.set_ylabel('y-axis')ax1.plot(t, s)ax1.grid(True) fig.clf(False) fig.suptitle('matplotlib.figure.Figure.clf() \\function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 25960,
"s": 25442,
"text": null
},
{
"code": null,
"e": 25968,
"s": 25960,
"text": "Output:"
},
{
"code": null,
"e": 25992,
"s": 25968,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 26010,
"s": 25992,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26017,
"s": 26010,
"text": "Python"
},
{
"code": null,
"e": 26115,
"s": 26017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26147,
"s": 26115,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26189,
"s": 26147,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26231,
"s": 26189,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26287,
"s": 26231,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26309,
"s": 26287,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26336,
"s": 26309,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26365,
"s": 26336,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26396,
"s": 26365,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26432,
"s": 26396,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Batch Script - MD
|
This batch command creates a new directory in the current location.
md [new directory name]
@echo off
md newdir
cd newdir
cd Rem “Goes back to the parent directory and create 2 directories”
cd..
md newdir1 newdir1
cd newdir1
cd
cd..
cd newdir2
cd
The above command produces the following output.
C:\newdir
C:\newdir1
C:\newdir2
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2237,
"s": 2169,
"text": "This batch command creates a new directory in the current location."
},
{
"code": null,
"e": 2262,
"s": 2237,
"text": "md [new directory name]\n"
},
{
"code": null,
"e": 2427,
"s": 2262,
"text": "@echo off \nmd newdir \ncd newdir \ncd Rem “Goes back to the parent directory and create 2 directories” \ncd.. \nmd newdir1 newdir1 \ncd newdir1 \ncd \ncd.. \ncd newdir2 \ncd"
},
{
"code": null,
"e": 2476,
"s": 2427,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2511,
"s": 2476,
"text": "C:\\newdir \nC:\\newdir1 \nC:\\newdir2\n"
},
{
"code": null,
"e": 2518,
"s": 2511,
"text": " Print"
},
{
"code": null,
"e": 2529,
"s": 2518,
"text": " Add Notes"
}
] |
bzgrep command in Linux with examples - GeeksforGeeks
|
15 May, 2019
bzgrep is a Linux command used to search for a pattern or an expression but inside a bzip2-compressed file. This command simply passes it’s arguments and the decompressed files to grep. Therefore, all the flags used in the grep command remain same in bzgrep, since they are simply sent to grep as they are. If no file is specified, then the standard input is decompressed if necessary and fed to grep.
Synopsis:
bzgrep [ grep_options ] [ -e ] pattern filename...
Example: Here we take a normal text file, use grep on it. Then we compress it using bzip2 and search the specific pattern in the compressed file with bzgrep.
linux-command
Linux-file-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
chown command in Linux with Examples
mv command in Linux with examples
Named Pipe or FIFO with example C program
SED command in Linux | Set 2
scp command in Linux with Examples
Docker - COPY Instruction
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 24808,
"s": 24406,
"text": "bzgrep is a Linux command used to search for a pattern or an expression but inside a bzip2-compressed file. This command simply passes it’s arguments and the decompressed files to grep. Therefore, all the flags used in the grep command remain same in bzgrep, since they are simply sent to grep as they are. If no file is specified, then the standard input is decompressed if necessary and fed to grep."
},
{
"code": null,
"e": 24818,
"s": 24808,
"text": "Synopsis:"
},
{
"code": null,
"e": 24870,
"s": 24818,
"text": "bzgrep [ grep_options ] [ -e ] pattern filename...\n"
},
{
"code": null,
"e": 25028,
"s": 24870,
"text": "Example: Here we take a normal text file, use grep on it. Then we compress it using bzip2 and search the specific pattern in the compressed file with bzgrep."
},
{
"code": null,
"e": 25042,
"s": 25028,
"text": "linux-command"
},
{
"code": null,
"e": 25062,
"s": 25042,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 25069,
"s": 25062,
"text": "Picked"
},
{
"code": null,
"e": 25093,
"s": 25069,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 25104,
"s": 25093,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25123,
"s": 25104,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25221,
"s": 25123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25230,
"s": 25221,
"text": "Comments"
},
{
"code": null,
"e": 25243,
"s": 25230,
"text": "Old Comments"
},
{
"code": null,
"e": 25269,
"s": 25243,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25304,
"s": 25269,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 25341,
"s": 25304,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25381,
"s": 25341,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 25418,
"s": 25381,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 25452,
"s": 25418,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25494,
"s": 25452,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 25523,
"s": 25494,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 25558,
"s": 25523,
"text": "scp command in Linux with Examples"
}
] |
How to replace multiple spaces in a string using a single space using Java regex?
|
The metacharacter “\\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \\S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.
Match the input string with the above regular expression and replace the results with single space “ ”.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\s+";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}
Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match space(s)
String regex = "\\s+";
//Replacing the pattern with single space
String result = input.replaceAll(regex, " ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}
Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces
|
[
{
"code": null,
"e": 1318,
"s": 1062,
"text": "The metacharacter “\\\\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \\\\S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space."
},
{
"code": null,
"e": 1422,
"s": 1318,
"text": "Match the input string with the above regular expression and replace the results with single space “ ”."
},
{
"code": null,
"e": 2134,
"s": 1422,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class ReplaceAllExample {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a String\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n String regex = \"\\\\s+\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n //Replacing all space characters with single space\n String result = matcher.replaceAll(\" \");\n System.out.print(\"Text after removing unwanted spaces: \\n\"+result);\n }\n}"
},
{
"code": null,
"e": 2286,
"s": 2134,
"text": "Enter a String\nhello this is a sample text with irregular spaces\nText after removing unwanted spaces:\nhello this is a sample text with irregular spaces"
},
{
"code": null,
"e": 2787,
"s": 2286,
"text": "import java.util.Scanner;\npublic class Test {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a String\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n //Regular expression to match space(s)\n String regex = \"\\\\s+\";\n //Replacing the pattern with single space\n String result = input.replaceAll(regex, \" \");\n System.out.print(\"Text after removing unwanted spaces: \\n\"+result);\n }\n}"
},
{
"code": null,
"e": 2939,
"s": 2787,
"text": "Enter a String\nhello this is a sample text with irregular spaces\nText after removing unwanted spaces:\nhello this is a sample text with irregular spaces"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.