title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Minimum X (xor) A | Practice | GeeksforGeeks
|
Given two integers A and B, the task is to find an integer X such that (X XOR A) is minimum possible and the count of set bit in X is equal to the count of set bits in B.
Example 1:
Input:
A = 3, B = 5
Output: 3
Explanation:
Binary(A) = Binary(3) = 011
Binary(B) = Binary(5) = 101
The XOR will be minimum when x = 3
i.e. (3 XOR 3) = 0 and the number
of set bits in 3 is equal
to the number of set bits in 5.
Example 2:
Input:
A = 7, B = 12
Output: 6
Explanation:
(7)2= 111
(12)2= 1100
The XOR will be minimum when x = 6
i.e. (6 XOR 7) = 1 and the number
of set bits in 6 is equal to the
number of set bits in 12.
0
samikshamahure3 months ago
class Solution {
public:
int minVal(int a, int b) {
//check the case if set bits(A)==set bits in(B)
int A=a,B=b;
int countA=0,countB=0;
while(A){
A=A&(A-1);
countA++;
}
while(B){
B=B&(B-1);
countB++;
}
if(countA==countB) return a;
int x=0;
stack<short int>s;
//push the binary of number in stack
while(a){
s.push(a%2);
a=a/2;
}
while(!s.empty()){
int rem=s.top();
if(rem==1 && countB){
//if it is set and count of set bit is less
x=x<<1;
x+=1;
countB--;
}
else{
x=x<<1;
}
s.pop();
}
if(!countB){
return x;
}
else{
//if number of bits is not equal to B
int i=1;
while(countB){
//traverse from lsb and add 1 if it is 0
if((x & i)==0) {
x+=i;
countB--;
}
else{
i++;
}
}
return x;
}
}
};
0
kake13373 months ago
int minVal(int a, int b) {
int c=0;
while(b>0)
{
b=b&(b-1);
c++;
}
int x=0;
int i=log2(a);
while(c>0 && i>=0)
{
if(a&(1<<i))
{
c--;
x=x|(1<<i);
}
i--;
}
i=0;
while(c>0)
{
if(!(x&(1<<i)))
{
c--;
x=x|(1<<i);
}
i++;
}
return x;
0
chessnoobdj4 months ago
Easy greedy c++
int minVal(int a, int b) {
int cnt_a = __builtin_popcount(a);
int cnt_b = __builtin_popcount(b);
int num = 0;
if(cnt_a >= cnt_b){
num = a;
int tmp = cnt_a-cnt_b, i=0;
while(tmp){
if((1&(num>>i)) == 1){
num ^= (1<<i);
tmp -= 1;
}
i += 1;
}
}
else{
num = a;
int tmp = cnt_b-cnt_a, i=0;
while(tmp){
if((1&(num>>i)) == 0){
num |= 1<<i;
tmp -= 1;
}
i += 1;
}
}
return num;
}
0
Jyoti9 months ago
Jyoti
yeahhhhh.......first time i solved a hard level question without help. basically the idea is Traverse from the MSB in A to the LSB and if a bit is 1 then it also needs to be 1 in the answer in order to minimize the XOR but the number of bits set has to be equal to the number of set bits in B. So, when the count of set bits in the answer has reached the count of 1s in B then the rest of the bits have to be 0.but there will be some case where you will reached to LSB and count of 1s in answer is not equal to count of 1s in B, then start traversing from LSB to MSB and if the bit is 0 then make it 1 in the answer do this untill no of 1s in answer and B is equal.
int getSetBits(int b) { int count=0; while(b) { b = b & (b-1); count++; } return count; } int minVal(int a, int b) { // code here int setBits = getSetBits(b); //cout<<setbits<<"hello\n";<br> int ans = 0; for (int i = 31; i >= 0; i--) { int mask = 1 << i; bool set = a & mask; if (set && setBits > 0) { ans |= (1 << i); setBits--; } } //cout<<setbits<<"hi\n";<br> if(setBits>0) { for(int i=0;i<32;i++) { int mask = 1 << i; bool set = ans & mask; if(!set && setBits) { ans|=(1<<i); setbits--;="" }<br=""> } } return ans; }
0
wallflower10 months ago
wallflower
Java easy solution. https://ide.geeksforgeeks.o...
0
Motasim1 year ago
Motasim
C++ 0.1 sec Solution:https://ide.geeksforgeeks.o...
0
SHIV RAM1 year ago
SHIV RAM
Hi @moderators... Please change the the question description to : " count of set bit in X is less than or equal to the count of set bits in B" or change the back-end code, Since it is producing wrong output for the cases when number of set bits in B is greater than number of set bits in A.
Since the problem is tagged as Hard, it would be apt to change the back-end function which handles all the cases correctly.
-1
Yash Khandelwal1 year ago
Yash Khandelwal
GFG is Known for its Incorrect Test cases!!.
0
Akshansh Jain1 year ago
Akshansh Jain
For input A = 9, B = 7, the answer of online judge is 9. According to question, number of set bits in X should be equal to number of set bits in B. I assume set bits are the number of 1's in the binary representation of the decimal. Here, X=9 (as given by online judge), and B = 7.
9's binary representation = 1001, number of set bits = 2.7's binary representation = 111, number of set bits = 3.
So, 9 should not even be a possible answer here, let alone the correct answer, as number of bits are not equal.
Please correct me if I have misunderstood anything.
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": 409,
"s": 238,
"text": "Given two integers A and B, the task is to find an integer X such that (X XOR A) is minimum possible and the count of set bit in X is equal to the count of set bits in B."
},
{
"code": null,
"e": 420,
"s": 409,
"text": "Example 1:"
},
{
"code": null,
"e": 647,
"s": 420,
"text": "Input: \nA = 3, B = 5\nOutput: 3\nExplanation:\nBinary(A) = Binary(3) = 011\nBinary(B) = Binary(5) = 101\nThe XOR will be minimum when x = 3\ni.e. (3 XOR 3) = 0 and the number\nof set bits in 3 is equal\nto the number of set bits in 5."
},
{
"code": null,
"e": 658,
"s": 647,
"text": "Example 2:"
},
{
"code": null,
"e": 856,
"s": 658,
"text": "Input: \nA = 7, B = 12\nOutput: 6\nExplanation:\n(7)2= 111\n(12)2= 1100\nThe XOR will be minimum when x = 6 \ni.e. (6 XOR 7) = 1 and the number \nof set bits in 6 is equal to the \nnumber of set bits in 12."
},
{
"code": null,
"e": 858,
"s": 856,
"text": "0"
},
{
"code": null,
"e": 885,
"s": 858,
"text": "samikshamahure3 months ago"
},
{
"code": null,
"e": 2152,
"s": 885,
"text": "class Solution {\n public:\n int minVal(int a, int b) {\n //check the case if set bits(A)==set bits in(B)\n int A=a,B=b;\n int countA=0,countB=0;\n while(A){\n A=A&(A-1);\n countA++;\n }\n while(B){\n B=B&(B-1);\n countB++;\n }\n if(countA==countB) return a;\n int x=0;\n stack<short int>s;\n //push the binary of number in stack\n while(a){\n s.push(a%2);\n a=a/2;\n }\n while(!s.empty()){\n int rem=s.top();\n if(rem==1 && countB){\n //if it is set and count of set bit is less\n x=x<<1;\n x+=1;\n countB--;\n }\n else{\n x=x<<1;\n }\n s.pop();\n }\n if(!countB){\n return x;\n }\n else{\n //if number of bits is not equal to B \n int i=1;\n while(countB){\n //traverse from lsb and add 1 if it is 0\n if((x & i)==0) {\n x+=i;\n countB--;\n }\n else{\n i++;\n }\n }\n return x;\n }\n }\n};"
},
{
"code": null,
"e": 2154,
"s": 2152,
"text": "0"
},
{
"code": null,
"e": 2175,
"s": 2154,
"text": "kake13373 months ago"
},
{
"code": null,
"e": 2672,
"s": 2175,
"text": " int minVal(int a, int b) {\n int c=0;\n while(b>0)\n {\n b=b&(b-1);\n c++;\n }\n int x=0;\n int i=log2(a);\n while(c>0 && i>=0)\n {\n if(a&(1<<i))\n {\n c--;\n x=x|(1<<i);\n }\n i--;\n }\n i=0;\n while(c>0)\n {\n if(!(x&(1<<i)))\n {\n c--;\n x=x|(1<<i);\n }\n i++;\n }\n return x;"
},
{
"code": null,
"e": 2674,
"s": 2672,
"text": "0"
},
{
"code": null,
"e": 2698,
"s": 2674,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 2714,
"s": 2698,
"text": "Easy greedy c++"
},
{
"code": null,
"e": 3424,
"s": 2714,
"text": "int minVal(int a, int b) {\n int cnt_a = __builtin_popcount(a);\n int cnt_b = __builtin_popcount(b);\n int num = 0;\n if(cnt_a >= cnt_b){\n num = a;\n int tmp = cnt_a-cnt_b, i=0;\n while(tmp){\n if((1&(num>>i)) == 1){\n num ^= (1<<i);\n tmp -= 1;\n }\n i += 1;\n }\n }\n else{\n num = a;\n int tmp = cnt_b-cnt_a, i=0;\n while(tmp){\n if((1&(num>>i)) == 0){\n num |= 1<<i;\n tmp -= 1;\n }\n i += 1;\n }\n }\n return num;\n }"
},
{
"code": null,
"e": 3426,
"s": 3424,
"text": "0"
},
{
"code": null,
"e": 3444,
"s": 3426,
"text": "Jyoti9 months ago"
},
{
"code": null,
"e": 3450,
"s": 3444,
"text": "Jyoti"
},
{
"code": null,
"e": 4116,
"s": 3450,
"text": "yeahhhhh.......first time i solved a hard level question without help. basically the idea is Traverse from the MSB in A to the LSB and if a bit is 1 then it also needs to be 1 in the answer in order to minimize the XOR but the number of bits set has to be equal to the number of set bits in B. So, when the count of set bits in the answer has reached the count of 1s in B then the rest of the bits have to be 0.but there will be some case where you will reached to LSB and count of 1s in answer is not equal to count of 1s in B, then start traversing from LSB to MSB and if the bit is 0 then make it 1 in the answer do this untill no of 1s in answer and B is equal."
},
{
"code": null,
"e": 4979,
"s": 4116,
"text": " int getSetBits(int b) { int count=0; while(b) { b = b & (b-1); count++; } return count; } int minVal(int a, int b) { // code here int setBits = getSetBits(b); //cout<<setbits<<\"hello\\n\";<br> int ans = 0; for (int i = 31; i >= 0; i--) { int mask = 1 << i; bool set = a & mask; if (set && setBits > 0) { ans |= (1 << i); setBits--; } } //cout<<setbits<<\"hi\\n\";<br> if(setBits>0) { for(int i=0;i<32;i++) { int mask = 1 << i; bool set = ans & mask; if(!set && setBits) { ans|=(1<<i); setbits--;=\"\" }<br=\"\"> } } return ans; }"
},
{
"code": null,
"e": 4981,
"s": 4979,
"text": "0"
},
{
"code": null,
"e": 5005,
"s": 4981,
"text": "wallflower10 months ago"
},
{
"code": null,
"e": 5016,
"s": 5005,
"text": "wallflower"
},
{
"code": null,
"e": 5067,
"s": 5016,
"text": "Java easy solution. https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5069,
"s": 5067,
"text": "0"
},
{
"code": null,
"e": 5087,
"s": 5069,
"text": "Motasim1 year ago"
},
{
"code": null,
"e": 5095,
"s": 5087,
"text": "Motasim"
},
{
"code": null,
"e": 5147,
"s": 5095,
"text": "C++ 0.1 sec Solution:https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5149,
"s": 5147,
"text": "0"
},
{
"code": null,
"e": 5168,
"s": 5149,
"text": "SHIV RAM1 year ago"
},
{
"code": null,
"e": 5177,
"s": 5168,
"text": "SHIV RAM"
},
{
"code": null,
"e": 5468,
"s": 5177,
"text": "Hi @moderators... Please change the the question description to : \" count of set bit in X is less than or equal to the count of set bits in B\" or change the back-end code, Since it is producing wrong output for the cases when number of set bits in B is greater than number of set bits in A."
},
{
"code": null,
"e": 5592,
"s": 5468,
"text": "Since the problem is tagged as Hard, it would be apt to change the back-end function which handles all the cases correctly."
},
{
"code": null,
"e": 5595,
"s": 5592,
"text": "-1"
},
{
"code": null,
"e": 5621,
"s": 5595,
"text": "Yash Khandelwal1 year ago"
},
{
"code": null,
"e": 5637,
"s": 5621,
"text": "Yash Khandelwal"
},
{
"code": null,
"e": 5682,
"s": 5637,
"text": "GFG is Known for its Incorrect Test cases!!."
},
{
"code": null,
"e": 5684,
"s": 5682,
"text": "0"
},
{
"code": null,
"e": 5708,
"s": 5684,
"text": "Akshansh Jain1 year ago"
},
{
"code": null,
"e": 5722,
"s": 5708,
"text": "Akshansh Jain"
},
{
"code": null,
"e": 6004,
"s": 5722,
"text": "For input A = 9, B = 7, the answer of online judge is 9. According to question, number of set bits in X should be equal to number of set bits in B. I assume set bits are the number of 1's in the binary representation of the decimal. Here, X=9 (as given by online judge), and B = 7."
},
{
"code": null,
"e": 6118,
"s": 6004,
"text": "9's binary representation = 1001, number of set bits = 2.7's binary representation = 111, number of set bits = 3."
},
{
"code": null,
"e": 6230,
"s": 6118,
"text": "So, 9 should not even be a possible answer here, let alone the correct answer, as number of bits are not equal."
},
{
"code": null,
"e": 6282,
"s": 6230,
"text": "Please correct me if I have misunderstood anything."
},
{
"code": null,
"e": 6428,
"s": 6282,
"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": 6464,
"s": 6428,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6474,
"s": 6464,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6484,
"s": 6474,
"text": "\nContest\n"
},
{
"code": null,
"e": 6547,
"s": 6484,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6695,
"s": 6547,
"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": 6903,
"s": 6695,
"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": 7009,
"s": 6903,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to label specific points in scatter plot in R ? - GeeksforGeeks
|
13 Jul, 2021
Scatter plots in the R programming language can be plotted to depict complex data easily and graphically. It is used to plot points, lines as well as curves. The points can be labeled using various methods available in base R and by incorporating some external packages.
The ggplot() method can be used in this package in order to simulate graph customizations and induce flexibility in graph plotting.
Syntax:
ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>()
The data can be binded into the scatter plot using the data attribute of the ggplot method. The mapping in the function can be induced using the aes() function to create aesthetic mapping, by filtering the variables to be plotted on the scatter plot. We can also specify how to depict different components in the graph, for instance, the x and y axes positions, the labels to assign to these points or characteristics such as size, shape, color, etc.
This method also allows the addition of various geoms- that is the components of graph. geom_point() is used for creation of scatter plot. geom_label() is used to understand the aesthetics specified to the ggplot.
Example:
R
library(ggplot2) # creating a data framedf <- data.frame(col1 = c(1:5), col2 = c(4:8), col3 = letters[1:5] )print ("Original DataFrame") # plotting the dataggplot(aes(x=col1, y=col2, label=col3), data=df) + geom_point() + geom_label()
Output
The plot() method in Base R is used to plotting the R objects, namely, lists or data frames.
Syntax:
plot(x, y, data , col)
Parameter :
x,y – The x and y coordinates of the points
col – The color to assign to the points. The color is specified using a character string.
data – The data frame points to be plotted in the graph
The text method can be used to customize the plots to add string names to the plotted points.
Syntax:
text (x, y , labels , data)
Parameter :
x, y – The coordinates of the points to label
labels – the vector of labels to be added
data – the data to use for plotting
Example:
R
# creating a data framedf <- data.frame(col1 = c(1:5), col2 = c(4:8), col3 = letters[1:5] ) print ("Original DataFrame") # plotting the dataplot(col1 ~col2 , col="red", cex=2, data= df ) # adding text to the datatext(col1 ~ col2, labels= col3 ,data=df , cex=0.9)
Output
kapoorsagar226
Picked
R-Charts
R-ggplot
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
Linear Discriminant Analysis in R Programming
How to filter R DataFrame by values in a column?
How to change Colors in ggplot2 Line Plot in R ?
How to import an Excel File into R ?
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 25122,
"s": 24851,
"text": "Scatter plots in the R programming language can be plotted to depict complex data easily and graphically. It is used to plot points, lines as well as curves. The points can be labeled using various methods available in base R and by incorporating some external packages."
},
{
"code": null,
"e": 25255,
"s": 25122,
"text": "The ggplot() method can be used in this package in order to simulate graph customizations and induce flexibility in graph plotting. "
},
{
"code": null,
"e": 25263,
"s": 25255,
"text": "Syntax:"
},
{
"code": null,
"e": 25333,
"s": 25263,
"text": "ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>()"
},
{
"code": null,
"e": 25784,
"s": 25333,
"text": "The data can be binded into the scatter plot using the data attribute of the ggplot method. The mapping in the function can be induced using the aes() function to create aesthetic mapping, by filtering the variables to be plotted on the scatter plot. We can also specify how to depict different components in the graph, for instance, the x and y axes positions, the labels to assign to these points or characteristics such as size, shape, color, etc."
},
{
"code": null,
"e": 25999,
"s": 25784,
"text": "This method also allows the addition of various geoms- that is the components of graph. geom_point() is used for creation of scatter plot. geom_label() is used to understand the aesthetics specified to the ggplot. "
},
{
"code": null,
"e": 26008,
"s": 25999,
"text": "Example:"
},
{
"code": null,
"e": 26010,
"s": 26008,
"text": "R"
},
{
"code": "library(ggplot2) # creating a data framedf <- data.frame(col1 = c(1:5), col2 = c(4:8), col3 = letters[1:5] )print (\"Original DataFrame\") # plotting the dataggplot(aes(x=col1, y=col2, label=col3), data=df) + geom_point() + geom_label()",
"e": 26301,
"s": 26010,
"text": null
},
{
"code": null,
"e": 26308,
"s": 26301,
"text": "Output"
},
{
"code": null,
"e": 26402,
"s": 26308,
"text": "The plot() method in Base R is used to plotting the R objects, namely, lists or data frames. "
},
{
"code": null,
"e": 26410,
"s": 26402,
"text": "Syntax:"
},
{
"code": null,
"e": 26433,
"s": 26410,
"text": "plot(x, y, data , col)"
},
{
"code": null,
"e": 26446,
"s": 26433,
"text": "Parameter : "
},
{
"code": null,
"e": 26490,
"s": 26446,
"text": "x,y – The x and y coordinates of the points"
},
{
"code": null,
"e": 26581,
"s": 26490,
"text": "col – The color to assign to the points. The color is specified using a character string. "
},
{
"code": null,
"e": 26637,
"s": 26581,
"text": "data – The data frame points to be plotted in the graph"
},
{
"code": null,
"e": 26732,
"s": 26637,
"text": "The text method can be used to customize the plots to add string names to the plotted points. "
},
{
"code": null,
"e": 26740,
"s": 26732,
"text": "Syntax:"
},
{
"code": null,
"e": 26769,
"s": 26740,
"text": "text (x, y , labels , data) "
},
{
"code": null,
"e": 26782,
"s": 26769,
"text": "Parameter : "
},
{
"code": null,
"e": 26828,
"s": 26782,
"text": "x, y – The coordinates of the points to label"
},
{
"code": null,
"e": 26871,
"s": 26828,
"text": "labels – the vector of labels to be added "
},
{
"code": null,
"e": 26907,
"s": 26871,
"text": "data – the data to use for plotting"
},
{
"code": null,
"e": 26916,
"s": 26907,
"text": "Example:"
},
{
"code": null,
"e": 26918,
"s": 26916,
"text": "R"
},
{
"code": "# creating a data framedf <- data.frame(col1 = c(1:5), col2 = c(4:8), col3 = letters[1:5] ) print (\"Original DataFrame\") # plotting the dataplot(col1 ~col2 , col=\"red\", cex=2, data= df ) # adding text to the datatext(col1 ~ col2, labels= col3 ,data=df , cex=0.9)",
"e": 27236,
"s": 26918,
"text": null
},
{
"code": null,
"e": 27247,
"s": 27240,
"text": "Output"
},
{
"code": null,
"e": 27266,
"s": 27251,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 27273,
"s": 27266,
"text": "Picked"
},
{
"code": null,
"e": 27282,
"s": 27273,
"text": "R-Charts"
},
{
"code": null,
"e": 27291,
"s": 27282,
"text": "R-ggplot"
},
{
"code": null,
"e": 27300,
"s": 27291,
"text": "R-Graphs"
},
{
"code": null,
"e": 27308,
"s": 27300,
"text": "R-plots"
},
{
"code": null,
"e": 27319,
"s": 27308,
"text": "R Language"
},
{
"code": null,
"e": 27417,
"s": 27319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27426,
"s": 27417,
"text": "Comments"
},
{
"code": null,
"e": 27439,
"s": 27426,
"text": "Old Comments"
},
{
"code": null,
"e": 27475,
"s": 27439,
"text": "Control Statements in R Programming"
},
{
"code": null,
"e": 27527,
"s": 27475,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27551,
"s": 27527,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 27586,
"s": 27551,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27624,
"s": 27586,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27661,
"s": 27624,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 27707,
"s": 27661,
"text": "Linear Discriminant Analysis in R Programming"
},
{
"code": null,
"e": 27756,
"s": 27707,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27805,
"s": 27756,
"text": "How to change Colors in ggplot2 Line Plot in R ?"
}
] |
Git Tutorial
|
Git is a version control system.
Git helps you keep track of code changes.
Git is used to collaborate on code.
In this tutorial, we will show you Git commands like this:
git --version
git version 2.30.2.windows.1
For new users, using the terminal view can seem a bit complicated. Don't worry! We will keep it really simple, and learning this way gives you a good grasp of how Git works.
In the code above, you can see commands (input) and output.
Lines like this are commands we input:
git --version
Lines like this are the output/response to our commands:
git version 2.30.2.windows.1
In general, lines with $ in front of it is input. These are the commands you can copy and run in your terminal.
Git and GitHub are different things.
In this tutorial you will understand what Git is and how to use it on the remote repository platforms, like GitHub.
You can choose, and change, which platform to focus on by clicking in the menu on the right:
Insert the missing part of the command to check which version of Git (if any)
is installed.
git
Start the Exercise
Test your Git skills with a quiz.
Start Git Quiz
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 33,
"s": 0,
"text": "Git is a version control system."
},
{
"code": null,
"e": 75,
"s": 33,
"text": "Git helps you keep track of code changes."
},
{
"code": null,
"e": 111,
"s": 75,
"text": "Git is used to collaborate on code."
},
{
"code": null,
"e": 170,
"s": 111,
"text": "In this tutorial, we will show you Git commands like this:"
},
{
"code": null,
"e": 213,
"s": 170,
"text": "git --version\ngit version 2.30.2.windows.1"
},
{
"code": null,
"e": 387,
"s": 213,
"text": "For new users, using the terminal view can seem a bit complicated. Don't worry! We will keep it really simple, and learning this way gives you a good grasp of how Git works."
},
{
"code": null,
"e": 447,
"s": 387,
"text": "In the code above, you can see commands (input) and output."
},
{
"code": null,
"e": 486,
"s": 447,
"text": "Lines like this are commands we input:"
},
{
"code": null,
"e": 500,
"s": 486,
"text": "git --version"
},
{
"code": null,
"e": 557,
"s": 500,
"text": "Lines like this are the output/response to our commands:"
},
{
"code": null,
"e": 586,
"s": 557,
"text": "git version 2.30.2.windows.1"
},
{
"code": null,
"e": 698,
"s": 586,
"text": "In general, lines with $ in front of it is input. These are the commands you can copy and run in your terminal."
},
{
"code": null,
"e": 735,
"s": 698,
"text": "Git and GitHub are different things."
},
{
"code": null,
"e": 851,
"s": 735,
"text": "In this tutorial you will understand what Git is and how to use it on the remote repository platforms, like GitHub."
},
{
"code": null,
"e": 944,
"s": 851,
"text": "You can choose, and change, which platform to focus on by clicking in the menu on the right:"
},
{
"code": null,
"e": 1037,
"s": 944,
"text": "Insert the missing part of the command to check which version of Git (if any) \nis installed."
},
{
"code": null,
"e": 1043,
"s": 1037,
"text": "git \n"
},
{
"code": null,
"e": 1063,
"s": 1043,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 1097,
"s": 1063,
"text": "Test your Git skills with a quiz."
},
{
"code": null,
"e": 1112,
"s": 1097,
"text": "Start Git Quiz"
},
{
"code": null,
"e": 1145,
"s": 1112,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1187,
"s": 1145,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1294,
"s": 1187,
"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": 1313,
"s": 1294,
"text": "[email protected]"
}
] |
How to use the return statement in C#?
|
The return statement is used to return value. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.
The following is an example to learn about the usage of return statement in C#. Here, we are finding the factorial of a number and returning the result using the return statement.
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;
Here is the complete example.
Live Demo
using System;
namespace Demo {
class Factorial {
public int display(int n) {
int res = 1;
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;
}
static void Main(string[] args) {
int value = 5;
int ret;
Factorial fact = new Factorial();
ret = fact.display(value);
Console.WriteLine("Value is : {0}", ret );
Console.ReadLine();
}
}
}
Value is : 120
|
[
{
"code": null,
"e": 1395,
"s": 1062,
"text": "The return statement is used to return value. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program."
},
{
"code": null,
"e": 1575,
"s": 1395,
"text": "The following is an example to learn about the usage of return statement in C#. Here, we are finding the factorial of a number and returning the result using the return statement."
},
{
"code": null,
"e": 1638,
"s": 1575,
"text": "while (n != 1) {\n res = res * n;\n n = n - 1;\n}\nreturn res;"
},
{
"code": null,
"e": 1668,
"s": 1638,
"text": "Here is the complete example."
},
{
"code": null,
"e": 1679,
"s": 1668,
"text": " Live Demo"
},
{
"code": null,
"e": 2160,
"s": 1679,
"text": "using System;\nnamespace Demo {\n class Factorial {\n public int display(int n) {\n int res = 1;\n while (n != 1) {\n res = res * n;\n n = n - 1;\n }\n return res;\n }\n static void Main(string[] args) {\n int value = 5;\n int ret;\n Factorial fact = new Factorial();\n ret = fact.display(value);\n Console.WriteLine(\"Value is : {0}\", ret );\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2175,
"s": 2160,
"text": "Value is : 120"
}
] |
Input Iterators in C++
|
In this tutorial, we will be discussing a program to understand input iterators in C++.
Input iterators are one of the five iterators in STL being the weakest and simplest of all. They are mostly used in serial input operations where each value is read one and then the iterator moves to the next one.
Live Demo
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v1 = { 1, 2, 3, 4, 5 };
//declaring iterator
vector<int>::iterator i1;
for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
//looping over elements via iterator
cout << (*i1) << " ";
}
return 0;
}
1 2 3 4 5
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to understand input iterators in C++."
},
{
"code": null,
"e": 1364,
"s": 1150,
"text": "Input iterators are one of the five iterators in STL being the weakest and simplest of all. They are mostly used in serial input operations where each value is read one and then the iterator moves to the next one."
},
{
"code": null,
"e": 1375,
"s": 1364,
"text": " Live Demo"
},
{
"code": null,
"e": 1678,
"s": 1375,
"text": "#include <iostream>\n#include <vector>\nusing namespace std;\nint main(){\n vector<int> v1 = { 1, 2, 3, 4, 5 };\n //declaring iterator\n vector<int>::iterator i1;\n for (i1 = v1.begin(); i1 != v1.end(); ++i1) {\n //looping over elements via iterator\n cout << (*i1) << \" \";\n }\n return 0;\n}"
},
{
"code": null,
"e": 1688,
"s": 1678,
"text": "1 2 3 4 5"
}
] |
Relational Operators in C++
|
In C++ Programming, the values stored in two variables can be compared using following operators and relation between them can be determined. These operators are called relational operators. Various C++ relational operators available are −
You can use these operators for checking the relationship between the operands. These operators are mostly used in conditional statements and loops to find a relation between 2 operands and act accordingly. For example,
#include<iostream>
using namespace std;
int main() {
int a = 3, b = 2;
if(a < b) {
cout<< a << " is less than " << b;
}
else if(a > b) {
cout<< a << " is greater than " << b;
}
else if(a == b){
cout << a << " is equal to " << b;
}
return 0;
}
This will give the output −
3 is greater than 2
|
[
{
"code": null,
"e": 1302,
"s": 1062,
"text": "In C++ Programming, the values stored in two variables can be compared using following operators and relation between them can be determined. These operators are called relational operators. Various C++ relational operators available are −"
},
{
"code": null,
"e": 1522,
"s": 1302,
"text": "You can use these operators for checking the relationship between the operands. These operators are mostly used in conditional statements and loops to find a relation between 2 operands and act accordingly. For example,"
},
{
"code": null,
"e": 1807,
"s": 1522,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int a = 3, b = 2;\n if(a < b) {\n cout<< a << \" is less than \" << b;\n }\n else if(a > b) {\n cout<< a << \" is greater than \" << b;\n }\n else if(a == b){\n cout << a << \" is equal to \" << b;\n }\n return 0;\n}"
},
{
"code": null,
"e": 1835,
"s": 1807,
"text": "This will give the output −"
},
{
"code": null,
"e": 1855,
"s": 1835,
"text": "3 is greater than 2"
}
] |
How to connect to the Azure subscription using Azure CLI in PowerShell?
|
To connect to the specific azure subscription using Az CLI we need to use “Az account set” command but before using this command make sure you are connected with the Azure cloud using “az login” account.
az account set --subscription 'subscription name or id'
You can also use -s instead of --subscription.
az account set -s 'subscription name or id'
To check if the subscription is set properly, use the below command.
PS C:\> az account show -otable
|
[
{
"code": null,
"e": 1266,
"s": 1062,
"text": "To connect to the specific azure subscription using Az CLI we need to use “Az account set” command but before using this command make sure you are connected with the Azure cloud using “az login” account."
},
{
"code": null,
"e": 1322,
"s": 1266,
"text": "az account set --subscription 'subscription name or id'"
},
{
"code": null,
"e": 1369,
"s": 1322,
"text": "You can also use -s instead of --subscription."
},
{
"code": null,
"e": 1413,
"s": 1369,
"text": "az account set -s 'subscription name or id'"
},
{
"code": null,
"e": 1482,
"s": 1413,
"text": "To check if the subscription is set properly, use the below command."
},
{
"code": null,
"e": 1514,
"s": 1482,
"text": "PS C:\\> az account show -otable"
}
] |
equals() and hashCode() methods in Java
|
11 Oct, 2019
Java.lang.object has two very important methods defined: public boolean equals(Object obj) and public int hashCode().
equals() method
In java equals() method is used to compare equality of two Objects. The equality can be compared in two ways:
Shallow comparison: The default implementation of equals method is defined in Java.lang.Object class which simply checks if two Object references (say x and y) refer to the same Object. i.e. It checks if x == y. Since Object class has no data members that define its state, it is also known as shallow comparison.
Deep Comparison: Suppose a class provides its own implementation of equals() method in order to compare the Objects of that class w.r.t state of the Objects. That means data members (i.e. fields) of Objects are to be compared with one another. Such Comparison based on data members is known as deep comparison.
Syntax :
public boolean equals (Object obj)
// This method checks if some other Object
// passed to it as an argument is equal to
// the Object on which it is invoked.
Some principles of equals() method of Object class : If some other object is equal to a given object, then it follows these rules:
Reflexive : for any reference value a, a.equals(a) should return true.
Symmetric : for any reference values a and b, if a.equals(b) should return true then b.equals(a) must return true.
Transitive : for any reference values a, b, and c, if a.equals(b) returns true and b.equals(c) returns true, then a.equals(c) should return true.
Consistent : for any reference values a and b, multiple invocations of a.equals(b) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
Note: For any non-null reference value a, a.equals(null) should return false.
// Java program to illustrate // how hashCode() and equals() methods workimport java.io.*; class Geek { public String name; public int id; Geek(String name, int id) { this.name = name; this.id = id; } @Override public boolean equals(Object obj) { // checking if both the object references are // referring to the same object. if(this == obj) return true; // it checks if the argument is of the // type Geek by comparing the classes // of the passed argument and this object. // if(!(obj instanceof Geek)) return false; ---> avoid. if(obj == null || obj.getClass()!= this.getClass()) return false; // type casting of the argument. Geek geek = (Geek) obj; // comparing the state of argument with // the state of 'this' Object. return (geek.name == this.name && geek.id == this.id); } @Override public int hashCode() { // We are returning the Geek_id // as a hashcode value. // we can also return some // other calculated value or may // be memory address of the // Object on which it is invoked. // it depends on how you implement // hashCode() method. return this.id; } } //Driver codeclass GFG{ public static void main (String[] args) { // creating the Objects of Geek class. Geek g1 = new Geek("aa", 1); Geek g2 = new Geek("aa", 1); // comparing above created Objects. if(g1.hashCode() == g2.hashCode()) { if(g1.equals(g2)) System.out.println("Both Objects are equal. "); else System.out.println("Both Objects are not equal. "); } else System.out.println("Both Objects are not equal. "); } }
Output:
Both Objects are equal.
In above example see the line:
// if(!(obj instanceof Geek)) return false;--> avoid.-->(a)
We’ve used this line instead of above line:
if(obj == null || obj.getClass()!= this.getClass()) return false; --->(y)
Here, First we are comparing the hashCode on both Objects (i.e. g1 and g2) and if same hashcode is generated by both the Objects that does not mean that they are equal as hashcode can be same for different Objects also, if they have the same id (in this case). So if get the generated hashcode values are equal for both the Objects, after that we compare the both these Objects w.r.t their state for that we override equals(Object) method within the class. And if both Objects have the same state according to the equals(Object) method then they are equal otherwise not. And it would be better w.r.t. performance if different Objects generates different hashcode value.
Reason : Reference obj can also refer to the Object of subclass of Geek. Line (b) ensures that it will return false if passed argument is an Object of subclass of class Geek. But the instanceof operator condition does not return false if it found the passed argument is a subclass of the class Geek. Read InstanceOf operator.
hashCode() method
It returns the hashcode value as an Integer. Hashcode value is mostly used in hashing based collections like HashMap, HashSet, HashTable....etc. This method must be overridden in every class which overrides equals() method.Syntax :
public int hashCode()
// This method returns the hash code value
// for the object on which this method is invoked.
The general contract of hashCode is:
During the execution of the application, if hashCode() is invoked more than once on the same Object then it must consistently return the same Integer value, provided no information used in equals(Object) comparison on the Object is modified. It is not necessary that this Integer value to be remained same from one execution of the application to another execution of the same application.
If two Objects are equal, according to the equals(Object) method, then hashCode() method must produce the same Integer on each of the two Objects.
If two Objects are unequal, according to the equals(Object) method, It is not necessary the Integer value produced by hashCode() method on each of the two Objects will be distinct. It can be same but producing the distinct Integer on each of the two Objects is better for improving the performance of hashing based Collections like HashMap, HashTable...etc.
Note: Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.
Related link : Overriding equal in JavaReference: JavaRanch
This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
akabhishek881
Akanksha_Rai
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 170,
"s": 52,
"text": "Java.lang.object has two very important methods defined: public boolean equals(Object obj) and public int hashCode()."
},
{
"code": null,
"e": 186,
"s": 170,
"text": "equals() method"
},
{
"code": null,
"e": 296,
"s": 186,
"text": "In java equals() method is used to compare equality of two Objects. The equality can be compared in two ways:"
},
{
"code": null,
"e": 610,
"s": 296,
"text": "Shallow comparison: The default implementation of equals method is defined in Java.lang.Object class which simply checks if two Object references (say x and y) refer to the same Object. i.e. It checks if x == y. Since Object class has no data members that define its state, it is also known as shallow comparison."
},
{
"code": null,
"e": 921,
"s": 610,
"text": "Deep Comparison: Suppose a class provides its own implementation of equals() method in order to compare the Objects of that class w.r.t state of the Objects. That means data members (i.e. fields) of Objects are to be compared with one another. Such Comparison based on data members is known as deep comparison."
},
{
"code": null,
"e": 930,
"s": 921,
"text": "Syntax :"
},
{
"code": null,
"e": 1093,
"s": 930,
"text": "public boolean equals (Object obj)\n\n// This method checks if some other Object\n// passed to it as an argument is equal to \n// the Object on which it is invoked.\n"
},
{
"code": null,
"e": 1224,
"s": 1093,
"text": "Some principles of equals() method of Object class : If some other object is equal to a given object, then it follows these rules:"
},
{
"code": null,
"e": 1295,
"s": 1224,
"text": "Reflexive : for any reference value a, a.equals(a) should return true."
},
{
"code": null,
"e": 1410,
"s": 1295,
"text": "Symmetric : for any reference values a and b, if a.equals(b) should return true then b.equals(a) must return true."
},
{
"code": null,
"e": 1556,
"s": 1410,
"text": "Transitive : for any reference values a, b, and c, if a.equals(b) returns true and b.equals(c) returns true, then a.equals(c) should return true."
},
{
"code": null,
"e": 1772,
"s": 1556,
"text": "Consistent : for any reference values a and b, multiple invocations of a.equals(b) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified."
},
{
"code": null,
"e": 1850,
"s": 1772,
"text": "Note: For any non-null reference value a, a.equals(null) should return false."
},
{
"code": "// Java program to illustrate // how hashCode() and equals() methods workimport java.io.*; class Geek { public String name; public int id; Geek(String name, int id) { this.name = name; this.id = id; } @Override public boolean equals(Object obj) { // checking if both the object references are // referring to the same object. if(this == obj) return true; // it checks if the argument is of the // type Geek by comparing the classes // of the passed argument and this object. // if(!(obj instanceof Geek)) return false; ---> avoid. if(obj == null || obj.getClass()!= this.getClass()) return false; // type casting of the argument. Geek geek = (Geek) obj; // comparing the state of argument with // the state of 'this' Object. return (geek.name == this.name && geek.id == this.id); } @Override public int hashCode() { // We are returning the Geek_id // as a hashcode value. // we can also return some // other calculated value or may // be memory address of the // Object on which it is invoked. // it depends on how you implement // hashCode() method. return this.id; } } //Driver codeclass GFG{ public static void main (String[] args) { // creating the Objects of Geek class. Geek g1 = new Geek(\"aa\", 1); Geek g2 = new Geek(\"aa\", 1); // comparing above created Objects. if(g1.hashCode() == g2.hashCode()) { if(g1.equals(g2)) System.out.println(\"Both Objects are equal. \"); else System.out.println(\"Both Objects are not equal. \"); } else System.out.println(\"Both Objects are not equal. \"); } }",
"e": 3825,
"s": 1850,
"text": null
},
{
"code": null,
"e": 3833,
"s": 3825,
"text": "Output:"
},
{
"code": null,
"e": 3858,
"s": 3833,
"text": "Both Objects are equal.\n"
},
{
"code": null,
"e": 3889,
"s": 3858,
"text": "In above example see the line:"
},
{
"code": null,
"e": 3949,
"s": 3889,
"text": "// if(!(obj instanceof Geek)) return false;--> avoid.-->(a)"
},
{
"code": null,
"e": 3993,
"s": 3949,
"text": "We’ve used this line instead of above line:"
},
{
"code": null,
"e": 4067,
"s": 3993,
"text": "if(obj == null || obj.getClass()!= this.getClass()) return false; --->(y)"
},
{
"code": null,
"e": 4737,
"s": 4067,
"text": "Here, First we are comparing the hashCode on both Objects (i.e. g1 and g2) and if same hashcode is generated by both the Objects that does not mean that they are equal as hashcode can be same for different Objects also, if they have the same id (in this case). So if get the generated hashcode values are equal for both the Objects, after that we compare the both these Objects w.r.t their state for that we override equals(Object) method within the class. And if both Objects have the same state according to the equals(Object) method then they are equal otherwise not. And it would be better w.r.t. performance if different Objects generates different hashcode value."
},
{
"code": null,
"e": 5063,
"s": 4737,
"text": "Reason : Reference obj can also refer to the Object of subclass of Geek. Line (b) ensures that it will return false if passed argument is an Object of subclass of class Geek. But the instanceof operator condition does not return false if it found the passed argument is a subclass of the class Geek. Read InstanceOf operator."
},
{
"code": null,
"e": 5081,
"s": 5063,
"text": "hashCode() method"
},
{
"code": null,
"e": 5313,
"s": 5081,
"text": "It returns the hashcode value as an Integer. Hashcode value is mostly used in hashing based collections like HashMap, HashSet, HashTable....etc. This method must be overridden in every class which overrides equals() method.Syntax :"
},
{
"code": null,
"e": 5432,
"s": 5313,
"text": "public int hashCode()\n\n// This method returns the hash code value \n// for the object on which this method is invoked.\n"
},
{
"code": null,
"e": 5469,
"s": 5432,
"text": "The general contract of hashCode is:"
},
{
"code": null,
"e": 5859,
"s": 5469,
"text": "During the execution of the application, if hashCode() is invoked more than once on the same Object then it must consistently return the same Integer value, provided no information used in equals(Object) comparison on the Object is modified. It is not necessary that this Integer value to be remained same from one execution of the application to another execution of the same application."
},
{
"code": null,
"e": 6006,
"s": 5859,
"text": "If two Objects are equal, according to the equals(Object) method, then hashCode() method must produce the same Integer on each of the two Objects."
},
{
"code": null,
"e": 6364,
"s": 6006,
"text": "If two Objects are unequal, according to the equals(Object) method, It is not necessary the Integer value produced by hashCode() method on each of the two Objects will be distinct. It can be same but producing the distinct Integer on each of the two Objects is better for improving the performance of hashing based Collections like HashMap, HashTable...etc."
},
{
"code": null,
"e": 6505,
"s": 6364,
"text": "Note: Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes."
},
{
"code": null,
"e": 6565,
"s": 6505,
"text": "Related link : Overriding equal in JavaReference: JavaRanch"
},
{
"code": null,
"e": 6867,
"s": 6565,
"text": "This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6992,
"s": 6867,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7006,
"s": 6992,
"text": "akabhishek881"
},
{
"code": null,
"e": 7019,
"s": 7006,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 7024,
"s": 7019,
"text": "Java"
},
{
"code": null,
"e": 7029,
"s": 7024,
"text": "Java"
},
{
"code": null,
"e": 7127,
"s": 7029,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7178,
"s": 7127,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 7209,
"s": 7178,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 7239,
"s": 7209,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 7254,
"s": 7239,
"text": "Stream In Java"
},
{
"code": null,
"e": 7272,
"s": 7254,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 7292,
"s": 7272,
"text": "Collections in Java"
},
{
"code": null,
"e": 7316,
"s": 7292,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 7348,
"s": 7316,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 7360,
"s": 7348,
"text": "Set in Java"
}
] |
Gated Recurrent Unit Networks
|
23 May, 2022
Prerequisites: Recurrent Neural Networks, Long Short Term Memory Networks
To solve the Vanishing-Exploding gradients problem often encountered during the operation of a basic Recurrent Neural Network, many variations were developed. One of the most famous variations is the Long Short Term Memory Network(LSTM). One of the lesser-known but equally effective variations is the Gated Recurrent Unit Network(GRU).
Unlike LSTM, it consists of only three gates and does not maintain an Internal Cell State. The information which is stored in the Internal Cell State in an LSTM recurrent unit is incorporated into the hidden state of the Gated Recurrent Unit. This collective information is passed onto the next Gated Recurrent Unit. The different gates of a GRU are as described below:-
Update Gate(z): It determines how much of the past knowledge needs to be passed along into the future. It is analogous to the Output Gate in an LSTM recurrent unit.Reset Gate(r): It determines how much of the past knowledge to forget. It is analogous to the combination of the Input Gate and the Forget Gate in an LSTM recurrent unit.Current Memory Gate(): It is often overlooked during a typical discussion on Gated Recurrent Unit Network. It is incorporated into the Reset Gate just like the Input Modulation Gate is a sub-part of the Input Gate and is used to introduce some non-linearity into the input and to also make the input Zero-mean. Another reason to make it a sub-part of the Reset gate is to reduce the effect that previous information has on the current information that is being passed into the future.
Update Gate(z): It determines how much of the past knowledge needs to be passed along into the future. It is analogous to the Output Gate in an LSTM recurrent unit.
Reset Gate(r): It determines how much of the past knowledge to forget. It is analogous to the combination of the Input Gate and the Forget Gate in an LSTM recurrent unit.
Current Memory Gate(): It is often overlooked during a typical discussion on Gated Recurrent Unit Network. It is incorporated into the Reset Gate just like the Input Modulation Gate is a sub-part of the Input Gate and is used to introduce some non-linearity into the input and to also make the input Zero-mean. Another reason to make it a sub-part of the Reset gate is to reduce the effect that previous information has on the current information that is being passed into the future.
The basic work-flow of a Gated Recurrent Unit Network is similar to that of a basic Recurrent Neural Network when illustrated, the main difference between the two is in the internal working within each recurrent unit as Gated Recurrent Unit networks consist of gates which modulate the current input and the previous hidden state.
Working of a Gated Recurrent Unit:
Take input the current input and the previous hidden state as vectors.
Calculate the values of the three different gates by following the steps given below:- For each gate, calculate the parameterized current input and previously hidden state vectors by performing element-wise multiplication (Hadamard Product) between the concerned vector and the respective weights for each gate.Apply the respective activation function for each gate element-wise on the parameterized vectors. Below given is the list of the gates with the activation function to be applied for the gate.
For each gate, calculate the parameterized current input and previously hidden state vectors by performing element-wise multiplication (Hadamard Product) between the concerned vector and the respective weights for each gate.Apply the respective activation function for each gate element-wise on the parameterized vectors. Below given is the list of the gates with the activation function to be applied for the gate.
For each gate, calculate the parameterized current input and previously hidden state vectors by performing element-wise multiplication (Hadamard Product) between the concerned vector and the respective weights for each gate.
Apply the respective activation function for each gate element-wise on the parameterized vectors. Below given is the list of the gates with the activation function to be applied for the gate.
Update Gate : Sigmoid Function
Reset Gate : Sigmoid Function
The process of calculating the Current Memory Gate is a little different. First, the Hadamard product of the Reset Gate and the previously hidden state vector is calculated. Then this vector is parameterized and then added to the parameterized current input vector.
To calculate the current hidden state, first, a vector of ones and the same dimensions as that of the input is defined. This vector will be called ones and mathematically be denoted by 1. First, calculate the Hadamard Product of the update gate and the previously hidden state vector. Then generate a new vector by subtracting the update gate from ones and then calculate the Hadamard Product of the newly generated vector with the current memory gate. Finally, add the two vectors to get the currently hidden state vector.The above-stated working is stated as below:-
The above-stated working is stated as below:-
Note that the blue circles denote element-wise multiplication. The positive sign in the circle denotes vector addition while the negative sign denotes vector subtraction(vector addition with negative value). The weight matrix W contains different weights for the current input vector and the previous hidden state for each gate.
Just like Recurrent Neural Networks, a GRU network also generates an output at each time step and this output is used to train the network using gradient descent.
Note that just like the workflow, the training process for a GRU network is also diagrammatically similar to that of a basic Recurrent Neural Network and differs only in the internal working of each recurrent unit.
The Back-Propagation Through Time Algorithm for a Gated Recurrent Unit Network is similar to that of a Long Short Term Memory Network and differs only in the differential chain formation.
Let be the predicted output at each time step and be the actual output at each time step. Then the error at each time step is given by:-
The total error is thus given by the summation of errors at all time steps.
Similarly, the value can be calculated as the summation of the gradients at each time step.
Using the chain rule and using the fact that is a function of and which indeed is a function of , the following expression arises:-
Thus the total error gradient is given by the following:-
Note that the gradient equation involves a chain of which looks similar to that of a basic Recurrent Neural Network but this equation works differently because of the internal workings of the derivatives of .
How do Gated Recurrent Units solve the problem of vanishing gradients?
The value of the gradients is controlled by the chain of derivatives starting from . Recall the expression for :-
Using the above expression, the value for is:-
Recall the expression for :-
Using the above expression to calculate the value of :-
Since both the update and reset gate use the sigmoid function as their activation function, both can take values either 0 or 1.
Case 1(z = 1):
In this case, irrespective of the value of , the term is equal to z which in turn is equal to 1.
Case 2A(z=0 and r=0):
In this case, the term is equal to 0.
Case 2B(z=0 and r=1):
In this case, the term is equal to . This value is controlled by the weight matrix which is trainable and thus the network learns to adjust the weights in such a way that the term comes closer to 1.
Thus the Back-Propagation Through Time algorithm adjusts the respective weights in such a manner that the value of the chain of derivatives is as close to 1 as possible.
sooda367
23620uday2021
ramankumar41
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Support Vector Machine Algorithm
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 103,
"s": 28,
"text": "Prerequisites: Recurrent Neural Networks, Long Short Term Memory Networks "
},
{
"code": null,
"e": 441,
"s": 103,
"text": "To solve the Vanishing-Exploding gradients problem often encountered during the operation of a basic Recurrent Neural Network, many variations were developed. One of the most famous variations is the Long Short Term Memory Network(LSTM). One of the lesser-known but equally effective variations is the Gated Recurrent Unit Network(GRU). "
},
{
"code": null,
"e": 813,
"s": 441,
"text": "Unlike LSTM, it consists of only three gates and does not maintain an Internal Cell State. The information which is stored in the Internal Cell State in an LSTM recurrent unit is incorporated into the hidden state of the Gated Recurrent Unit. This collective information is passed onto the next Gated Recurrent Unit. The different gates of a GRU are as described below:- "
},
{
"code": null,
"e": 1632,
"s": 813,
"text": "Update Gate(z): It determines how much of the past knowledge needs to be passed along into the future. It is analogous to the Output Gate in an LSTM recurrent unit.Reset Gate(r): It determines how much of the past knowledge to forget. It is analogous to the combination of the Input Gate and the Forget Gate in an LSTM recurrent unit.Current Memory Gate(): It is often overlooked during a typical discussion on Gated Recurrent Unit Network. It is incorporated into the Reset Gate just like the Input Modulation Gate is a sub-part of the Input Gate and is used to introduce some non-linearity into the input and to also make the input Zero-mean. Another reason to make it a sub-part of the Reset gate is to reduce the effect that previous information has on the current information that is being passed into the future."
},
{
"code": null,
"e": 1797,
"s": 1632,
"text": "Update Gate(z): It determines how much of the past knowledge needs to be passed along into the future. It is analogous to the Output Gate in an LSTM recurrent unit."
},
{
"code": null,
"e": 1968,
"s": 1797,
"text": "Reset Gate(r): It determines how much of the past knowledge to forget. It is analogous to the combination of the Input Gate and the Forget Gate in an LSTM recurrent unit."
},
{
"code": null,
"e": 2453,
"s": 1968,
"text": "Current Memory Gate(): It is often overlooked during a typical discussion on Gated Recurrent Unit Network. It is incorporated into the Reset Gate just like the Input Modulation Gate is a sub-part of the Input Gate and is used to introduce some non-linearity into the input and to also make the input Zero-mean. Another reason to make it a sub-part of the Reset gate is to reduce the effect that previous information has on the current information that is being passed into the future."
},
{
"code": null,
"e": 2785,
"s": 2453,
"text": "The basic work-flow of a Gated Recurrent Unit Network is similar to that of a basic Recurrent Neural Network when illustrated, the main difference between the two is in the internal working within each recurrent unit as Gated Recurrent Unit networks consist of gates which modulate the current input and the previous hidden state. "
},
{
"code": null,
"e": 2821,
"s": 2785,
"text": "Working of a Gated Recurrent Unit: "
},
{
"code": null,
"e": 2893,
"s": 2821,
"text": "Take input the current input and the previous hidden state as vectors. "
},
{
"code": null,
"e": 3396,
"s": 2893,
"text": "Calculate the values of the three different gates by following the steps given below:- For each gate, calculate the parameterized current input and previously hidden state vectors by performing element-wise multiplication (Hadamard Product) between the concerned vector and the respective weights for each gate.Apply the respective activation function for each gate element-wise on the parameterized vectors. Below given is the list of the gates with the activation function to be applied for the gate."
},
{
"code": null,
"e": 3812,
"s": 3396,
"text": "For each gate, calculate the parameterized current input and previously hidden state vectors by performing element-wise multiplication (Hadamard Product) between the concerned vector and the respective weights for each gate.Apply the respective activation function for each gate element-wise on the parameterized vectors. Below given is the list of the gates with the activation function to be applied for the gate."
},
{
"code": null,
"e": 4037,
"s": 3812,
"text": "For each gate, calculate the parameterized current input and previously hidden state vectors by performing element-wise multiplication (Hadamard Product) between the concerned vector and the respective weights for each gate."
},
{
"code": null,
"e": 4229,
"s": 4037,
"text": "Apply the respective activation function for each gate element-wise on the parameterized vectors. Below given is the list of the gates with the activation function to be applied for the gate."
},
{
"code": null,
"e": 4291,
"s": 4229,
"text": "Update Gate : Sigmoid Function\nReset Gate : Sigmoid Function"
},
{
"code": null,
"e": 4558,
"s": 4291,
"text": "The process of calculating the Current Memory Gate is a little different. First, the Hadamard product of the Reset Gate and the previously hidden state vector is calculated. Then this vector is parameterized and then added to the parameterized current input vector. "
},
{
"code": null,
"e": 5128,
"s": 4558,
"text": "To calculate the current hidden state, first, a vector of ones and the same dimensions as that of the input is defined. This vector will be called ones and mathematically be denoted by 1. First, calculate the Hadamard Product of the update gate and the previously hidden state vector. Then generate a new vector by subtracting the update gate from ones and then calculate the Hadamard Product of the newly generated vector with the current memory gate. Finally, add the two vectors to get the currently hidden state vector.The above-stated working is stated as below:- "
},
{
"code": null,
"e": 5175,
"s": 5128,
"text": "The above-stated working is stated as below:- "
},
{
"code": null,
"e": 5505,
"s": 5175,
"text": "Note that the blue circles denote element-wise multiplication. The positive sign in the circle denotes vector addition while the negative sign denotes vector subtraction(vector addition with negative value). The weight matrix W contains different weights for the current input vector and the previous hidden state for each gate. "
},
{
"code": null,
"e": 5670,
"s": 5505,
"text": "Just like Recurrent Neural Networks, a GRU network also generates an output at each time step and this output is used to train the network using gradient descent. "
},
{
"code": null,
"e": 5886,
"s": 5670,
"text": "Note that just like the workflow, the training process for a GRU network is also diagrammatically similar to that of a basic Recurrent Neural Network and differs only in the internal working of each recurrent unit. "
},
{
"code": null,
"e": 6075,
"s": 5886,
"text": "The Back-Propagation Through Time Algorithm for a Gated Recurrent Unit Network is similar to that of a Long Short Term Memory Network and differs only in the differential chain formation. "
},
{
"code": null,
"e": 6213,
"s": 6075,
"text": "Let be the predicted output at each time step and be the actual output at each time step. Then the error at each time step is given by:- "
},
{
"code": null,
"e": 6290,
"s": 6213,
"text": "The total error is thus given by the summation of errors at all time steps. "
},
{
"code": null,
"e": 6383,
"s": 6290,
"text": "Similarly, the value can be calculated as the summation of the gradients at each time step. "
},
{
"code": null,
"e": 6516,
"s": 6383,
"text": "Using the chain rule and using the fact that is a function of and which indeed is a function of , the following expression arises:- "
},
{
"code": null,
"e": 6575,
"s": 6516,
"text": "Thus the total error gradient is given by the following:- "
},
{
"code": null,
"e": 6785,
"s": 6575,
"text": "Note that the gradient equation involves a chain of which looks similar to that of a basic Recurrent Neural Network but this equation works differently because of the internal workings of the derivatives of . "
},
{
"code": null,
"e": 6857,
"s": 6785,
"text": "How do Gated Recurrent Units solve the problem of vanishing gradients? "
},
{
"code": null,
"e": 6972,
"s": 6857,
"text": "The value of the gradients is controlled by the chain of derivatives starting from . Recall the expression for :- "
},
{
"code": null,
"e": 7020,
"s": 6972,
"text": "Using the above expression, the value for is:- "
},
{
"code": null,
"e": 7050,
"s": 7020,
"text": "Recall the expression for :- "
},
{
"code": null,
"e": 7107,
"s": 7050,
"text": "Using the above expression to calculate the value of :- "
},
{
"code": null,
"e": 7236,
"s": 7107,
"text": "Since both the update and reset gate use the sigmoid function as their activation function, both can take values either 0 or 1. "
},
{
"code": null,
"e": 7252,
"s": 7236,
"text": "Case 1(z = 1): "
},
{
"code": null,
"e": 7350,
"s": 7252,
"text": "In this case, irrespective of the value of , the term is equal to z which in turn is equal to 1. "
},
{
"code": null,
"e": 7373,
"s": 7350,
"text": "Case 2A(z=0 and r=0): "
},
{
"code": null,
"e": 7412,
"s": 7373,
"text": "In this case, the term is equal to 0. "
},
{
"code": null,
"e": 7435,
"s": 7412,
"text": "Case 2B(z=0 and r=1): "
},
{
"code": null,
"e": 7635,
"s": 7435,
"text": "In this case, the term is equal to . This value is controlled by the weight matrix which is trainable and thus the network learns to adjust the weights in such a way that the term comes closer to 1. "
},
{
"code": null,
"e": 7806,
"s": 7635,
"text": "Thus the Back-Propagation Through Time algorithm adjusts the respective weights in such a manner that the value of the chain of derivatives is as close to 1 as possible. "
},
{
"code": null,
"e": 7815,
"s": 7806,
"text": "sooda367"
},
{
"code": null,
"e": 7829,
"s": 7815,
"text": "23620uday2021"
},
{
"code": null,
"e": 7842,
"s": 7829,
"text": "ramankumar41"
},
{
"code": null,
"e": 7859,
"s": 7842,
"text": "Machine Learning"
},
{
"code": null,
"e": 7866,
"s": 7859,
"text": "Python"
},
{
"code": null,
"e": 7883,
"s": 7866,
"text": "Machine Learning"
},
{
"code": null,
"e": 7981,
"s": 7883,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8004,
"s": 7981,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 8044,
"s": 8004,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 8068,
"s": 8044,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 8106,
"s": 8068,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 8139,
"s": 8106,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 8167,
"s": 8139,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 8189,
"s": 8167,
"text": "Python map() function"
},
{
"code": null,
"e": 8239,
"s": 8189,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 8257,
"s": 8239,
"text": "Python Dictionary"
}
] |
Program that allows integer input only
|
05 Jun, 2022
Given an input value N, the task is to allow taking only integer input from the user.
Now, if the user enters any input other than an integer, that is, a character or symbol, it will not be accepted by the program. Below is the C program to implement this approach:
C
// C program for the above approach#include <stdio.h> // Driver Codeint main(){ int a; printf("Enter the input: "); // Take the input from console scanf("%d", &a); // Display the output printf("The value entered by the user is: "); printf("%d", a); return 0;}
Output:
Explanation: In the above program, if the input is a character value, then the scanf() function will take the input but will not print anything on the output screen or it will ignore the character and print the integers only. So, to avoid this problem, let’s discuss how to write a program that takes only integer input only. Below are the steps for the same:
Steps: The steps involved in the program below are:
Step 1: The user creates a function called getIntegeronly() and assigns it to int x.Step 2: In this function, the input which is entered will go through a do-while loop in which the if statement checks the ASCII code of the integer. If the ASCII code matches the integer ASCII code, the input will be seen on the screen.
Step 1: The user creates a function called getIntegeronly() and assigns it to int x.
Step 2: In this function, the input which is entered will go through a do-while loop in which the if statement checks the ASCII code of the integer. If the ASCII code matches the integer ASCII code, the input will be seen on the screen.
do
{
If( ch>=48 && ch<=57)
}
Here ch is the input to be enter and 48 to 57 is the
ASCII Code of 0 to 9 respectively.
Step 3: To make the single number a digit, multiply the number and add the integer that is entered.
num = num * 10 + (ch – 48) Here num * 10 will change the place value of the integer to make it digit and (ch – 48) will add the integer by subtracting its ASCII code.
Step 4: To break the loop an if statement is added so that the loop does not go in an infinite loop.
if(ch == 13)
break;
Here 13 is the ASCII code of carriage return which breaks and
return the input value.
Step 5: The return function returns the integer stored in num to x and the output gets printed on the screen.
printf("you have entered %d", x)
Below is the C program to implement the above approach:
C
// C program for the above approach#include <stdio.h>int getIntegerOnly(); // Driver Codeint main(){ int x = 0; x = getIntegerOnly(); printf("\nvalue entered is: %d", x);} // Function to check if the user// entered value is integer or not int getIntegerOnly(){ int num = 0, ch; printf("Enter the input: "); do { ch = getchar(); // Checks the ASCII code of ' // digits 0 to 9 if (ch >= 48 && ch <= 57) { printf("%c", ch); // To make a digit num = num * 10 + (ch - 48); } // 13 is carriage return it breaks // and return the input if (ch == '\n') break; } while (1); return (num);}
Output:
Explanation: It can be observed while executing the program, that the program is only accepting the integer input and printing the input on the screen.
jayanth_mkv
C Basics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
Header files in C/C++ and its uses
UDP Server-Client implementation in C
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Jun, 2022"
},
{
"code": null,
"e": 139,
"s": 53,
"text": "Given an input value N, the task is to allow taking only integer input from the user."
},
{
"code": null,
"e": 319,
"s": 139,
"text": "Now, if the user enters any input other than an integer, that is, a character or symbol, it will not be accepted by the program. Below is the C program to implement this approach:"
},
{
"code": null,
"e": 321,
"s": 319,
"text": "C"
},
{
"code": "// C program for the above approach#include <stdio.h> // Driver Codeint main(){ int a; printf(\"Enter the input: \"); // Take the input from console scanf(\"%d\", &a); // Display the output printf(\"The value entered by the user is: \"); printf(\"%d\", a); return 0;}",
"e": 608,
"s": 321,
"text": null
},
{
"code": null,
"e": 616,
"s": 608,
"text": "Output:"
},
{
"code": null,
"e": 976,
"s": 616,
"text": "Explanation: In the above program, if the input is a character value, then the scanf() function will take the input but will not print anything on the output screen or it will ignore the character and print the integers only. So, to avoid this problem, let’s discuss how to write a program that takes only integer input only. Below are the steps for the same:"
},
{
"code": null,
"e": 1028,
"s": 976,
"text": "Steps: The steps involved in the program below are:"
},
{
"code": null,
"e": 1349,
"s": 1028,
"text": "Step 1: The user creates a function called getIntegeronly() and assigns it to int x.Step 2: In this function, the input which is entered will go through a do-while loop in which the if statement checks the ASCII code of the integer. If the ASCII code matches the integer ASCII code, the input will be seen on the screen."
},
{
"code": null,
"e": 1434,
"s": 1349,
"text": "Step 1: The user creates a function called getIntegeronly() and assigns it to int x."
},
{
"code": null,
"e": 1671,
"s": 1434,
"text": "Step 2: In this function, the input which is entered will go through a do-while loop in which the if statement checks the ASCII code of the integer. If the ASCII code matches the integer ASCII code, the input will be seen on the screen."
},
{
"code": null,
"e": 1795,
"s": 1671,
"text": "do\n{\n If( ch>=48 && ch<=57)\n}\n\nHere ch is the input to be enter and 48 to 57 is the \nASCII Code of 0 to 9 respectively. "
},
{
"code": null,
"e": 1895,
"s": 1795,
"text": "Step 3: To make the single number a digit, multiply the number and add the integer that is entered."
},
{
"code": null,
"e": 2062,
"s": 1895,
"text": "num = num * 10 + (ch – 48) Here num * 10 will change the place value of the integer to make it digit and (ch – 48) will add the integer by subtracting its ASCII code."
},
{
"code": null,
"e": 2163,
"s": 2062,
"text": "Step 4: To break the loop an if statement is added so that the loop does not go in an infinite loop."
},
{
"code": null,
"e": 2271,
"s": 2163,
"text": "if(ch == 13)\nbreak;\n\nHere 13 is the ASCII code of carriage return which breaks and \nreturn the input value."
},
{
"code": null,
"e": 2381,
"s": 2271,
"text": "Step 5: The return function returns the integer stored in num to x and the output gets printed on the screen."
},
{
"code": null,
"e": 2414,
"s": 2381,
"text": "printf(\"you have entered %d\", x)"
},
{
"code": null,
"e": 2470,
"s": 2414,
"text": "Below is the C program to implement the above approach:"
},
{
"code": null,
"e": 2472,
"s": 2470,
"text": "C"
},
{
"code": "// C program for the above approach#include <stdio.h>int getIntegerOnly(); // Driver Codeint main(){ int x = 0; x = getIntegerOnly(); printf(\"\\nvalue entered is: %d\", x);} // Function to check if the user// entered value is integer or not int getIntegerOnly(){ int num = 0, ch; printf(\"Enter the input: \"); do { ch = getchar(); // Checks the ASCII code of ' // digits 0 to 9 if (ch >= 48 && ch <= 57) { printf(\"%c\", ch); // To make a digit num = num * 10 + (ch - 48); } // 13 is carriage return it breaks // and return the input if (ch == '\\n') break; } while (1); return (num);}",
"e": 3188,
"s": 2472,
"text": null
},
{
"code": null,
"e": 3196,
"s": 3188,
"text": "Output:"
},
{
"code": null,
"e": 3348,
"s": 3196,
"text": "Explanation: It can be observed while executing the program, that the program is only accepting the integer input and printing the input on the screen."
},
{
"code": null,
"e": 3360,
"s": 3348,
"text": "jayanth_mkv"
},
{
"code": null,
"e": 3369,
"s": 3360,
"text": "C Basics"
},
{
"code": null,
"e": 3380,
"s": 3369,
"text": "C Language"
},
{
"code": null,
"e": 3391,
"s": 3380,
"text": "C Programs"
},
{
"code": null,
"e": 3489,
"s": 3391,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3537,
"s": 3489,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3558,
"s": 3537,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 3584,
"s": 3558,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 3629,
"s": 3584,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 3667,
"s": 3629,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 3680,
"s": 3667,
"text": "Strings in C"
},
{
"code": null,
"e": 3721,
"s": 3680,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 3750,
"s": 3721,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 3785,
"s": 3750,
"text": "Header files in C/C++ and its uses"
}
] |
Ruby | String length Method
|
08 Jan, 2020
length is a String class method in Ruby which is used to find the character length of the given string.
Syntax: str.length
Parameters: Here, str is the string whose length is to be calculated
Returns:It will return the character length of the str.
Example 1:
# Ruby program to demonstrate# the length method # Taking a string and# using the methodputs "GFG".lengthputs "geeksforgeeks".length
Output:
3
13
Example 2:
# Ruby program to demonstrate# the length method # Taking a string and# using the methodputs "g4g".lengthputs "ruby string".length
Output:
3
11
Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Ruby | String capitalize() Method
Ruby | String gsub! Method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jan, 2020"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "length is a String class method in Ruby which is used to find the character length of the given string."
},
{
"code": null,
"e": 151,
"s": 132,
"text": "Syntax: str.length"
},
{
"code": null,
"e": 220,
"s": 151,
"text": "Parameters: Here, str is the string whose length is to be calculated"
},
{
"code": null,
"e": 276,
"s": 220,
"text": "Returns:It will return the character length of the str."
},
{
"code": null,
"e": 287,
"s": 276,
"text": "Example 1:"
},
{
"code": "# Ruby program to demonstrate# the length method # Taking a string and# using the methodputs \"GFG\".lengthputs \"geeksforgeeks\".length",
"e": 422,
"s": 287,
"text": null
},
{
"code": null,
"e": 430,
"s": 422,
"text": "Output:"
},
{
"code": null,
"e": 436,
"s": 430,
"text": "3\n13\n"
},
{
"code": null,
"e": 447,
"s": 436,
"text": "Example 2:"
},
{
"code": "# Ruby program to demonstrate# the length method # Taking a string and# using the methodputs \"g4g\".lengthputs \"ruby string\".length",
"e": 580,
"s": 447,
"text": null
},
{
"code": null,
"e": 588,
"s": 580,
"text": "Output:"
},
{
"code": null,
"e": 594,
"s": 588,
"text": "3\n11\n"
},
{
"code": null,
"e": 612,
"s": 594,
"text": "Ruby String-class"
},
{
"code": null,
"e": 625,
"s": 612,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 630,
"s": 625,
"text": "Ruby"
},
{
"code": null,
"e": 728,
"s": 630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 774,
"s": 728,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 798,
"s": 774,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 829,
"s": 798,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 872,
"s": 829,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 894,
"s": 872,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 938,
"s": 894,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 968,
"s": 938,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 986,
"s": 968,
"text": "Ruby | Data Types"
},
{
"code": null,
"e": 1020,
"s": 986,
"text": "Ruby | String capitalize() Method"
}
] |
Python MongoDB – insert_one Query
|
03 Jun, 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 is developed by MongoDB Inc. and was initially released on 11 February 2009. It is written in C++, Go, JavaScript, and Python languages. MongoDB offers high speed, high availability, and high scalability.
This is a method by which we can insert a single entry within the collection or the database in MongoDB. If the collection does not exist this method creates a new collection and insert the data into it. It takes a dictionary as a parameter containing the name and value of each field in the document you want to insert in the collection.
This method returns an instance of class “~pymongo.results.InsertOneResult” which has a “_id” field that holds the id of the inserted document. If the document does not specify an “_id” field, then MongoDB will add the “_id” field and assign a unique object id for the document before inserting.
Syntax:
collection.insert_one(document, bypass_document_validation=False, session=None, comment=None)
Parameters:
‘document’: The document to insert. Must be a mutable mapping type. If the document does not have an _id field one will be added automatically.
‘bypass_document_validation’ (optional): If “True”, allows the write to opt-out of document level validation. Default is “False”.
‘session’ (optional): A class ‘~pymongo.client_session.ClientSession’.
‘comment'(optional): A user-provided comment to attach to this command.
Example 1:
Sample database is as follows:
Example
Python3
# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient("mongodb://localhost:27017/") # databasedb = myclient["GFG"] # Created or Switched to collection# names: GeeksForGeekscollection = db["Student"] # Creating Dictionary of records to be# insertedrecord = { "_id": 5, "name": "Raju", "Roll No": "1005", "Branch": "CSE"} # Inserting the record1 in the collection# by using collection.insert_one()rec_id1 = collection.insert_one(record)
Output:
Example 2: Inserting multiple values
To insert multiple values, 2 Methods can be followed:
#1: Naive Method: Using for loop and insert_one
Python3
# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient("mongodb://localhost:27017/") # databasedb = myclient["GFG"] # Created or Switched to collection# names: GeeksForGeekscollection = db["Student"] # Creating Dictionary of records to be# insertedrecords = { "record1": { "_id": 6, "name": "Anshul", "Roll No": "1006", "Branch": "CSE"}, "record2": { "_id": 7, "name": "Abhinav", "Roll No": "1007", "Branch": "ME"}} # Inserting the records in the collection# by using collection.insert_one()for record in records.values(): collection.insert_one(record)
Output:
#2: Using insert_many method: This method can be used to insert multiple documents in a collection in MongoDB.
The insert_many method is explained briefly in the next tutorial.
indorexian
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
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 ?
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 431,
"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. MongoDB is developed by MongoDB Inc. and was initially released on 11 February 2009. It is written in C++, Go, JavaScript, and Python languages. MongoDB offers high speed, high availability, and high scalability."
},
{
"code": null,
"e": 771,
"s": 431,
"text": "This is a method by which we can insert a single entry within the collection or the database in MongoDB. If the collection does not exist this method creates a new collection and insert the data into it. It takes a dictionary as a parameter containing the name and value of each field in the document you want to insert in the collection. "
},
{
"code": null,
"e": 1067,
"s": 771,
"text": "This method returns an instance of class “~pymongo.results.InsertOneResult” which has a “_id” field that holds the id of the inserted document. If the document does not specify an “_id” field, then MongoDB will add the “_id” field and assign a unique object id for the document before inserting."
},
{
"code": null,
"e": 1075,
"s": 1067,
"text": "Syntax:"
},
{
"code": null,
"e": 1170,
"s": 1075,
"text": "collection.insert_one(document, bypass_document_validation=False, session=None, comment=None)"
},
{
"code": null,
"e": 1183,
"s": 1170,
"text": "Parameters: "
},
{
"code": null,
"e": 1327,
"s": 1183,
"text": "‘document’: The document to insert. Must be a mutable mapping type. If the document does not have an _id field one will be added automatically."
},
{
"code": null,
"e": 1457,
"s": 1327,
"text": "‘bypass_document_validation’ (optional): If “True”, allows the write to opt-out of document level validation. Default is “False”."
},
{
"code": null,
"e": 1528,
"s": 1457,
"text": "‘session’ (optional): A class ‘~pymongo.client_session.ClientSession’."
},
{
"code": null,
"e": 1600,
"s": 1528,
"text": "‘comment'(optional): A user-provided comment to attach to this command."
},
{
"code": null,
"e": 1612,
"s": 1600,
"text": "Example 1: "
},
{
"code": null,
"e": 1644,
"s": 1612,
"text": "Sample database is as follows: "
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Example"
},
{
"code": null,
"e": 1660,
"s": 1652,
"text": "Python3"
},
{
"code": "# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient(\"mongodb://localhost:27017/\") # databasedb = myclient[\"GFG\"] # Created or Switched to collection# names: GeeksForGeekscollection = db[\"Student\"] # Creating Dictionary of records to be# insertedrecord = { \"_id\": 5, \"name\": \"Raju\", \"Roll No\": \"1005\", \"Branch\": \"CSE\"} # Inserting the record1 in the collection# by using collection.insert_one()rec_id1 = collection.insert_one(record)",
"e": 2180,
"s": 1660,
"text": null
},
{
"code": null,
"e": 2189,
"s": 2180,
"text": "Output: "
},
{
"code": null,
"e": 2226,
"s": 2189,
"text": "Example 2: Inserting multiple values"
},
{
"code": null,
"e": 2280,
"s": 2226,
"text": "To insert multiple values, 2 Methods can be followed:"
},
{
"code": null,
"e": 2328,
"s": 2280,
"text": "#1: Naive Method: Using for loop and insert_one"
},
{
"code": null,
"e": 2336,
"s": 2328,
"text": "Python3"
},
{
"code": "# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient(\"mongodb://localhost:27017/\") # databasedb = myclient[\"GFG\"] # Created or Switched to collection# names: GeeksForGeekscollection = db[\"Student\"] # Creating Dictionary of records to be# insertedrecords = { \"record1\": { \"_id\": 6, \"name\": \"Anshul\", \"Roll No\": \"1006\", \"Branch\": \"CSE\"}, \"record2\": { \"_id\": 7, \"name\": \"Abhinav\", \"Roll No\": \"1007\", \"Branch\": \"ME\"}} # Inserting the records in the collection# by using collection.insert_one()for record in records.values(): collection.insert_one(record)",
"e": 2974,
"s": 2336,
"text": null
},
{
"code": null,
"e": 2983,
"s": 2974,
"text": "Output: "
},
{
"code": null,
"e": 3094,
"s": 2983,
"text": "#2: Using insert_many method: This method can be used to insert multiple documents in a collection in MongoDB."
},
{
"code": null,
"e": 3160,
"s": 3094,
"text": "The insert_many method is explained briefly in the next tutorial."
},
{
"code": null,
"e": 3171,
"s": 3160,
"text": "indorexian"
},
{
"code": null,
"e": 3186,
"s": 3171,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 3193,
"s": 3186,
"text": "Python"
},
{
"code": null,
"e": 3291,
"s": 3193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3319,
"s": 3291,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3341,
"s": 3319,
"text": "Python map() function"
},
{
"code": null,
"e": 3391,
"s": 3341,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3435,
"s": 3391,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3477,
"s": 3435,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3499,
"s": 3477,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3534,
"s": 3499,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3560,
"s": 3534,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3592,
"s": 3560,
"text": "How to Install PIP on Windows ?"
}
] |
Java String contentEquals() Method with Examples
|
13 May, 2022
contentEquals() method of String class is used to compare the strings. There are two types of contentEquals method available in java.lang.String with different parameters:
contentEquals(StringBuffer sb)contentEquals(CharSequence cs)
contentEquals(StringBuffer sb)
contentEquals(CharSequence cs)
contentEquals(StringBuffer sb) method compares the string to the specified StringBuffer. It will return true if the String represents the same sequence of characters as the specified StringBuffer; otherwise, it will return false.
Syntax:
public boolean contentEquals(StringBuffer sb)
Return Type: It has a boolean return type that will return true if this String represents the same sequence of characters as the specified StringBuffer, otherwise will return false.
Method Parameter: It has one parameter of type StringBuffer
Step 1: First, create an instance of the StringBuffer class to compare its sequence of characters
StringBuffer stringBuffer = new StringBuffer( "GFG is the best");
Step 2: create an instance of String, then invoke its contentEquals method
String str= "GFG is the best";
str.contentEquals(stringBuffer)
The below Java program will illustrate the use of the contentEquals(StringBuffer sb) method:
Java
// Java program to demonstrate the working// of the contentEquals(StringBuffer sb) method import java.io.*;import java.lang.*; class GFG { public static void main(String[] args) { // creating instance of StringBuffer class StringBuffer stringBuffer = new StringBuffer("GFG is a portal for geeks"); String one = "GFG is a portal for geeks"; String two = "GFG is a portal for gamers"; // invoking contentEquals method // for String one and two System.out.println( "String one equals to specified StringBuffer : " + one.contentEquals(stringBuffer)); System.out.println( "String two equals to specified StringBuffer : " + two.contentEquals(stringBuffer)); }}
String one equals to specified StringBuffer : true
String two equals to specified StringBuffer : false
contentEquals(CharSequence cs) method compares the string to the specified CharSequence. It will return true if the String represents the same sequence of char value as the specified CharSequence otherwise, it will return false.
Syntax:
public boolean contentEquals(CharSequence cs)
Method Return Type: It has a boolean return type that will return true if this String represents the same sequence of char values as the specified sequence, otherwise will return false.
Parameter: It has one parameter of type CharSequence
Step 1: First, create a sequence to compare the sequence of char values
CharSequence cs = "portal for geeks"
Step 2: Create an instance of String, then invoke its contentEquals method
String str= "portal for geeks";
str.contentEquals(cs);
The below java program will illustrate the use of the contentEquals(CharSequence cs) method –
Example:
Java
// Java program to demonstrate the working// of contentEquals(CharSequence cs) method import java.io.*;import java.lang.*; class GFG { public static void main(String[] args) { // creating instance of StringBuffer class CharSequence cs = "GFG is best website for programmer"; String one = "GFG is best website for programmer"; String two = "GFG is a portal for geeks"; // invoking contentEquals method // for String one and two System.out.println( "String one equals to specified sequence : " + one.contentEquals(cs)); System.out.println( "String two equals to specified sequence : " + two.contentEquals(cs)); }}
String one equals to specified sequence : true
String two equals to specified sequence : false
blalverma92
Java-Strings
Picked
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 224,
"s": 52,
"text": "contentEquals() method of String class is used to compare the strings. There are two types of contentEquals method available in java.lang.String with different parameters:"
},
{
"code": null,
"e": 285,
"s": 224,
"text": "contentEquals(StringBuffer sb)contentEquals(CharSequence cs)"
},
{
"code": null,
"e": 316,
"s": 285,
"text": "contentEquals(StringBuffer sb)"
},
{
"code": null,
"e": 347,
"s": 316,
"text": "contentEquals(CharSequence cs)"
},
{
"code": null,
"e": 577,
"s": 347,
"text": "contentEquals(StringBuffer sb) method compares the string to the specified StringBuffer. It will return true if the String represents the same sequence of characters as the specified StringBuffer; otherwise, it will return false."
},
{
"code": null,
"e": 585,
"s": 577,
"text": "Syntax:"
},
{
"code": null,
"e": 631,
"s": 585,
"text": "public boolean contentEquals(StringBuffer sb)"
},
{
"code": null,
"e": 813,
"s": 631,
"text": "Return Type: It has a boolean return type that will return true if this String represents the same sequence of characters as the specified StringBuffer, otherwise will return false."
},
{
"code": null,
"e": 873,
"s": 813,
"text": "Method Parameter: It has one parameter of type StringBuffer"
},
{
"code": null,
"e": 972,
"s": 873,
"text": "Step 1: First, create an instance of the StringBuffer class to compare its sequence of characters "
},
{
"code": null,
"e": 1038,
"s": 972,
"text": "StringBuffer stringBuffer = new StringBuffer( \"GFG is the best\");"
},
{
"code": null,
"e": 1113,
"s": 1038,
"text": "Step 2: create an instance of String, then invoke its contentEquals method"
},
{
"code": null,
"e": 1176,
"s": 1113,
"text": "String str= \"GFG is the best\";\nstr.contentEquals(stringBuffer)"
},
{
"code": null,
"e": 1269,
"s": 1176,
"text": "The below Java program will illustrate the use of the contentEquals(StringBuffer sb) method:"
},
{
"code": null,
"e": 1274,
"s": 1269,
"text": "Java"
},
{
"code": "// Java program to demonstrate the working// of the contentEquals(StringBuffer sb) method import java.io.*;import java.lang.*; class GFG { public static void main(String[] args) { // creating instance of StringBuffer class StringBuffer stringBuffer = new StringBuffer(\"GFG is a portal for geeks\"); String one = \"GFG is a portal for geeks\"; String two = \"GFG is a portal for gamers\"; // invoking contentEquals method // for String one and two System.out.println( \"String one equals to specified StringBuffer : \" + one.contentEquals(stringBuffer)); System.out.println( \"String two equals to specified StringBuffer : \" + two.contentEquals(stringBuffer)); }}",
"e": 2052,
"s": 1274,
"text": null
},
{
"code": null,
"e": 2155,
"s": 2052,
"text": "String one equals to specified StringBuffer : true\nString two equals to specified StringBuffer : false"
},
{
"code": null,
"e": 2384,
"s": 2155,
"text": "contentEquals(CharSequence cs) method compares the string to the specified CharSequence. It will return true if the String represents the same sequence of char value as the specified CharSequence otherwise, it will return false."
},
{
"code": null,
"e": 2392,
"s": 2384,
"text": "Syntax:"
},
{
"code": null,
"e": 2438,
"s": 2392,
"text": "public boolean contentEquals(CharSequence cs)"
},
{
"code": null,
"e": 2624,
"s": 2438,
"text": "Method Return Type: It has a boolean return type that will return true if this String represents the same sequence of char values as the specified sequence, otherwise will return false."
},
{
"code": null,
"e": 2677,
"s": 2624,
"text": "Parameter: It has one parameter of type CharSequence"
},
{
"code": null,
"e": 2749,
"s": 2677,
"text": "Step 1: First, create a sequence to compare the sequence of char values"
},
{
"code": null,
"e": 2786,
"s": 2749,
"text": "CharSequence cs = \"portal for geeks\""
},
{
"code": null,
"e": 2861,
"s": 2786,
"text": "Step 2: Create an instance of String, then invoke its contentEquals method"
},
{
"code": null,
"e": 2916,
"s": 2861,
"text": "String str= \"portal for geeks\";\nstr.contentEquals(cs);"
},
{
"code": null,
"e": 3010,
"s": 2916,
"text": "The below java program will illustrate the use of the contentEquals(CharSequence cs) method –"
},
{
"code": null,
"e": 3019,
"s": 3010,
"text": "Example:"
},
{
"code": null,
"e": 3024,
"s": 3019,
"text": "Java"
},
{
"code": "// Java program to demonstrate the working// of contentEquals(CharSequence cs) method import java.io.*;import java.lang.*; class GFG { public static void main(String[] args) { // creating instance of StringBuffer class CharSequence cs = \"GFG is best website for programmer\"; String one = \"GFG is best website for programmer\"; String two = \"GFG is a portal for geeks\"; // invoking contentEquals method // for String one and two System.out.println( \"String one equals to specified sequence : \" + one.contentEquals(cs)); System.out.println( \"String two equals to specified sequence : \" + two.contentEquals(cs)); }}",
"e": 3777,
"s": 3024,
"text": null
},
{
"code": null,
"e": 3872,
"s": 3777,
"text": "String one equals to specified sequence : true\nString two equals to specified sequence : false"
},
{
"code": null,
"e": 3884,
"s": 3872,
"text": "blalverma92"
},
{
"code": null,
"e": 3897,
"s": 3884,
"text": "Java-Strings"
},
{
"code": null,
"e": 3904,
"s": 3897,
"text": "Picked"
},
{
"code": null,
"e": 3909,
"s": 3904,
"text": "Java"
},
{
"code": null,
"e": 3922,
"s": 3909,
"text": "Java-Strings"
},
{
"code": null,
"e": 3927,
"s": 3922,
"text": "Java"
},
{
"code": null,
"e": 4025,
"s": 3927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4040,
"s": 4025,
"text": "Stream In Java"
},
{
"code": null,
"e": 4061,
"s": 4040,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4082,
"s": 4061,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4101,
"s": 4082,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4118,
"s": 4101,
"text": "Generics in Java"
},
{
"code": null,
"e": 4148,
"s": 4118,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4174,
"s": 4148,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4190,
"s": 4174,
"text": "Strings in Java"
},
{
"code": null,
"e": 4227,
"s": 4190,
"text": "Differences between JDK, JRE and JVM"
}
] |
numpy.rot90() in Python
|
09 Mar, 2022
The numpy.rot90() method performs rotation of an array by 90 degrees in the plane specified by axis(0 or 1).Syntax:
numpy.rot90(array, k = 1, axes = (0, 1))
Parameters :
array : [array_like]i.e. array having two or more dimensions.
k : [optional , int]No. of times we wish to rotate array by 90 degrees.
axes : [array_like]Plane, along which we wish to rotate array.
Returns :
rotated copy of array
# Python Program illustrating# numpy.rot90() method import numpy as geek array = geek.arange(12).reshape(3, 4)print("Original array : \n", array) # Rotating array 4 times : Returns same original arrayprint("\nArray being rotated 4 times : \n", geek.rot90(array, 4)) # Rotating onceprint("\nRotated array : \n", geek.rot90(array)) # Rotating twiceprint("\nRotated array : \n", geek.rot90(array, 2))
Output :
Original array :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Array being rotated 4 times :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Rotated array :
[[ 3 7 11]
[ 2 6 10]
[ 1 5 9]
[ 0 4 8]]
Rotated array :
[[11 10 9 8]
[ 7 6 5 4]
[ 3 2 1 0]]
References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.rot90.html
Note :These codes won’t run on online IDE’s. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
vinayedula
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "The numpy.rot90() method performs rotation of an array by 90 degrees in the plane specified by axis(0 or 1).Syntax:"
},
{
"code": null,
"e": 185,
"s": 144,
"text": "numpy.rot90(array, k = 1, axes = (0, 1))"
},
{
"code": null,
"e": 198,
"s": 185,
"text": "Parameters :"
},
{
"code": null,
"e": 401,
"s": 198,
"text": "array : [array_like]i.e. array having two or more dimensions.\nk : [optional , int]No. of times we wish to rotate array by 90 degrees.\naxes : [array_like]Plane, along which we wish to rotate array.\n"
},
{
"code": null,
"e": 411,
"s": 401,
"text": "Returns :"
},
{
"code": null,
"e": 434,
"s": 411,
"text": "rotated copy of array\n"
},
{
"code": "# Python Program illustrating# numpy.rot90() method import numpy as geek array = geek.arange(12).reshape(3, 4)print(\"Original array : \\n\", array) # Rotating array 4 times : Returns same original arrayprint(\"\\nArray being rotated 4 times : \\n\", geek.rot90(array, 4)) # Rotating onceprint(\"\\nRotated array : \\n\", geek.rot90(array)) # Rotating twiceprint(\"\\nRotated array : \\n\", geek.rot90(array, 2))",
"e": 837,
"s": 434,
"text": null
},
{
"code": null,
"e": 846,
"s": 837,
"text": "Output :"
},
{
"code": null,
"e": 1124,
"s": 846,
"text": "Original array : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nArray being rotated 4 times : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nRotated array : \n [[ 3 7 11]\n [ 2 6 10]\n [ 1 5 9]\n [ 0 4 8]]\n\nRotated array : \n [[11 10 9 8]\n [ 7 6 5 4]\n [ 3 2 1 0]]\n"
},
{
"code": null,
"e": 1210,
"s": 1124,
"text": "References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.rot90.html"
},
{
"code": null,
"e": 1610,
"s": 1210,
"text": "Note :These codes won’t run on online IDE’s. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1621,
"s": 1610,
"text": "vinayedula"
},
{
"code": null,
"e": 1652,
"s": 1621,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 1665,
"s": 1652,
"text": "Python-numpy"
},
{
"code": null,
"e": 1672,
"s": 1665,
"text": "Python"
},
{
"code": null,
"e": 1770,
"s": 1672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1802,
"s": 1770,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1829,
"s": 1802,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1850,
"s": 1829,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1873,
"s": 1850,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1929,
"s": 1873,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1960,
"s": 1929,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2002,
"s": 1960,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2044,
"s": 2002,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2083,
"s": 2044,
"text": "Python | datetime.timedelta() function"
}
] |
Modes of DMA Transfer
|
29 Jun, 2022
In this article we will try to understand the details associated with the DMA (Direct Memory Access) like what exactly DMA is or how it works and also further we will see various modes of DMA Transfer (like Burst mode and other modes). Before directly jumping into the details associated with the modes of DMA transfer let us first try to understand what exactly DMA is and how does this DMA actually works.
Direct Memory Access (DMA) :DMA basically stands for Direct Memory Access. It is a process which enables data transfer between the Memory and the IO (Input/ Output) device without the need of or you can say without the involvement of CPU during data transfer.
Working of DMA :Following list of points will describe briefly about DMA and its working as follows.
For DMA, you basically need a hardware called DMAC (Direct Memory Access Controller) which will help in the throughout process of data transfer between the Memory and IO device directly.
First what happens is IO device sends the DMA request to DMA Controller, then further DMAC device sends HOLD signal to CPU by which it asks CPU for several information which are needed while transferring data.
CPU then shares two basic information with DMAC before the Data transfer which are: Starting address (memory address starting from where data transfer should be performed) and Data Count (no of bytes or words to be transferred).
CPU then sends HLDACK (Hold Acknowledgement) back to DMAC illustrating that now DMAC can successfully pass on the information.
Then further DMAC shares the DMA ACK (DMA Acknowledgement) to the IO device which would eventually let IO device to access or transfer the data from memory in a direct and efficient manner.
Modes of DMA Transfer :Now after getting some brief idea about DMA and its working it’s the time to analyze Modes of DMA Transfer.
During the DMA Transfer CPU can perform only those operation in which it doesn’t require the access of System Bus which means mostly CPU will be in blocked state.
For how much time CPU remains in the blocked state or we can say for how much time CPU will give the control of DMAC of system buses will actually depend upon the following modes of DMA Transfer and after that CPU will take back control of system buses from DMAC.
Mode-1 : Burst Mode –
In this mode Burst of data (entire data or burst of block containing data) is transferred before CPU takes control of the buses back from DMAC.
This is the quickest mode of DMA Transfer since at once a huge amount of data is being transferred.
Since at once only the huge amount of data is being transferred so time will be saved in huge amount.
Percentage of Time CPU remains blocked :Let time taken to prepare the data be Tx and time taken to transfer the data be Ty. Then percentage of time CPU remains blocked due to DMA is as follows.
Percentage of time CPU remains in blocked state = Ty * 100% / Tx + Ty
Mode-2 : Cycle Stealing Mode –
Slow IO device will take some time to prepare data (or word) and within that time CPU keeps the control of the buses.
Once the data or the word is ready CPU give back control of system buses to DMAC for 1-cycle in which the prepared word is transferred to memory.
As compared to Burst mode this mode is little bit slowest since it requires little bit of time which is actually consumed by IO device while preparing the data.
Percentage of Time CPU remains blocked :Let time taken to prepare data be Tx and time taken to transfer the data be Ty. Then percentage of time CPU remains blocked due to DMA is as follows.
Percentage of time CPU remains in blocked state = Ty * 100% / Tx
Mode-3 : Interleaving Mode –
Whenever CPU does not require the system buses then only control of buses will be given to DMAC.
In this mode, CPU will not be blocked due to DMA at all.
This is the slowest mode of DMA Transfer since DMAC has to wait might be for so long time to just even get the access of system buses from the CPU itself.
Hence due to which less amount of data will be transferred.
Example : Consider a device operating on 2MBPs speed and transferring the data to memory is done using Cycle Stealing mode. It takes 2 microseconds to transfer 16 bytes of data to memory when it is ready or prepared. Then for what percentage of time CPU is blocked due to DMA transfer?
Explanation –
Internal data preparation speed given = 2 MBPs.
So for preparing 2 MB it takes ------> 1 second
For preparing 1B it takes -------> 1 second / 2MB
So now for 16B data preparation it takes ------->1 second * 16B / 2MB
(after reciprocating Mega will be become micro
(that is 10^6 will become 10^-6 after reciprocating))
therefore for preparation 16B it takes -------> 8 microseconds
Therefore percentage of time CPU remains blocked in case of
Cycle Stealing mode = 2 * 100% / 8 = 25%
surinderdawra388
Blogathon-2021
Computer Organization and Architecture
Blogathon
Computer Organization & Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 462,
"s": 54,
"text": "In this article we will try to understand the details associated with the DMA (Direct Memory Access) like what exactly DMA is or how it works and also further we will see various modes of DMA Transfer (like Burst mode and other modes). Before directly jumping into the details associated with the modes of DMA transfer let us first try to understand what exactly DMA is and how does this DMA actually works."
},
{
"code": null,
"e": 722,
"s": 462,
"text": "Direct Memory Access (DMA) :DMA basically stands for Direct Memory Access. It is a process which enables data transfer between the Memory and the IO (Input/ Output) device without the need of or you can say without the involvement of CPU during data transfer."
},
{
"code": null,
"e": 823,
"s": 722,
"text": "Working of DMA :Following list of points will describe briefly about DMA and its working as follows."
},
{
"code": null,
"e": 1010,
"s": 823,
"text": "For DMA, you basically need a hardware called DMAC (Direct Memory Access Controller) which will help in the throughout process of data transfer between the Memory and IO device directly."
},
{
"code": null,
"e": 1220,
"s": 1010,
"text": "First what happens is IO device sends the DMA request to DMA Controller, then further DMAC device sends HOLD signal to CPU by which it asks CPU for several information which are needed while transferring data."
},
{
"code": null,
"e": 1449,
"s": 1220,
"text": "CPU then shares two basic information with DMAC before the Data transfer which are: Starting address (memory address starting from where data transfer should be performed) and Data Count (no of bytes or words to be transferred)."
},
{
"code": null,
"e": 1576,
"s": 1449,
"text": "CPU then sends HLDACK (Hold Acknowledgement) back to DMAC illustrating that now DMAC can successfully pass on the information."
},
{
"code": null,
"e": 1766,
"s": 1576,
"text": "Then further DMAC shares the DMA ACK (DMA Acknowledgement) to the IO device which would eventually let IO device to access or transfer the data from memory in a direct and efficient manner."
},
{
"code": null,
"e": 1897,
"s": 1766,
"text": "Modes of DMA Transfer :Now after getting some brief idea about DMA and its working it’s the time to analyze Modes of DMA Transfer."
},
{
"code": null,
"e": 2060,
"s": 1897,
"text": "During the DMA Transfer CPU can perform only those operation in which it doesn’t require the access of System Bus which means mostly CPU will be in blocked state."
},
{
"code": null,
"e": 2324,
"s": 2060,
"text": "For how much time CPU remains in the blocked state or we can say for how much time CPU will give the control of DMAC of system buses will actually depend upon the following modes of DMA Transfer and after that CPU will take back control of system buses from DMAC."
},
{
"code": null,
"e": 2346,
"s": 2324,
"text": "Mode-1 : Burst Mode –"
},
{
"code": null,
"e": 2490,
"s": 2346,
"text": "In this mode Burst of data (entire data or burst of block containing data) is transferred before CPU takes control of the buses back from DMAC."
},
{
"code": null,
"e": 2590,
"s": 2490,
"text": "This is the quickest mode of DMA Transfer since at once a huge amount of data is being transferred."
},
{
"code": null,
"e": 2692,
"s": 2590,
"text": "Since at once only the huge amount of data is being transferred so time will be saved in huge amount."
},
{
"code": null,
"e": 2886,
"s": 2692,
"text": "Percentage of Time CPU remains blocked :Let time taken to prepare the data be Tx and time taken to transfer the data be Ty. Then percentage of time CPU remains blocked due to DMA is as follows."
},
{
"code": null,
"e": 2956,
"s": 2886,
"text": "Percentage of time CPU remains in blocked state = Ty * 100% / Tx + Ty"
},
{
"code": null,
"e": 2987,
"s": 2956,
"text": "Mode-2 : Cycle Stealing Mode –"
},
{
"code": null,
"e": 3105,
"s": 2987,
"text": "Slow IO device will take some time to prepare data (or word) and within that time CPU keeps the control of the buses."
},
{
"code": null,
"e": 3251,
"s": 3105,
"text": "Once the data or the word is ready CPU give back control of system buses to DMAC for 1-cycle in which the prepared word is transferred to memory."
},
{
"code": null,
"e": 3412,
"s": 3251,
"text": "As compared to Burst mode this mode is little bit slowest since it requires little bit of time which is actually consumed by IO device while preparing the data."
},
{
"code": null,
"e": 3602,
"s": 3412,
"text": "Percentage of Time CPU remains blocked :Let time taken to prepare data be Tx and time taken to transfer the data be Ty. Then percentage of time CPU remains blocked due to DMA is as follows."
},
{
"code": null,
"e": 3667,
"s": 3602,
"text": "Percentage of time CPU remains in blocked state = Ty * 100% / Tx"
},
{
"code": null,
"e": 3696,
"s": 3667,
"text": "Mode-3 : Interleaving Mode –"
},
{
"code": null,
"e": 3793,
"s": 3696,
"text": "Whenever CPU does not require the system buses then only control of buses will be given to DMAC."
},
{
"code": null,
"e": 3850,
"s": 3793,
"text": "In this mode, CPU will not be blocked due to DMA at all."
},
{
"code": null,
"e": 4005,
"s": 3850,
"text": "This is the slowest mode of DMA Transfer since DMAC has to wait might be for so long time to just even get the access of system buses from the CPU itself."
},
{
"code": null,
"e": 4065,
"s": 4005,
"text": "Hence due to which less amount of data will be transferred."
},
{
"code": null,
"e": 4351,
"s": 4065,
"text": "Example : Consider a device operating on 2MBPs speed and transferring the data to memory is done using Cycle Stealing mode. It takes 2 microseconds to transfer 16 bytes of data to memory when it is ready or prepared. Then for what percentage of time CPU is blocked due to DMA transfer?"
},
{
"code": null,
"e": 4366,
"s": 4351,
"text": "Explanation – "
},
{
"code": null,
"e": 4895,
"s": 4366,
"text": "Internal data preparation speed given = 2 MBPs. \nSo for preparing 2 MB it takes ------> 1 second\nFor preparing 1B it takes -------> 1 second / 2MB\n\nSo now for 16B data preparation it takes ------->1 second * 16B / 2MB\n(after reciprocating Mega will be become micro \n\n(that is 10^6 will become 10^-6 after reciprocating))\ntherefore for preparation 16B it takes -------> 8 microseconds\n\nTherefore percentage of time CPU remains blocked in case of \nCycle Stealing mode = 2 * 100% / 8 = 25% "
},
{
"code": null,
"e": 4912,
"s": 4895,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4927,
"s": 4912,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 4966,
"s": 4927,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 4976,
"s": 4966,
"text": "Blogathon"
},
{
"code": null,
"e": 5013,
"s": 4976,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 5021,
"s": 5013,
"text": "GATE CS"
}
] |
Python | Decision Tree Regression using sklearn
|
18 May, 2022
Decision Tree is a decision-making tool that uses a flowchart-like tree structure or is a model of decisions and all of their possible results, including outcomes, input costs, and utility.Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables.
The branches/edges represent the result of the node and the nodes have either:
Conditions [Decision Nodes]Result [End Nodes]
Conditions [Decision Nodes]
Result [End Nodes]
The branches/edges represent the truth/falsity of the statement and take makes a decision based on that in the example below which shows a decision tree that evaluates the smallest of three numbers:
Decision Tree Regression: Decision tree regression observes features of an object and trains a model in the structure of a tree to predict data in the future to produce meaningful continuous output. Continuous output means that the output/result is not discrete, i.e., it is not represented just by a discrete, known set of numbers or values.
Discrete output example: A weather prediction model that predicts whether or not there’ll be rain on a particular day. Continuous output example: A profit prediction model that states the probable profit that can be generated from the sale of a product.Here, continuous values are predicted with the help of a decision tree regression model.
Let’s see the Step-by-Step implementation –
Step 1: Import the required libraries.
Python3
# import numpy package for arrays and stuffimport numpy as np # import matplotlib.pyplot for plotting our resultimport matplotlib.pyplot as plt # import pandas for importing csv files import pandas as pd
Step 2: Initialize and print the Dataset.
Python3
# import dataset# dataset = pd.read_csv('Data.csv') # alternatively open up .csv file to read data dataset = np.array([['Asset Flip', 100, 1000],['Text Based', 500, 3000],['Visual Novel', 1500, 5000],['2D Pixel Art', 3500, 8000],['2D Vector Art', 5000, 6500],['Strategy', 6000, 7000],['First Person Shooter', 8000, 15000],['Simulator', 9500, 20000],['Racing', 12000, 21000],['RPG', 14000, 25000],['Sandbox', 15500, 27000],['Open-World', 16500, 30000],['MMOFPS', 25000, 52000],['MMORPG', 30000, 80000]]) # print the datasetprint(dataset)
Output:
[['Asset Flip' '100' '1000']
['Text Based' '500' '3000']
['Visual Novel' '1500' '5000']
['2D Pixel Art' '3500' '8000']
['2D Vector Art' '5000' '6500']
['Strategy' '6000' '7000']
['First Person Shooter' '8000' '15000']
['Simulator' '9500' '20000']
['Racing' '12000' '21000']
['RPG' '14000' '25000']
['Sandbox' '15500' '27000']
['Open-World' '16500' '30000']
['MMOFPS' '25000' '52000']
['MMORPG' '30000' '80000']]
Step 3: Select all the rows and column 1 from the dataset to “X”.
Python3
# select all rows by : and column 1# by 1:2 representing featuresX = dataset[:, 1:2].astype(int) # print Xprint(X)
Output:
[[ 100]
[ 500]
[ 1500]
[ 3500]
[ 5000]
[ 6000]
[ 8000]
[ 9500]
[12000]
[14000]
[15500]
[16500]
[25000]
[30000]]
Step 4: Select all of the rows and column 2 from the dataset to “y”.
Python3
# select all rows by : and column 2# by 2 to Y representing labelsy = dataset[:, 2].astype(int) # print yprint(y)
Output:
[ 1000 3000 5000 8000 6500 7000 15000 20000 21000 25000 27000 30000 52000 80000]
Step 5: Fit decision tree regressor to the dataset
Python3
# import the regressorfrom sklearn.tree import DecisionTreeRegressor # create a regressor objectregressor = DecisionTreeRegressor(random_state = 0) # fit the regressor with X and Y dataregressor.fit(X, y)
Output:
DecisionTreeRegressor(ccp_alpha=0.0, criterion='mse', max_depth=None,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort='deprecated',
random_state=0, splitter='best')
Step 6: Predicting a new value
Python3
# predicting a new value # test the output by changing values, like 3750y_pred = regressor.predict([[3750]]) # print the predicted priceprint("Predicted price: % d\n"% y_pred)
Output:
Predicted price: 8000
Step 7: Visualising the result
Python3
# arange for creating a range of values # from min value of X to max value of X # with a difference of 0.01 between two# consecutive valuesX_grid = np.arange(min(X), max(X), 0.01) # reshape for reshaping the data into # a len(X_grid)*1 array, i.e. to make# a column out of the X_grid valuesX_grid = X_grid.reshape((len(X_grid), 1)) # scatter plot for original dataplt.scatter(X, y, color = 'red') # plot predicted dataplt.plot(X_grid, regressor.predict(X_grid), color = 'blue') # specify titleplt.title('Profit to Production Cost (Decision Tree Regression)') # specify X axis labelplt.xlabel('Production Cost') # specify Y axis labelplt.ylabel('Profit') # show the plotplt.show()
Step 8: The tree is finally exported and shown in the TREE STRUCTURE below, visualized using http://www.webgraphviz.com/ by copying the data from the ‘tree.dot’ file.
Python3
# import export_graphvizfrom sklearn.tree import export_graphviz # export the decision tree to a tree.dot file# for visualizing the plot easily anywhereexport_graphviz(regressor, out_file ='tree.dot', feature_names =['Production Cost'])
Output (Decision Tree):
marcosarcticseal
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
How to Run a Python Script using Docker?
Agents in Artificial Intelligence
Search Algorithms in AI
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Markov Decision Process
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 395,
"s": 52,
"text": "Decision Tree is a decision-making tool that uses a flowchart-like tree structure or is a model of decisions and all of their possible results, including outcomes, input costs, and utility.Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables."
},
{
"code": null,
"e": 475,
"s": 395,
"text": "The branches/edges represent the result of the node and the nodes have either: "
},
{
"code": null,
"e": 521,
"s": 475,
"text": "Conditions [Decision Nodes]Result [End Nodes]"
},
{
"code": null,
"e": 549,
"s": 521,
"text": "Conditions [Decision Nodes]"
},
{
"code": null,
"e": 568,
"s": 549,
"text": "Result [End Nodes]"
},
{
"code": null,
"e": 769,
"s": 568,
"text": "The branches/edges represent the truth/falsity of the statement and take makes a decision based on that in the example below which shows a decision tree that evaluates the smallest of three numbers: "
},
{
"code": null,
"e": 1112,
"s": 769,
"text": "Decision Tree Regression: Decision tree regression observes features of an object and trains a model in the structure of a tree to predict data in the future to produce meaningful continuous output. Continuous output means that the output/result is not discrete, i.e., it is not represented just by a discrete, known set of numbers or values."
},
{
"code": null,
"e": 1454,
"s": 1112,
"text": "Discrete output example: A weather prediction model that predicts whether or not there’ll be rain on a particular day. Continuous output example: A profit prediction model that states the probable profit that can be generated from the sale of a product.Here, continuous values are predicted with the help of a decision tree regression model."
},
{
"code": null,
"e": 1499,
"s": 1454,
"text": "Let’s see the Step-by-Step implementation – "
},
{
"code": null,
"e": 1539,
"s": 1499,
"text": "Step 1: Import the required libraries. "
},
{
"code": null,
"e": 1547,
"s": 1539,
"text": "Python3"
},
{
"code": "# import numpy package for arrays and stuffimport numpy as np # import matplotlib.pyplot for plotting our resultimport matplotlib.pyplot as plt # import pandas for importing csv files import pandas as pd ",
"e": 1755,
"s": 1547,
"text": null
},
{
"code": null,
"e": 1797,
"s": 1755,
"text": "Step 2: Initialize and print the Dataset."
},
{
"code": null,
"e": 1805,
"s": 1797,
"text": "Python3"
},
{
"code": "# import dataset# dataset = pd.read_csv('Data.csv') # alternatively open up .csv file to read data dataset = np.array([['Asset Flip', 100, 1000],['Text Based', 500, 3000],['Visual Novel', 1500, 5000],['2D Pixel Art', 3500, 8000],['2D Vector Art', 5000, 6500],['Strategy', 6000, 7000],['First Person Shooter', 8000, 15000],['Simulator', 9500, 20000],['Racing', 12000, 21000],['RPG', 14000, 25000],['Sandbox', 15500, 27000],['Open-World', 16500, 30000],['MMOFPS', 25000, 52000],['MMORPG', 30000, 80000]]) # print the datasetprint(dataset) ",
"e": 2345,
"s": 1805,
"text": null
},
{
"code": null,
"e": 2353,
"s": 2345,
"text": "Output:"
},
{
"code": null,
"e": 2778,
"s": 2353,
"text": "[['Asset Flip' '100' '1000']\n ['Text Based' '500' '3000']\n ['Visual Novel' '1500' '5000']\n ['2D Pixel Art' '3500' '8000']\n ['2D Vector Art' '5000' '6500']\n ['Strategy' '6000' '7000']\n ['First Person Shooter' '8000' '15000']\n ['Simulator' '9500' '20000']\n ['Racing' '12000' '21000']\n ['RPG' '14000' '25000']\n ['Sandbox' '15500' '27000']\n ['Open-World' '16500' '30000']\n ['MMOFPS' '25000' '52000']\n ['MMORPG' '30000' '80000']]"
},
{
"code": null,
"e": 2844,
"s": 2778,
"text": "Step 3: Select all the rows and column 1 from the dataset to “X”."
},
{
"code": null,
"e": 2852,
"s": 2844,
"text": "Python3"
},
{
"code": "# select all rows by : and column 1# by 1:2 representing featuresX = dataset[:, 1:2].astype(int) # print Xprint(X)",
"e": 2969,
"s": 2852,
"text": null
},
{
"code": null,
"e": 2977,
"s": 2969,
"text": "Output:"
},
{
"code": null,
"e": 3105,
"s": 2977,
"text": "[[ 100]\n [ 500]\n [ 1500]\n [ 3500]\n [ 5000]\n [ 6000]\n [ 8000]\n [ 9500]\n [12000]\n [14000]\n [15500]\n [16500]\n [25000]\n [30000]]\n"
},
{
"code": null,
"e": 3174,
"s": 3105,
"text": "Step 4: Select all of the rows and column 2 from the dataset to “y”."
},
{
"code": null,
"e": 3182,
"s": 3174,
"text": "Python3"
},
{
"code": "# select all rows by : and column 2# by 2 to Y representing labelsy = dataset[:, 2].astype(int) # print yprint(y)",
"e": 3298,
"s": 3182,
"text": null
},
{
"code": null,
"e": 3306,
"s": 3298,
"text": "Output:"
},
{
"code": null,
"e": 3392,
"s": 3306,
"text": "[ 1000 3000 5000 8000 6500 7000 15000 20000 21000 25000 27000 30000 52000 80000]"
},
{
"code": null,
"e": 3443,
"s": 3392,
"text": "Step 5: Fit decision tree regressor to the dataset"
},
{
"code": null,
"e": 3451,
"s": 3443,
"text": "Python3"
},
{
"code": "# import the regressorfrom sklearn.tree import DecisionTreeRegressor # create a regressor objectregressor = DecisionTreeRegressor(random_state = 0) # fit the regressor with X and Y dataregressor.fit(X, y)",
"e": 3660,
"s": 3451,
"text": null
},
{
"code": null,
"e": 3668,
"s": 3660,
"text": "Output:"
},
{
"code": null,
"e": 4066,
"s": 3668,
"text": "DecisionTreeRegressor(ccp_alpha=0.0, criterion='mse', max_depth=None,\n max_features=None, max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, presort='deprecated',\n random_state=0, splitter='best')"
},
{
"code": null,
"e": 4097,
"s": 4066,
"text": "Step 6: Predicting a new value"
},
{
"code": null,
"e": 4105,
"s": 4097,
"text": "Python3"
},
{
"code": "# predicting a new value # test the output by changing values, like 3750y_pred = regressor.predict([[3750]]) # print the predicted priceprint(\"Predicted price: % d\\n\"% y_pred) ",
"e": 4284,
"s": 4105,
"text": null
},
{
"code": null,
"e": 4292,
"s": 4284,
"text": "Output:"
},
{
"code": null,
"e": 4315,
"s": 4292,
"text": "Predicted price: 8000"
},
{
"code": null,
"e": 4346,
"s": 4315,
"text": "Step 7: Visualising the result"
},
{
"code": null,
"e": 4354,
"s": 4346,
"text": "Python3"
},
{
"code": "# arange for creating a range of values # from min value of X to max value of X # with a difference of 0.01 between two# consecutive valuesX_grid = np.arange(min(X), max(X), 0.01) # reshape for reshaping the data into # a len(X_grid)*1 array, i.e. to make# a column out of the X_grid valuesX_grid = X_grid.reshape((len(X_grid), 1)) # scatter plot for original dataplt.scatter(X, y, color = 'red') # plot predicted dataplt.plot(X_grid, regressor.predict(X_grid), color = 'blue') # specify titleplt.title('Profit to Production Cost (Decision Tree Regression)') # specify X axis labelplt.xlabel('Production Cost') # specify Y axis labelplt.ylabel('Profit') # show the plotplt.show()",
"e": 5044,
"s": 4354,
"text": null
},
{
"code": null,
"e": 5211,
"s": 5044,
"text": "Step 8: The tree is finally exported and shown in the TREE STRUCTURE below, visualized using http://www.webgraphviz.com/ by copying the data from the ‘tree.dot’ file."
},
{
"code": null,
"e": 5219,
"s": 5211,
"text": "Python3"
},
{
"code": "# import export_graphvizfrom sklearn.tree import export_graphviz # export the decision tree to a tree.dot file# for visualizing the plot easily anywhereexport_graphviz(regressor, out_file ='tree.dot', feature_names =['Production Cost']) ",
"e": 5473,
"s": 5219,
"text": null
},
{
"code": null,
"e": 5498,
"s": 5473,
"text": "Output (Decision Tree): "
},
{
"code": null,
"e": 5517,
"s": 5500,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 5543,
"s": 5517,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 5560,
"s": 5543,
"text": "Machine Learning"
},
{
"code": null,
"e": 5567,
"s": 5560,
"text": "Python"
},
{
"code": null,
"e": 5584,
"s": 5567,
"text": "Machine Learning"
},
{
"code": null,
"e": 5682,
"s": 5584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5705,
"s": 5682,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 5731,
"s": 5705,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 5767,
"s": 5731,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5791,
"s": 5767,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 5832,
"s": 5791,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 5866,
"s": 5832,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 5890,
"s": 5866,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 5926,
"s": 5890,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5967,
"s": 5926,
"text": "Introduction to Recurrent Neural Network"
}
] |
Python in Competitive Programming
|
27 Nov, 2020
In 2017, when ACM allowed Python support for its prestigious competition, the ACM ICPC, a whole new community became interested in the sport of competitive programming. This meant more people coming back to the basics, learning algorithms that are the building blocks of complex packages they use to build their high level packages.Unfortunately, not a lot of information exists out there on how to effectively use data structures and even the scoping rules of python which lead people to believe that python is subpar for competitive programming.Today I’ll show you how python sometimes is even more powerful than C++ or Java thanks to its amazing libraries, and how simple it actually can be.
Let me demonstrate with a simple example, look at the following snippets of code-
alphabets = ['a', 'b', 'c']for item in alphabets: len(item)
alphabets = ['a', 'b', 'c']fn = lenfor item in alphabets: fn(item)
You might think I’ve assigned an alias to the function ‘len’ and it might not make a difference.So i wrote a performance testing function as follows.
import datetimealphabets = [str(x)for x in range(10000000)]a = datetime.datetime.now() # store initial timefor item in alphabets: len(item)b = datetime.datetime.now() # store final timeprint (b-a).total_seconds() # resultsa = datetime.datetime.now()fn = len # function stored locallyfor item in alphabets: fn(item)b = datetime.datetime.now()print (b-a).total_seconds()
I encourage you to try it on your systems.Here’s the output on mine on running the performance.py script.
Almost half!
Okay, now let’s try to analyse why this happened. Reason? Lookup for a function is a costly operation.In the second snippet, I stored the function directly in the scope of the function, so it doesn’t matter how many times I call it, each time the runtime knows exactly where it has to look for the results.
ItertoolsIf you’ve been to codeforces, you know by now that the a lot of programming challenges involve backtracking. So today I’ll tell you about a library to generate all permutations and combinations using a inbuilt library package which is extremely fast. Itertools. If you’re looking to solve algorithmic challenges with python then itertools is library you must definitely explore.To generate all permutations –
from itertools import permutationsperm = permutations([1, 2, 3], 2)for i in list(perm): print i # Answer->(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)
The combinations() functions behaves similarly I encourage the readers to try it on their own.
Python is a slow language only if your code is not leveraging the power of it successfully. Do not feel like you are at a disadvantage if you’re a python coder, it’s actually very neat and very quick!
ACM-ICPC
Competitive Programming
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
Algorithm Library | C++ Magicians STL Algorithm
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Nov, 2020"
},
{
"code": null,
"e": 747,
"s": 52,
"text": "In 2017, when ACM allowed Python support for its prestigious competition, the ACM ICPC, a whole new community became interested in the sport of competitive programming. This meant more people coming back to the basics, learning algorithms that are the building blocks of complex packages they use to build their high level packages.Unfortunately, not a lot of information exists out there on how to effectively use data structures and even the scoping rules of python which lead people to believe that python is subpar for competitive programming.Today I’ll show you how python sometimes is even more powerful than C++ or Java thanks to its amazing libraries, and how simple it actually can be."
},
{
"code": null,
"e": 829,
"s": 747,
"text": "Let me demonstrate with a simple example, look at the following snippets of code-"
},
{
"code": "alphabets = ['a', 'b', 'c']for item in alphabets: len(item) ",
"e": 893,
"s": 829,
"text": null
},
{
"code": "alphabets = ['a', 'b', 'c']fn = lenfor item in alphabets: fn(item)",
"e": 967,
"s": 893,
"text": null
},
{
"code": null,
"e": 1117,
"s": 967,
"text": "You might think I’ve assigned an alias to the function ‘len’ and it might not make a difference.So i wrote a performance testing function as follows."
},
{
"code": "import datetimealphabets = [str(x)for x in range(10000000)]a = datetime.datetime.now() # store initial timefor item in alphabets: len(item)b = datetime.datetime.now() # store final timeprint (b-a).total_seconds() # resultsa = datetime.datetime.now()fn = len # function stored locallyfor item in alphabets: fn(item)b = datetime.datetime.now()print (b-a).total_seconds()",
"e": 1511,
"s": 1117,
"text": null
},
{
"code": null,
"e": 1617,
"s": 1511,
"text": "I encourage you to try it on your systems.Here’s the output on mine on running the performance.py script."
},
{
"code": null,
"e": 1630,
"s": 1617,
"text": "Almost half!"
},
{
"code": null,
"e": 1937,
"s": 1630,
"text": "Okay, now let’s try to analyse why this happened. Reason? Lookup for a function is a costly operation.In the second snippet, I stored the function directly in the scope of the function, so it doesn’t matter how many times I call it, each time the runtime knows exactly where it has to look for the results."
},
{
"code": null,
"e": 2355,
"s": 1937,
"text": "ItertoolsIf you’ve been to codeforces, you know by now that the a lot of programming challenges involve backtracking. So today I’ll tell you about a library to generate all permutations and combinations using a inbuilt library package which is extremely fast. Itertools. If you’re looking to solve algorithmic challenges with python then itertools is library you must definitely explore.To generate all permutations –"
},
{
"code": "from itertools import permutationsperm = permutations([1, 2, 3], 2)for i in list(perm): print i # Answer->(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)",
"e": 2512,
"s": 2355,
"text": null
},
{
"code": null,
"e": 2607,
"s": 2512,
"text": "The combinations() functions behaves similarly I encourage the readers to try it on their own."
},
{
"code": null,
"e": 2808,
"s": 2607,
"text": "Python is a slow language only if your code is not leveraging the power of it successfully. Do not feel like you are at a disadvantage if you’re a python coder, it’s actually very neat and very quick!"
},
{
"code": null,
"e": 2817,
"s": 2808,
"text": "ACM-ICPC"
},
{
"code": null,
"e": 2841,
"s": 2817,
"text": "Competitive Programming"
},
{
"code": null,
"e": 2848,
"s": 2841,
"text": "Python"
},
{
"code": null,
"e": 2946,
"s": 2848,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2973,
"s": 2946,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 3051,
"s": 2973,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 3089,
"s": 3051,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 3148,
"s": 3089,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 3196,
"s": 3148,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 3224,
"s": 3196,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3274,
"s": 3224,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3296,
"s": 3274,
"text": "Python map() function"
}
] |
size element method – Selenium Python
|
30 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use size method in Selenium. size method is used to get size of current element.
element.size
Example –
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
Now one can get size of this element with –
element.size
Let’s try to get element and its size at geeksforgeeks using size method.Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_id("gsc-i-id2") # get rectprint(element.size)
Output-
Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 585,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies"
},
{
"code": null,
"e": 702,
"s": 585,
"text": "This article revolves around how to use size method in Selenium. size method is used to get size of current element."
},
{
"code": null,
"e": 715,
"s": 702,
"text": "element.size"
},
{
"code": null,
"e": 725,
"s": 715,
"text": "Example –"
},
{
"code": "<input type=\"text\" name=\"passwd\" id=\"passwd-id\" />",
"e": 776,
"s": 725,
"text": null
},
{
"code": null,
"e": 857,
"s": 776,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": null,
"e": 1021,
"s": 857,
"text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")"
},
{
"code": null,
"e": 1067,
"s": 1021,
"text": "Also, to find multiple elements, we can use –"
},
{
"code": null,
"e": 1117,
"s": 1067,
"text": "elements = driver.find_elements_by_name(\"passwd\")"
},
{
"code": null,
"e": 1161,
"s": 1117,
"text": "Now one can get size of this element with –"
},
{
"code": null,
"e": 1174,
"s": 1161,
"text": "element.size"
},
{
"code": null,
"e": 1257,
"s": 1174,
"text": "Let’s try to get element and its size at geeksforgeeks using size method.Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_id(\"gsc-i-id2\") # get rectprint(element.size)",
"e": 1525,
"s": 1257,
"text": null
},
{
"code": null,
"e": 1533,
"s": 1525,
"text": "Output-"
},
{
"code": null,
"e": 1551,
"s": 1533,
"text": "Terminal Output –"
},
{
"code": null,
"e": 1567,
"s": 1551,
"text": "Python-selenium"
},
{
"code": null,
"e": 1576,
"s": 1567,
"text": "selenium"
},
{
"code": null,
"e": 1583,
"s": 1576,
"text": "Python"
},
{
"code": null,
"e": 1681,
"s": 1583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1713,
"s": 1681,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1740,
"s": 1713,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1761,
"s": 1740,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1784,
"s": 1761,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1815,
"s": 1784,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1871,
"s": 1815,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1913,
"s": 1871,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1955,
"s": 1913,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1994,
"s": 1955,
"text": "Python | Get unique values from a list"
}
] |
Create a Stop Watch using ReactJS
|
23 Feb, 2021
We can create Stop Watch in ReactJS using the following approach. Our StopWatch will have the functionality of Start, Pause, Resume and Reset.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app stopwatch
Step 2: After creating your project folder i.e. stopwatch, move to it using the following command.
cd stopwatch
Create a Components folder insider the src folder. Inside the Components folder create three different subfolders with the names StopWatch, Timer, ControlButtons. Now make a .jsx and a .css for each components.
Project Structure: It will look like the following.
Components used in our applications are:
Example: The outer component is StopWatch, the blue marked is the Timer, and the green-colored component will be denoted as ControlButtons.
index.js
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root'));
App.js
import './App.css';import StopWatch from './Components/StopWatch/StopWatch.js'; function App() { return ( <div className="App"> <StopWatch /> </div> );} export default App;
App.css
.App{ background-color: rgb(238, 238, 238); width: 100vw; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center;}
StopWatch.jsx
import React, { useState } from "react";import "./StopWatch.css";import Timer from "../Timer/Timer";import ControlButtons from "../ControlButtons/ControlButtons"; function StopWatch() { const [isActive, setIsActive] = useState(false); const [isPaused, setIsPaused] = useState(true); const [time, setTime] = useState(0); React.useEffect(() => { let interval = null; if (isActive && isPaused === false) { interval = setInterval(() => { setTime((time) => time + 10); }, 10); } else { clearInterval(interval); } return () => { clearInterval(interval); }; }, [isActive, isPaused]); const handleStart = () => { setIsActive(true); setIsPaused(false); }; const handlePauseResume = () => { setIsPaused(!isPaused); }; const handleReset = () => { setIsActive(false); setTime(0); }; return ( <div className="stop-watch"> <Timer time={time} /> <ControlButtons active={isActive} isPaused={isPaused} handleStart={handleStart} handlePauseResume={handlePauseResume} handleReset={handleReset} /> </div> );} export default StopWatch;
StopWatch.css
.stop-watch{ height: 85vh; width: 23vw; background-color: #0d0c1b; display: flex; flex-direction: column; align-items: center; justify-content: space-between;}
Three states used in the StopWatch component.
time: It stores the time elapsed since you pressed start.
isActive: It tells if the stop watch is in active state (i.e it is running, or it is being paused).
isPaused: It tells if the stop watch is in active state and is paused or not.
Timer.jsx
import React from "react";import "./Timer.css"; export default function Timer(props) { return ( <div className="timer"> <span className="digits"> {("0" + Math.floor((props.time / 60000) % 60)).slice(-2)}: </span> <span className="digits"> {("0" + Math.floor((props.time / 1000) % 60)).slice(-2)}. </span> <span className="digits mili-sec"> {("0" + ((props.time / 10) % 100)).slice(-2)} </span> </div> );}
Timer.css
.timer{ margin : 3rem 0; width: 100%; display: flex; height: 12%; justify-content: center; align-items: center;} .digits{ font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 3rem; color: #f5f5f5;} .mili-sec{ color: #e42a2a;}
ControlButtons.jsx
import React from "react";import "./ControlButtons.css"; export default function ControlButtons(props) { const StartButton = ( <div className="btn btn-one btn-start" onClick={props.handleStart}> Start </div> ); const ActiveButtons = ( <div className="btn-grp"> <div className="btn btn-two" onClick={props.handleReset}> Reset </div> <div className="btn btn-one" onClick={props.handlePauseResume}> {props.isPaused ? "Resume" : "Pause"} </div> </div> ); return ( <div className="Control-Buttons"> <div>{props.active ? ActiveButtons : StartButton}</div> </div> );}
ControlButtons.css
<pre>.Control-Buttons { margin: 3rem 0; width: 100%; box-sizing: border-box; display: flex; align-items: center; justify-content: center;} .btn-grp { display: flex; align-items: center; justify-content: space-around;} .btn { font-family: Verdana, Geneva, Tahoma, sans-serif; width: 10vw; height: 5vh; border-radius: 14px; margin: 0px 6px; display: flex; border: 2px solid #e42a2a; justify-content: center; align-items: center; cursor: pointer; color: #f5f5f5;} .btn-one{ background-color: #e42a2a;}
ControlButtons Rendering: If user haven’t started the stop watch then you are supposed to show only the start button. If the user have started the stop watch then you are supposed to show the reset and resume/pause buttons.
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Picked
React-Questions
Technical Scripter 2020
ReactJS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to do crud operations in ReactJS ?
How to create a multi-page website using React.js ?
How to Use Bootstrap with React?
React-Router Hooks
How to navigate on path by button click in react router ?
How to check the version of ReactJS ?
How to Create a Countdown Timer Using ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 195,
"s": 52,
"text": "We can create Stop Watch in ReactJS using the following approach. Our StopWatch will have the functionality of Start, Pause, Resume and Reset."
},
{
"code": null,
"e": 245,
"s": 195,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 309,
"s": 245,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 340,
"s": 309,
"text": "npx create-react-app stopwatch"
},
{
"code": null,
"e": 439,
"s": 340,
"text": "Step 2: After creating your project folder i.e. stopwatch, move to it using the following command."
},
{
"code": null,
"e": 452,
"s": 439,
"text": "cd stopwatch"
},
{
"code": null,
"e": 663,
"s": 452,
"text": "Create a Components folder insider the src folder. Inside the Components folder create three different subfolders with the names StopWatch, Timer, ControlButtons. Now make a .jsx and a .css for each components."
},
{
"code": null,
"e": 715,
"s": 663,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 756,
"s": 715,
"text": "Components used in our applications are:"
},
{
"code": null,
"e": 896,
"s": 756,
"text": "Example: The outer component is StopWatch, the blue marked is the Timer, and the green-colored component will be denoted as ControlButtons."
},
{
"code": null,
"e": 905,
"s": 896,
"text": "index.js"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root'));",
"e": 1117,
"s": 905,
"text": null
},
{
"code": null,
"e": 1124,
"s": 1117,
"text": "App.js"
},
{
"code": "import './App.css';import StopWatch from './Components/StopWatch/StopWatch.js'; function App() { return ( <div className=\"App\"> <StopWatch /> </div> );} export default App;",
"e": 1313,
"s": 1124,
"text": null
},
{
"code": null,
"e": 1321,
"s": 1313,
"text": "App.css"
},
{
"code": ".App{ background-color: rgb(238, 238, 238); width: 100vw; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center;}",
"e": 1487,
"s": 1321,
"text": null
},
{
"code": null,
"e": 1501,
"s": 1487,
"text": "StopWatch.jsx"
},
{
"code": "import React, { useState } from \"react\";import \"./StopWatch.css\";import Timer from \"../Timer/Timer\";import ControlButtons from \"../ControlButtons/ControlButtons\"; function StopWatch() { const [isActive, setIsActive] = useState(false); const [isPaused, setIsPaused] = useState(true); const [time, setTime] = useState(0); React.useEffect(() => { let interval = null; if (isActive && isPaused === false) { interval = setInterval(() => { setTime((time) => time + 10); }, 10); } else { clearInterval(interval); } return () => { clearInterval(interval); }; }, [isActive, isPaused]); const handleStart = () => { setIsActive(true); setIsPaused(false); }; const handlePauseResume = () => { setIsPaused(!isPaused); }; const handleReset = () => { setIsActive(false); setTime(0); }; return ( <div className=\"stop-watch\"> <Timer time={time} /> <ControlButtons active={isActive} isPaused={isPaused} handleStart={handleStart} handlePauseResume={handlePauseResume} handleReset={handleReset} /> </div> );} export default StopWatch;",
"e": 2659,
"s": 1501,
"text": null
},
{
"code": null,
"e": 2673,
"s": 2659,
"text": "StopWatch.css"
},
{
"code": ".stop-watch{ height: 85vh; width: 23vw; background-color: #0d0c1b; display: flex; flex-direction: column; align-items: center; justify-content: space-between;}",
"e": 2854,
"s": 2673,
"text": null
},
{
"code": null,
"e": 2900,
"s": 2854,
"text": "Three states used in the StopWatch component."
},
{
"code": null,
"e": 2958,
"s": 2900,
"text": "time: It stores the time elapsed since you pressed start."
},
{
"code": null,
"e": 3058,
"s": 2958,
"text": "isActive: It tells if the stop watch is in active state (i.e it is running, or it is being paused)."
},
{
"code": null,
"e": 3136,
"s": 3058,
"text": "isPaused: It tells if the stop watch is in active state and is paused or not."
},
{
"code": null,
"e": 3146,
"s": 3136,
"text": "Timer.jsx"
},
{
"code": "import React from \"react\";import \"./Timer.css\"; export default function Timer(props) { return ( <div className=\"timer\"> <span className=\"digits\"> {(\"0\" + Math.floor((props.time / 60000) % 60)).slice(-2)}: </span> <span className=\"digits\"> {(\"0\" + Math.floor((props.time / 1000) % 60)).slice(-2)}. </span> <span className=\"digits mili-sec\"> {(\"0\" + ((props.time / 10) % 100)).slice(-2)} </span> </div> );}",
"e": 3611,
"s": 3146,
"text": null
},
{
"code": null,
"e": 3621,
"s": 3611,
"text": "Timer.css"
},
{
"code": ".timer{ margin : 3rem 0; width: 100%; display: flex; height: 12%; justify-content: center; align-items: center;} .digits{ font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 3rem; color: #f5f5f5;} .mili-sec{ color: #e42a2a;}",
"e": 3889,
"s": 3621,
"text": null
},
{
"code": null,
"e": 3908,
"s": 3889,
"text": "ControlButtons.jsx"
},
{
"code": "import React from \"react\";import \"./ControlButtons.css\"; export default function ControlButtons(props) { const StartButton = ( <div className=\"btn btn-one btn-start\" onClick={props.handleStart}> Start </div> ); const ActiveButtons = ( <div className=\"btn-grp\"> <div className=\"btn btn-two\" onClick={props.handleReset}> Reset </div> <div className=\"btn btn-one\" onClick={props.handlePauseResume}> {props.isPaused ? \"Resume\" : \"Pause\"} </div> </div> ); return ( <div className=\"Control-Buttons\"> <div>{props.active ? ActiveButtons : StartButton}</div> </div> );}",
"e": 4570,
"s": 3908,
"text": null
},
{
"code": null,
"e": 4589,
"s": 4570,
"text": "ControlButtons.css"
},
{
"code": "<pre>.Control-Buttons { margin: 3rem 0; width: 100%; box-sizing: border-box; display: flex; align-items: center; justify-content: center;} .btn-grp { display: flex; align-items: center; justify-content: space-around;} .btn { font-family: Verdana, Geneva, Tahoma, sans-serif; width: 10vw; height: 5vh; border-radius: 14px; margin: 0px 6px; display: flex; border: 2px solid #e42a2a; justify-content: center; align-items: center; cursor: pointer; color: #f5f5f5;} .btn-one{ background-color: #e42a2a;}",
"e": 5114,
"s": 4589,
"text": null
},
{
"code": null,
"e": 5338,
"s": 5114,
"text": "ControlButtons Rendering: If user haven’t started the stop watch then you are supposed to show only the start button. If the user have started the stop watch then you are supposed to show the reset and resume/pause buttons."
},
{
"code": null,
"e": 5451,
"s": 5338,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 5461,
"s": 5451,
"text": "npm start"
},
{
"code": null,
"e": 5560,
"s": 5461,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 5567,
"s": 5560,
"text": "Picked"
},
{
"code": null,
"e": 5583,
"s": 5567,
"text": "React-Questions"
},
{
"code": null,
"e": 5607,
"s": 5583,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5615,
"s": 5607,
"text": "ReactJS"
},
{
"code": null,
"e": 5634,
"s": 5615,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5732,
"s": 5634,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5770,
"s": 5732,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 5797,
"s": 5770,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 5836,
"s": 5797,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 5875,
"s": 5836,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 5927,
"s": 5875,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 5960,
"s": 5927,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 5979,
"s": 5960,
"text": "React-Router Hooks"
},
{
"code": null,
"e": 6037,
"s": 5979,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 6075,
"s": 6037,
"text": "How to check the version of ReactJS ?"
}
] |
How to use R to download file from internet ?
|
09 Jul, 2021
In this article, we will be looking at the approach to download any type of file from the internet using R Programming Language. To download any type of file from the Internet download.file() function is used. This function can be used to download a file from the Internet.
Syntax: download.file(url, destfile, method, quiet = FALSE, mode = “w”, cacheOK = TRUE, extra = getOption(“download.file.extra”),headers = NULL, ...)
Parameters:
URL:-a character string (or longer vector e.g., for the “libcurl” method) naming the URL of a resource to be downloaded.
destfile:-a character string (or vector, see URL) with the name where the downloaded file is saved.
method:-Method to be used for downloading files.
Returns: It will save the downloaded file to the provided destination.
In this approach for Downloading any type of file using download.file() function in R language user just need to call the download.file() function which is one of the inbuilt functions of R language and passes the URL of the file which is needed to be downloaded and the destination address for saving the downloaded file.
Under this example, we will be simply assigning a URL variable to the link to a sample CSV file from the internet and setting the destination address for the downloaded file ad then calling the download.file() function and pass the URL and destination address as the parameter.
File to be downloaded: Sample-Spreadsheet-1000-rows
Program:
R
# Specify URL where file is storedurl <- "https://sample-videos.com/csv/Sample-Spreadsheet-1000-rows.csv" destination<- "C:/Users/Geetansh Sahni/Documents/downloaded_gfg.csv" download.file(url, destination)
Output:
Under this example, we will be simply assigning a URL variable to the link to a sample PDF file from the internet and setting the destination address for the downloaded file ad then calling the download.file() function and pass the URL and destination address as the parameter.
File to be downloaded: sample
Program:
R
# Specify URL where file is storedurl <- "https://cin.ufpe.br/~fbma/Crack/Cracking%20the%20Coding% 20Interview%20189%20Programming%20Questions%20 and%20Solutions.pdf" destination<- "C:/Users/Geetansh Sahni/Documents/downloaded_gfg.pdf" download.file(url, destination)
Output:
Picked
Web-scraping
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "In this article, we will be looking at the approach to download any type of file from the internet using R Programming Language. To download any type of file from the Internet download.file() function is used. This function can be used to download a file from the Internet."
},
{
"code": null,
"e": 452,
"s": 302,
"text": "Syntax: download.file(url, destfile, method, quiet = FALSE, mode = “w”, cacheOK = TRUE, extra = getOption(“download.file.extra”),headers = NULL, ...)"
},
{
"code": null,
"e": 464,
"s": 452,
"text": "Parameters:"
},
{
"code": null,
"e": 585,
"s": 464,
"text": "URL:-a character string (or longer vector e.g., for the “libcurl” method) naming the URL of a resource to be downloaded."
},
{
"code": null,
"e": 685,
"s": 585,
"text": "destfile:-a character string (or vector, see URL) with the name where the downloaded file is saved."
},
{
"code": null,
"e": 734,
"s": 685,
"text": "method:-Method to be used for downloading files."
},
{
"code": null,
"e": 805,
"s": 734,
"text": "Returns: It will save the downloaded file to the provided destination."
},
{
"code": null,
"e": 1128,
"s": 805,
"text": "In this approach for Downloading any type of file using download.file() function in R language user just need to call the download.file() function which is one of the inbuilt functions of R language and passes the URL of the file which is needed to be downloaded and the destination address for saving the downloaded file."
},
{
"code": null,
"e": 1406,
"s": 1128,
"text": "Under this example, we will be simply assigning a URL variable to the link to a sample CSV file from the internet and setting the destination address for the downloaded file ad then calling the download.file() function and pass the URL and destination address as the parameter."
},
{
"code": null,
"e": 1458,
"s": 1406,
"text": "File to be downloaded: Sample-Spreadsheet-1000-rows"
},
{
"code": null,
"e": 1467,
"s": 1458,
"text": "Program:"
},
{
"code": null,
"e": 1469,
"s": 1467,
"text": "R"
},
{
"code": "# Specify URL where file is storedurl <- \"https://sample-videos.com/csv/Sample-Spreadsheet-1000-rows.csv\" destination<- \"C:/Users/Geetansh Sahni/Documents/downloaded_gfg.csv\" download.file(url, destination)",
"e": 1678,
"s": 1469,
"text": null
},
{
"code": null,
"e": 1686,
"s": 1678,
"text": "Output:"
},
{
"code": null,
"e": 1964,
"s": 1686,
"text": "Under this example, we will be simply assigning a URL variable to the link to a sample PDF file from the internet and setting the destination address for the downloaded file ad then calling the download.file() function and pass the URL and destination address as the parameter."
},
{
"code": null,
"e": 1994,
"s": 1964,
"text": "File to be downloaded: sample"
},
{
"code": null,
"e": 2003,
"s": 1994,
"text": "Program:"
},
{
"code": null,
"e": 2005,
"s": 2003,
"text": "R"
},
{
"code": "# Specify URL where file is storedurl <- \"https://cin.ufpe.br/~fbma/Crack/Cracking%20the%20Coding% 20Interview%20189%20Programming%20Questions%20 and%20Solutions.pdf\" destination<- \"C:/Users/Geetansh Sahni/Documents/downloaded_gfg.pdf\" download.file(url, destination)",
"e": 2287,
"s": 2005,
"text": null
},
{
"code": null,
"e": 2295,
"s": 2287,
"text": "Output:"
},
{
"code": null,
"e": 2302,
"s": 2295,
"text": "Picked"
},
{
"code": null,
"e": 2315,
"s": 2302,
"text": "Web-scraping"
},
{
"code": null,
"e": 2326,
"s": 2315,
"text": "R Language"
},
{
"code": null,
"e": 2424,
"s": 2326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2476,
"s": 2424,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2534,
"s": 2476,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2569,
"s": 2534,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2607,
"s": 2569,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2624,
"s": 2607,
"text": "R - if statement"
},
{
"code": null,
"e": 2661,
"s": 2624,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 2710,
"s": 2661,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2753,
"s": 2710,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2790,
"s": 2753,
"text": "How to import an Excel File into R ?"
}
] |
Total position where king can reach on a chessboard in exactly M moves | Set 2
|
09 Jun, 2022
Given the position of the king on an 8 X 8 chessboard, the task is to count the total number of squares that can be visited by the king in m moves. The position of the king is denoted using row and column number. Note: The square which is currently acquired by the king is already visited and will be counted in the result.Examples:
Input: r = 4, c = 4, m = 1 Output: 9Input: r = 4, c = 4, m = 2 Output: 25
Approach: A king can move one square in any direction (i.e horizontally, vertically and diagonally). So, in one move king can visit its adjacent squares.
So, A square which is within m units distance (Considering 1 Square as 1 unit distance) from the king’s current position can be visited in m moves. For all squares of the chessboard, check if a particular square is at m unit distance away or less from King’s current position.
Increment count, if step 1 is true.Print the count
Increment count, if step 1 is true.
Print the count
Below is the implementation of the above approach:
C++
Java
C#
Python3
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of squares// that can be visited by king in m movesint countSquares(int r, int c, int m){ // To store the count of squares int squares = 0; // Check all squares of // the chessboard for (int i = 1; i <= 8; i++) { for (int j = 1; j <= 8; j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (max(abs(i - r), abs(j - c)) <= m) squares++; } } // Return count of squares return squares;} // Driver codeint main(){ int r = 4, c = 4, m = 1; cout << countSquares(r, c, m) << endl; return 0;}
// Java implementation of the approachclass GFG { // Function to return the count of squares // that can be visited by king in m moves static int countSquares(int r, int c, int m) { // To store the count of squares int squares = 0; // Check all squares of // the chessboard for (int i = 1; i <= 8; i++) { for (int j = 1; j <= 8; j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (Math.max(Math.abs(i - r), Math.abs(j - c)) <= m) squares++; } } // Return count of squares return squares; } // Driver code public static void main(String[] args) { int r = 4, c = 4, m = 1; System.out.print(countSquares(r, c, m)); }}
// C# implementation of the approachusing System;class GFG { // Function to return the count of squares // that can be visited by king in m moves static int countSquares(int r, int c, int m) { // To store the count of squares int squares = 0; // Check all squares of // the chessboard for (int i = 1; i <= 8; i++) { for (int j = 1; j <= 8; j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (Math.Max(Math.Abs(i - r), Math.Abs(j - c)) <= m) squares++; } } // Return count of squares return squares; } // Driver code public static void Main() { int r = 4, c = 4, m = 1; Console.Write(countSquares(r, c, m)); }}
# Python implementation of the approach # Function to return the count of squares# that can be visited by king in m movesdef countSquares(r, c, m): # To store the count of squares squares = 0 # Check all squares of # the chessboard for i in range (1, 9): for j in range (1, 9): # Check if square (i, j) is # at a distance <= m units # from king's current position if(max(abs(i - r), abs(j - c)) <= m): squares = squares + 1 # Return count of squares return squares # Driver coder = 4c = 4m = 1 print(countSquares(r, c, m));
<?php// PHP implementation of the approach // Function to return the count of squares// that can be visited by king in m movesfunction countSquares($r, $c, $m){ // To store the count of squares $squares = 0; // Check all squares of // the chessboard for ($i = 1; $i <= 8; $i++) { for ($j = 1; $j <= 8; $j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (max(abs($i - $r), abs($j - $c)) <= $m) $squares++; } } // Return count of squares return $squares;} // Driver code$r = 4;$c = 4;$m = 1; echo countSquares($r, $c, $m); // This code is contributed by Ryuga?>
<script> // Javascript implementation of the approach // Function to return the count of squares // that can be visited by king in m moves function countSquares(r, c, m) { // To store the count of squares let squares = 0; // Check all squares of // the chessboard for (let i = 1; i <= 8; i++) { for (let j = 1; j <= 8; j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (Math.max(Math.abs(i - r), Math.abs(j - c)) <= m) squares++; } } // Return count of squares return squares; } // Driver Code let r = 4, c = 4, m = 1; document.write(countSquares(r, c, m)); </script>
9
Time Complexity: O(1), since the loop runs for a total of 64 times, that is constant time only.Auxiliary Space: O(1), since no extra space has been taken.
ankthon
sanjoy_62
singhh3010
subhamkumarm348
chessboard-problems
Constructive Algorithms
math
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 363,
"s": 28,
"text": "Given the position of the king on an 8 X 8 chessboard, the task is to count the total number of squares that can be visited by the king in m moves. The position of the king is denoted using row and column number. Note: The square which is currently acquired by the king is already visited and will be counted in the result.Examples: "
},
{
"code": null,
"e": 438,
"s": 363,
"text": "Input: r = 4, c = 4, m = 1 Output: 9Input: r = 4, c = 4, m = 2 Output: 25 "
},
{
"code": null,
"e": 594,
"s": 438,
"text": "Approach: A king can move one square in any direction (i.e horizontally, vertically and diagonally). So, in one move king can visit its adjacent squares. "
},
{
"code": null,
"e": 871,
"s": 594,
"text": "So, A square which is within m units distance (Considering 1 Square as 1 unit distance) from the king’s current position can be visited in m moves. For all squares of the chessboard, check if a particular square is at m unit distance away or less from King’s current position."
},
{
"code": null,
"e": 922,
"s": 871,
"text": "Increment count, if step 1 is true.Print the count"
},
{
"code": null,
"e": 958,
"s": 922,
"text": "Increment count, if step 1 is true."
},
{
"code": null,
"e": 974,
"s": 958,
"text": "Print the count"
},
{
"code": null,
"e": 1025,
"s": 974,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1029,
"s": 1025,
"text": "C++"
},
{
"code": null,
"e": 1034,
"s": 1029,
"text": "Java"
},
{
"code": null,
"e": 1037,
"s": 1034,
"text": "C#"
},
{
"code": null,
"e": 1045,
"s": 1037,
"text": "Python3"
},
{
"code": null,
"e": 1049,
"s": 1045,
"text": "PHP"
},
{
"code": null,
"e": 1060,
"s": 1049,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of squares// that can be visited by king in m movesint countSquares(int r, int c, int m){ // To store the count of squares int squares = 0; // Check all squares of // the chessboard for (int i = 1; i <= 8; i++) { for (int j = 1; j <= 8; j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (max(abs(i - r), abs(j - c)) <= m) squares++; } } // Return count of squares return squares;} // Driver codeint main(){ int r = 4, c = 4, m = 1; cout << countSquares(r, c, m) << endl; return 0;}",
"e": 1817,
"s": 1060,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the count of squares // that can be visited by king in m moves static int countSquares(int r, int c, int m) { // To store the count of squares int squares = 0; // Check all squares of // the chessboard for (int i = 1; i <= 8; i++) { for (int j = 1; j <= 8; j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (Math.max(Math.abs(i - r), Math.abs(j - c)) <= m) squares++; } } // Return count of squares return squares; } // Driver code public static void main(String[] args) { int r = 4, c = 4, m = 1; System.out.print(countSquares(r, c, m)); }}",
"e": 2683,
"s": 1817,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG { // Function to return the count of squares // that can be visited by king in m moves static int countSquares(int r, int c, int m) { // To store the count of squares int squares = 0; // Check all squares of // the chessboard for (int i = 1; i <= 8; i++) { for (int j = 1; j <= 8; j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (Math.Max(Math.Abs(i - r), Math.Abs(j - c)) <= m) squares++; } } // Return count of squares return squares; } // Driver code public static void Main() { int r = 4, c = 4, m = 1; Console.Write(countSquares(r, c, m)); }}",
"e": 3544,
"s": 2683,
"text": null
},
{
"code": "# Python implementation of the approach # Function to return the count of squares# that can be visited by king in m movesdef countSquares(r, c, m): # To store the count of squares squares = 0 # Check all squares of # the chessboard for i in range (1, 9): for j in range (1, 9): # Check if square (i, j) is # at a distance <= m units # from king's current position if(max(abs(i - r), abs(j - c)) <= m): squares = squares + 1 # Return count of squares return squares # Driver coder = 4c = 4m = 1 print(countSquares(r, c, m));",
"e": 4183,
"s": 3544,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the count of squares// that can be visited by king in m movesfunction countSquares($r, $c, $m){ // To store the count of squares $squares = 0; // Check all squares of // the chessboard for ($i = 1; $i <= 8; $i++) { for ($j = 1; $j <= 8; $j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (max(abs($i - $r), abs($j - $c)) <= $m) $squares++; } } // Return count of squares return $squares;} // Driver code$r = 4;$c = 4;$m = 1; echo countSquares($r, $c, $m); // This code is contributed by Ryuga?>",
"e": 4922,
"s": 4183,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count of squares // that can be visited by king in m moves function countSquares(r, c, m) { // To store the count of squares let squares = 0; // Check all squares of // the chessboard for (let i = 1; i <= 8; i++) { for (let j = 1; j <= 8; j++) { // Check if square (i, j) is // at a distance <= m units // from king's current position if (Math.max(Math.abs(i - r), Math.abs(j - c)) <= m) squares++; } } // Return count of squares return squares; } // Driver Code let r = 4, c = 4, m = 1; document.write(countSquares(r, c, m)); </script>",
"e": 5749,
"s": 4922,
"text": null
},
{
"code": null,
"e": 5751,
"s": 5749,
"text": "9"
},
{
"code": null,
"e": 5908,
"s": 5753,
"text": "Time Complexity: O(1), since the loop runs for a total of 64 times, that is constant time only.Auxiliary Space: O(1), since no extra space has been taken."
},
{
"code": null,
"e": 5916,
"s": 5908,
"text": "ankthon"
},
{
"code": null,
"e": 5926,
"s": 5916,
"text": "sanjoy_62"
},
{
"code": null,
"e": 5937,
"s": 5926,
"text": "singhh3010"
},
{
"code": null,
"e": 5953,
"s": 5937,
"text": "subhamkumarm348"
},
{
"code": null,
"e": 5973,
"s": 5953,
"text": "chessboard-problems"
},
{
"code": null,
"e": 5997,
"s": 5973,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 6002,
"s": 5997,
"text": "math"
},
{
"code": null,
"e": 6015,
"s": 6002,
"text": "Mathematical"
},
{
"code": null,
"e": 6028,
"s": 6015,
"text": "Mathematical"
}
] |
Multiplication of two polynomials using Linked list
|
13 Sep, 2021
Given two polynomials in the form of linked list. The task is to find the multiplication of both polynomials.
Examples:
Input: Poly1: 3x^2 + 5x^1 + 6, Poly2: 6x^1 + 8
Output: 18x^3 + 54x^2 + 76x^1 + 48
On multiplying each element of 1st polynomial with
elements of 2nd polynomial, we get
18x^3 + 24x^2 + 30x^2 + 40x^1 + 36x^1 + 48
On adding values with same power of x,
18x^3 + 54x^2 + 76x^1 + 48
Input: Poly1: 3x^3 + 6x^1 - 9, Poly2: 9x^3 - 8x^2 + 7x^1 + 2
Output: 27x^6 - 24x^5 + 75x^4 - 123x^3 + 114x^2 - 51x^1 - 18
Approach:
In this approach we will multiply the 2nd polynomial with each term of 1st polynomial.Store the multiplied value in a new linked list.Then we will add the coefficients of elements having the same power in resultant polynomial.
In this approach we will multiply the 2nd polynomial with each term of 1st polynomial.
Store the multiplied value in a new linked list.
Then we will add the coefficients of elements having the same power in resultant polynomial.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Node structure containing powerer// and coefficient of variablestruct Node { int coeff, power; Node* next;}; // Function add a new node at the end of listNode* addnode(Node* start, int coeff, int power){ // Create a new node Node* newnode = new Node; newnode->coeff = coeff; newnode->power = power; newnode->next = NULL; // If linked list is empty if (start == NULL) return newnode; // If linked list has nodes Node* ptr = start; while (ptr->next != NULL) ptr = ptr->next; ptr->next = newnode; return start;} // Function To Display The Linked listvoid printList(struct Node* ptr){ while (ptr->next != NULL) { cout << ptr->coeff << "x^" << ptr->power ; if( ptr->next!=NULL && ptr->next->coeff >=0) cout << "+"; ptr = ptr->next; } cout << ptr->coeff << "\n";} // Function to add coefficients of// two elements having same powerervoid removeDuplicates(Node* start){ Node *ptr1, *ptr2, *dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != NULL && ptr1->next != NULL) { ptr2 = ptr1; // Compare the picked element // with rest of the elements while (ptr2->next != NULL) { // If powerer of two elements are same if (ptr1->power == ptr2->next->power) { // Add their coefficients and put it in 1st element ptr1->coeff = ptr1->coeff + ptr2->next->coeff; dup = ptr2->next; ptr2->next = ptr2->next->next; // remove the 2nd element delete (dup); } else ptr2 = ptr2->next; } ptr1 = ptr1->next; }} // Function two Multiply two polynomial NumbersNode* multiply(Node* poly1, Node* poly2, Node* poly3){ // Create two pointer and store the // address of 1st and 2nd polynomials Node *ptr1, *ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != NULL) { while (ptr2 != NULL) { int coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1->coeff * ptr2->coeff; // Add the powerer of both polynomials // and store it in power power = ptr1->power + ptr2->power; // Invoke addnode function to create // a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2->next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1->next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removeDuplicates(poly3); return poly3;} // Driver Codeint main(){ Node *poly1 = NULL, *poly2 = NULL, *poly3 = NULL; // Creation of 1st Polynomial: 3x^2 + 5x^1 + 6 poly1 = addnode(poly1, 3, 3); poly1 = addnode(poly1, 6, 1); poly1 = addnode(poly1, -9, 0); // Creation of 2nd polynomial: 6x^1 + 8 poly2 = addnode(poly2, 9, 3); poly2 = addnode(poly2, -8, 2); poly2 = addnode(poly2, 7, 1); poly2 = addnode(poly2, 2, 0); // Displaying 1st polynomial cout << "1st Polynomial:- "; printList(poly1); // Displaying 2nd polynomial cout << "2nd Polynomial:- "; printList(poly2); // calling multiply function poly3 = multiply(poly1, poly2, poly3); // Displaying Resultant Polynomial cout << "Resultant Polynomial:- "; printList(poly3); return 0;}
// Java implementation of above approachimport java.util.*;class GFG{ // Node structure containing powerer// and coefficient of variablestatic class Node { int coeff, power; Node next;}; // Function add a new node at the end of liststatic Node addnode(Node start, int coeff, int power){ // Create a new node Node newnode = new Node(); newnode.coeff = coeff; newnode.power = power; newnode.next = null; // If linked list is empty if (start == null) return newnode; // If linked list has nodes Node ptr = start; while (ptr.next != null) ptr = ptr.next; ptr.next = newnode; return start;} // Function To Display The Linked liststatic void printList( Node ptr){ while (ptr.next != null) { System.out.print( ptr.coeff + "x^" + ptr.power + " + "); ptr = ptr.next; } System.out.print( ptr.coeff +"\n");} // Function to add coefficients of// two elements having same powererstatic void removeDuplicates(Node start){ Node ptr1, ptr2, dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; // Compare the picked element // with rest of the elements while (ptr2.next != null) { // If powerer of two elements are same if (ptr1.power == ptr2.next.power) { // Add their coefficients and put it in 1st element ptr1.coeff = ptr1.coeff + ptr2.next.coeff; dup = ptr2.next; ptr2.next = ptr2.next.next; } else ptr2 = ptr2.next; } ptr1 = ptr1.next; }} // Function two Multiply two polynomial Numbersstatic Node multiply(Node poly1, Node poly2, Node poly3){ // Create two pointer and store the // address of 1st and 2nd polynomials Node ptr1, ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != null) { while (ptr2 != null) { int coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1.coeff * ptr2.coeff; // Add the powerer of both polynomials // and store it in power power = ptr1.power + ptr2.power; // Invoke addnode function to create // a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2.next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1.next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removeDuplicates(poly3); return poly3;} // Driver Codepublic static void main(String args[]){ Node poly1 = null, poly2 = null, poly3 = null; // Creation of 1st Polynomial: 3x^2 + 5x^1 + 6 poly1 = addnode(poly1, 3, 2); poly1 = addnode(poly1, 5, 1); poly1 = addnode(poly1, 6, 0); // Creation of 2nd polynomial: 6x^1 + 8 poly2 = addnode(poly2, 6, 1); poly2 = addnode(poly2, 8, 0); // Displaying 1st polynomial System.out.print("1st Polynomial:- "); printList(poly1); // Displaying 2nd polynomial System.out.print("2nd Polynomial:- "); printList(poly2); // calling multiply function poly3 = multiply(poly1, poly2, poly3); // Displaying Resultant Polynomial System.out.print( "Resultant Polynomial:- "); printList(poly3); } }// This code is contributed by Arnab Kundu
# Python3 implementation of the above approach # Node structure containing powerer# and coefficient of variableclass Node: def __init__(self): self.coeff = None self.power = None self.next = None # Function add a new node at the end of listdef addnode(start, coeff, power): # Create a new node newnode = Node(); newnode.coeff = coeff; newnode.power = power; newnode.next = None; # If linked list is empty if (start == None): return newnode; # If linked list has nodes ptr = start; while (ptr.next != None): ptr = ptr.next; ptr.next = newnode; return start; # Function To Display The Linked listdef printList(ptr): while (ptr.next != None): print(str(ptr.coeff) + 'x^' + str(ptr.power), end = '') if( ptr.next != None and ptr.next.coeff >= 0): print('+', end = '') ptr = ptr.next print(ptr.coeff) # Function to add coefficients of# two elements having same powererdef removeDuplicates(start): ptr2 = None dup = None ptr1 = start; # Pick elements one by one while (ptr1 != None and ptr1.next != None): ptr2 = ptr1; # Compare the picked element # with rest of the elements while (ptr2.next != None): # If powerer of two elements are same if (ptr1.power == ptr2.next.power): # Add their coefficients and put it in 1st element ptr1.coeff = ptr1.coeff + ptr2.next.coeff; dup = ptr2.next; ptr2.next = ptr2.next.next; else: ptr2 = ptr2.next; ptr1 = ptr1.next; # Function two Multiply two polynomial Numbersdef multiply(poly1, Npoly2, poly3): # Create two pointer and store the # address of 1st and 2nd polynomials ptr1 = poly1; ptr2 = poly2; while (ptr1 != None): while (ptr2 != None): # Multiply the coefficient of both # polynomials and store it in coeff coeff = ptr1.coeff * ptr2.coeff; # Add the powerer of both polynomials # and store it in power power = ptr1.power + ptr2.power; # Invoke addnode function to create # a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); # move the pointer of 2nd polynomial # two get its next term ptr2 = ptr2.next; # Move the 2nd pointer to the # starting point of 2nd polynomial ptr2 = poly2; # move the pointer of 1st polynomial ptr1 = ptr1.next; # this function will be invoke to add # the coefficient of the elements # having same powerer from the resultant linked list removeDuplicates(poly3); return poly3; # Driver Codeif __name__=='__main__': poly1 = None poly2 = None poly3 = None; # Creation of 1st Polynomial: 3x^2 + 5x^1 + 6 poly1 = addnode(poly1, 3, 3); poly1 = addnode(poly1, 6, 1); poly1 = addnode(poly1, -9, 0); # Creation of 2nd polynomial: 6x^1 + 8 poly2 = addnode(poly2, 9, 3); poly2 = addnode(poly2, -8, 2); poly2 = addnode(poly2, 7, 1); poly2 = addnode(poly2, 2, 0); # Displaying 1st polynomial print("1st Polynomial:- ", end = ''); printList(poly1); # Displaying 2nd polynomial print("2nd Polynomial:- ", end = ''); printList(poly2); # calling multiply function poly3 = multiply(poly1, poly2, poly3); # Displaying Resultant Polynomial print("Resultant Polynomial:- ", end = ''); printList(poly3); # This code is contributed by rutvik_56
// C# implementation of above approachusing System; class GFG{ // Node structure containing powerer// and coefficient of variablepublic class Node{ public int coeff, power; public Node next;}; // Function add a new node at the end of liststatic Node addnode(Node start, int coeff, int power){ // Create a new node Node newnode = new Node(); newnode.coeff = coeff; newnode.power = power; newnode.next = null; // If linked list is empty if (start == null) return newnode; // If linked list has nodes Node ptr = start; while (ptr.next != null) ptr = ptr.next; ptr.next = newnode; return start;} // Function To Display The Linked liststatic void printList( Node ptr){ while (ptr.next != null) { Console.Write( ptr.coeff + "x^" + ptr.power + " + "); ptr = ptr.next; } Console.Write( ptr.coeff +"\n");} // Function to add coefficients of// two elements having same powererstatic void removeDuplicates(Node start){ Node ptr1, ptr2, dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; // Compare the picked element // with rest of the elements while (ptr2.next != null) { // If powerer of two elements are same if (ptr1.power == ptr2.next.power) { // Add their coefficients and put it in 1st element ptr1.coeff = ptr1.coeff + ptr2.next.coeff; dup = ptr2.next; ptr2.next = ptr2.next.next; } else ptr2 = ptr2.next; } ptr1 = ptr1.next; }} // Function two Multiply two polynomial Numbersstatic Node multiply(Node poly1, Node poly2, Node poly3){ // Create two pointer and store the // address of 1st and 2nd polynomials Node ptr1, ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != null) { while (ptr2 != null) { int coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1.coeff * ptr2.coeff; // Add the powerer of both polynomials // and store it in power power = ptr1.power + ptr2.power; // Invoke addnode function to create // a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2.next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1.next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removeDuplicates(poly3); return poly3;} // Driver Codepublic static void Main(String []args){ Node poly1 = null, poly2 = null, poly3 = null; // Creation of 1st Polynomial: 3x^2 + 5x^1 + 6 poly1 = addnode(poly1, 3, 2); poly1 = addnode(poly1, 5, 1); poly1 = addnode(poly1, 6, 0); // Creation of 2nd polynomial: 6x^1 + 8 poly2 = addnode(poly2, 6, 1); poly2 = addnode(poly2, 8, 0); // Displaying 1st polynomial Console.Write("1st Polynomial:- "); printList(poly1); // Displaying 2nd polynomial Console.Write("2nd Polynomial:- "); printList(poly2); // calling multiply function poly3 = multiply(poly1, poly2, poly3); // Displaying Resultant Polynomial Console.Write( "Resultant Polynomial:- "); printList(poly3);}} // This code has been contributed by 29AjayKumar
<script> // Javascript implementation of above approach // Link list nodeclass Node { constructor() { this.coeff = 0; this.power = 0; this.next = null; } } // Function add a new node at the end of listfunction addnode(start, coeff, power){ // Create a new node var newnode = new Node(); newnode.coeff = coeff; newnode.power = power; newnode.next = null; // If linked list is empty if (start == null) return newnode; // If linked list has nodes var ptr = start; while (ptr.next != null) ptr = ptr.next; ptr.next = newnode; return start;} // Function To Display The Linked listfunction printList( ptr){ while (ptr.next != null) { document.write( ptr.coeff + "x^" + ptr.power + " + "); ptr = ptr.next; } document.write( ptr.coeff +"</br>");} // Function to add coefficients of// two elements having same powererfunction removeDuplicates( start){ var ptr1, ptr2, dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; // Compare the picked element // with rest of the elements while (ptr2.next != null) { // If powerer of two elements are same if (ptr1.power == ptr2.next.power) { // Add their coefficients and put it in 1st element ptr1.coeff = ptr1.coeff + ptr2.next.coeff; dup = ptr2.next; ptr2.next = ptr2.next.next; } else ptr2 = ptr2.next; } ptr1 = ptr1.next; }} // Function two Multiply two polynomial Numbersfunction multiply( poly1, poly2, poly3){ // Create two pointer and store the // address of 1st and 2nd polynomials var ptr1, ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != null) { while (ptr2 != null) { let coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1.coeff * ptr2.coeff; // Add the powerer of both polynomials // and store it in power power = ptr1.power + ptr2.power; // Invoke addnode function to create // a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2.next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1.next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removeDuplicates(poly3); return poly3;} // Driver Code var poly1 = null, poly2 = null, poly3 = null; // Creation of 1st Polynomial: 3x^2 + 5x^1 + 6poly1 = addnode(poly1, 3, 2);poly1 = addnode(poly1, 5, 1);poly1 = addnode(poly1, 6, 0); // Creation of 2nd polynomial: 6x^1 + 8poly2 = addnode(poly2, 6, 1);poly2 = addnode(poly2, 8, 0); // Displaying 1st polynomialdocument.write("1st Polynomial:- ");printList(poly1); // Displaying 2nd polynomialdocument.write("2nd Polynomial:- ");printList(poly2); // calling multiply functionpoly3 = multiply(poly1, poly2, poly3); // Displaying Resultant Polynomialdocument.write( "Resultant Polynomial:- ");printList(poly3); // This code is contributed by jana_sayantan. </script>
1st Polynomial:- 3x^3+6x^1-9
2nd Polynomial:- 9x^3-8x^2+7x^1+2
Resultant Polynomial:- 27x^6-24x^5+75x^4-123x^3+114x^2-51x^1-18
andrew1234
29AjayKumar
aniket173000
rutvik_56
jana_sayantan
surindertarika1234
Linked-List-Polynomial
maths-polynomial
Technical Scripter 2018
Linked List
Technical Scripter
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion)
Detect loop in a linked list
Merge two sorted linked lists
What is Data Structure: Types, Classifications and Applications
Find the middle of a given linked list
Linked List vs Array
Merge Sort for Linked Lists
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 164,
"s": 54,
"text": "Given two polynomials in the form of linked list. The task is to find the multiplication of both polynomials."
},
{
"code": null,
"e": 175,
"s": 164,
"text": "Examples: "
},
{
"code": null,
"e": 576,
"s": 175,
"text": "Input: Poly1: 3x^2 + 5x^1 + 6, Poly2: 6x^1 + 8\nOutput: 18x^3 + 54x^2 + 76x^1 + 48\nOn multiplying each element of 1st polynomial with \nelements of 2nd polynomial, we get\n18x^3 + 24x^2 + 30x^2 + 40x^1 + 36x^1 + 48\nOn adding values with same power of x,\n18x^3 + 54x^2 + 76x^1 + 48\n\nInput: Poly1: 3x^3 + 6x^1 - 9, Poly2: 9x^3 - 8x^2 + 7x^1 + 2\nOutput: 27x^6 - 24x^5 + 75x^4 - 123x^3 + 114x^2 - 51x^1 - 18"
},
{
"code": null,
"e": 587,
"s": 576,
"text": "Approach: "
},
{
"code": null,
"e": 814,
"s": 587,
"text": "In this approach we will multiply the 2nd polynomial with each term of 1st polynomial.Store the multiplied value in a new linked list.Then we will add the coefficients of elements having the same power in resultant polynomial."
},
{
"code": null,
"e": 901,
"s": 814,
"text": "In this approach we will multiply the 2nd polynomial with each term of 1st polynomial."
},
{
"code": null,
"e": 950,
"s": 901,
"text": "Store the multiplied value in a new linked list."
},
{
"code": null,
"e": 1043,
"s": 950,
"text": "Then we will add the coefficients of elements having the same power in resultant polynomial."
},
{
"code": null,
"e": 1095,
"s": 1043,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1099,
"s": 1095,
"text": "C++"
},
{
"code": null,
"e": 1104,
"s": 1099,
"text": "Java"
},
{
"code": null,
"e": 1112,
"s": 1104,
"text": "Python3"
},
{
"code": null,
"e": 1115,
"s": 1112,
"text": "C#"
},
{
"code": null,
"e": 1126,
"s": 1115,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Node structure containing powerer// and coefficient of variablestruct Node { int coeff, power; Node* next;}; // Function add a new node at the end of listNode* addnode(Node* start, int coeff, int power){ // Create a new node Node* newnode = new Node; newnode->coeff = coeff; newnode->power = power; newnode->next = NULL; // If linked list is empty if (start == NULL) return newnode; // If linked list has nodes Node* ptr = start; while (ptr->next != NULL) ptr = ptr->next; ptr->next = newnode; return start;} // Function To Display The Linked listvoid printList(struct Node* ptr){ while (ptr->next != NULL) { cout << ptr->coeff << \"x^\" << ptr->power ; if( ptr->next!=NULL && ptr->next->coeff >=0) cout << \"+\"; ptr = ptr->next; } cout << ptr->coeff << \"\\n\";} // Function to add coefficients of// two elements having same powerervoid removeDuplicates(Node* start){ Node *ptr1, *ptr2, *dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != NULL && ptr1->next != NULL) { ptr2 = ptr1; // Compare the picked element // with rest of the elements while (ptr2->next != NULL) { // If powerer of two elements are same if (ptr1->power == ptr2->next->power) { // Add their coefficients and put it in 1st element ptr1->coeff = ptr1->coeff + ptr2->next->coeff; dup = ptr2->next; ptr2->next = ptr2->next->next; // remove the 2nd element delete (dup); } else ptr2 = ptr2->next; } ptr1 = ptr1->next; }} // Function two Multiply two polynomial NumbersNode* multiply(Node* poly1, Node* poly2, Node* poly3){ // Create two pointer and store the // address of 1st and 2nd polynomials Node *ptr1, *ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != NULL) { while (ptr2 != NULL) { int coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1->coeff * ptr2->coeff; // Add the powerer of both polynomials // and store it in power power = ptr1->power + ptr2->power; // Invoke addnode function to create // a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2->next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1->next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removeDuplicates(poly3); return poly3;} // Driver Codeint main(){ Node *poly1 = NULL, *poly2 = NULL, *poly3 = NULL; // Creation of 1st Polynomial: 3x^2 + 5x^1 + 6 poly1 = addnode(poly1, 3, 3); poly1 = addnode(poly1, 6, 1); poly1 = addnode(poly1, -9, 0); // Creation of 2nd polynomial: 6x^1 + 8 poly2 = addnode(poly2, 9, 3); poly2 = addnode(poly2, -8, 2); poly2 = addnode(poly2, 7, 1); poly2 = addnode(poly2, 2, 0); // Displaying 1st polynomial cout << \"1st Polynomial:- \"; printList(poly1); // Displaying 2nd polynomial cout << \"2nd Polynomial:- \"; printList(poly2); // calling multiply function poly3 = multiply(poly1, poly2, poly3); // Displaying Resultant Polynomial cout << \"Resultant Polynomial:- \"; printList(poly3); return 0;}",
"e": 4942,
"s": 1126,
"text": null
},
{
"code": "// Java implementation of above approachimport java.util.*;class GFG{ // Node structure containing powerer// and coefficient of variablestatic class Node { int coeff, power; Node next;}; // Function add a new node at the end of liststatic Node addnode(Node start, int coeff, int power){ // Create a new node Node newnode = new Node(); newnode.coeff = coeff; newnode.power = power; newnode.next = null; // If linked list is empty if (start == null) return newnode; // If linked list has nodes Node ptr = start; while (ptr.next != null) ptr = ptr.next; ptr.next = newnode; return start;} // Function To Display The Linked liststatic void printList( Node ptr){ while (ptr.next != null) { System.out.print( ptr.coeff + \"x^\" + ptr.power + \" + \"); ptr = ptr.next; } System.out.print( ptr.coeff +\"\\n\");} // Function to add coefficients of// two elements having same powererstatic void removeDuplicates(Node start){ Node ptr1, ptr2, dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; // Compare the picked element // with rest of the elements while (ptr2.next != null) { // If powerer of two elements are same if (ptr1.power == ptr2.next.power) { // Add their coefficients and put it in 1st element ptr1.coeff = ptr1.coeff + ptr2.next.coeff; dup = ptr2.next; ptr2.next = ptr2.next.next; } else ptr2 = ptr2.next; } ptr1 = ptr1.next; }} // Function two Multiply two polynomial Numbersstatic Node multiply(Node poly1, Node poly2, Node poly3){ // Create two pointer and store the // address of 1st and 2nd polynomials Node ptr1, ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != null) { while (ptr2 != null) { int coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1.coeff * ptr2.coeff; // Add the powerer of both polynomials // and store it in power power = ptr1.power + ptr2.power; // Invoke addnode function to create // a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2.next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1.next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removeDuplicates(poly3); return poly3;} // Driver Codepublic static void main(String args[]){ Node poly1 = null, poly2 = null, poly3 = null; // Creation of 1st Polynomial: 3x^2 + 5x^1 + 6 poly1 = addnode(poly1, 3, 2); poly1 = addnode(poly1, 5, 1); poly1 = addnode(poly1, 6, 0); // Creation of 2nd polynomial: 6x^1 + 8 poly2 = addnode(poly2, 6, 1); poly2 = addnode(poly2, 8, 0); // Displaying 1st polynomial System.out.print(\"1st Polynomial:- \"); printList(poly1); // Displaying 2nd polynomial System.out.print(\"2nd Polynomial:- \"); printList(poly2); // calling multiply function poly3 = multiply(poly1, poly2, poly3); // Displaying Resultant Polynomial System.out.print( \"Resultant Polynomial:- \"); printList(poly3); } }// This code is contributed by Arnab Kundu",
"e": 8622,
"s": 4942,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Node structure containing powerer# and coefficient of variableclass Node: def __init__(self): self.coeff = None self.power = None self.next = None # Function add a new node at the end of listdef addnode(start, coeff, power): # Create a new node newnode = Node(); newnode.coeff = coeff; newnode.power = power; newnode.next = None; # If linked list is empty if (start == None): return newnode; # If linked list has nodes ptr = start; while (ptr.next != None): ptr = ptr.next; ptr.next = newnode; return start; # Function To Display The Linked listdef printList(ptr): while (ptr.next != None): print(str(ptr.coeff) + 'x^' + str(ptr.power), end = '') if( ptr.next != None and ptr.next.coeff >= 0): print('+', end = '') ptr = ptr.next print(ptr.coeff) # Function to add coefficients of# two elements having same powererdef removeDuplicates(start): ptr2 = None dup = None ptr1 = start; # Pick elements one by one while (ptr1 != None and ptr1.next != None): ptr2 = ptr1; # Compare the picked element # with rest of the elements while (ptr2.next != None): # If powerer of two elements are same if (ptr1.power == ptr2.next.power): # Add their coefficients and put it in 1st element ptr1.coeff = ptr1.coeff + ptr2.next.coeff; dup = ptr2.next; ptr2.next = ptr2.next.next; else: ptr2 = ptr2.next; ptr1 = ptr1.next; # Function two Multiply two polynomial Numbersdef multiply(poly1, Npoly2, poly3): # Create two pointer and store the # address of 1st and 2nd polynomials ptr1 = poly1; ptr2 = poly2; while (ptr1 != None): while (ptr2 != None): # Multiply the coefficient of both # polynomials and store it in coeff coeff = ptr1.coeff * ptr2.coeff; # Add the powerer of both polynomials # and store it in power power = ptr1.power + ptr2.power; # Invoke addnode function to create # a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); # move the pointer of 2nd polynomial # two get its next term ptr2 = ptr2.next; # Move the 2nd pointer to the # starting point of 2nd polynomial ptr2 = poly2; # move the pointer of 1st polynomial ptr1 = ptr1.next; # this function will be invoke to add # the coefficient of the elements # having same powerer from the resultant linked list removeDuplicates(poly3); return poly3; # Driver Codeif __name__=='__main__': poly1 = None poly2 = None poly3 = None; # Creation of 1st Polynomial: 3x^2 + 5x^1 + 6 poly1 = addnode(poly1, 3, 3); poly1 = addnode(poly1, 6, 1); poly1 = addnode(poly1, -9, 0); # Creation of 2nd polynomial: 6x^1 + 8 poly2 = addnode(poly2, 9, 3); poly2 = addnode(poly2, -8, 2); poly2 = addnode(poly2, 7, 1); poly2 = addnode(poly2, 2, 0); # Displaying 1st polynomial print(\"1st Polynomial:- \", end = ''); printList(poly1); # Displaying 2nd polynomial print(\"2nd Polynomial:- \", end = ''); printList(poly2); # calling multiply function poly3 = multiply(poly1, poly2, poly3); # Displaying Resultant Polynomial print(\"Resultant Polynomial:- \", end = ''); printList(poly3); # This code is contributed by rutvik_56",
"e": 12282,
"s": 8622,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ // Node structure containing powerer// and coefficient of variablepublic class Node{ public int coeff, power; public Node next;}; // Function add a new node at the end of liststatic Node addnode(Node start, int coeff, int power){ // Create a new node Node newnode = new Node(); newnode.coeff = coeff; newnode.power = power; newnode.next = null; // If linked list is empty if (start == null) return newnode; // If linked list has nodes Node ptr = start; while (ptr.next != null) ptr = ptr.next; ptr.next = newnode; return start;} // Function To Display The Linked liststatic void printList( Node ptr){ while (ptr.next != null) { Console.Write( ptr.coeff + \"x^\" + ptr.power + \" + \"); ptr = ptr.next; } Console.Write( ptr.coeff +\"\\n\");} // Function to add coefficients of// two elements having same powererstatic void removeDuplicates(Node start){ Node ptr1, ptr2, dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; // Compare the picked element // with rest of the elements while (ptr2.next != null) { // If powerer of two elements are same if (ptr1.power == ptr2.next.power) { // Add their coefficients and put it in 1st element ptr1.coeff = ptr1.coeff + ptr2.next.coeff; dup = ptr2.next; ptr2.next = ptr2.next.next; } else ptr2 = ptr2.next; } ptr1 = ptr1.next; }} // Function two Multiply two polynomial Numbersstatic Node multiply(Node poly1, Node poly2, Node poly3){ // Create two pointer and store the // address of 1st and 2nd polynomials Node ptr1, ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != null) { while (ptr2 != null) { int coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1.coeff * ptr2.coeff; // Add the powerer of both polynomials // and store it in power power = ptr1.power + ptr2.power; // Invoke addnode function to create // a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2.next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1.next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removeDuplicates(poly3); return poly3;} // Driver Codepublic static void Main(String []args){ Node poly1 = null, poly2 = null, poly3 = null; // Creation of 1st Polynomial: 3x^2 + 5x^1 + 6 poly1 = addnode(poly1, 3, 2); poly1 = addnode(poly1, 5, 1); poly1 = addnode(poly1, 6, 0); // Creation of 2nd polynomial: 6x^1 + 8 poly2 = addnode(poly2, 6, 1); poly2 = addnode(poly2, 8, 0); // Displaying 1st polynomial Console.Write(\"1st Polynomial:- \"); printList(poly1); // Displaying 2nd polynomial Console.Write(\"2nd Polynomial:- \"); printList(poly2); // calling multiply function poly3 = multiply(poly1, poly2, poly3); // Displaying Resultant Polynomial Console.Write( \"Resultant Polynomial:- \"); printList(poly3);}} // This code has been contributed by 29AjayKumar",
"e": 15990,
"s": 12282,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // Link list nodeclass Node { constructor() { this.coeff = 0; this.power = 0; this.next = null; } } // Function add a new node at the end of listfunction addnode(start, coeff, power){ // Create a new node var newnode = new Node(); newnode.coeff = coeff; newnode.power = power; newnode.next = null; // If linked list is empty if (start == null) return newnode; // If linked list has nodes var ptr = start; while (ptr.next != null) ptr = ptr.next; ptr.next = newnode; return start;} // Function To Display The Linked listfunction printList( ptr){ while (ptr.next != null) { document.write( ptr.coeff + \"x^\" + ptr.power + \" + \"); ptr = ptr.next; } document.write( ptr.coeff +\"</br>\");} // Function to add coefficients of// two elements having same powererfunction removeDuplicates( start){ var ptr1, ptr2, dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; // Compare the picked element // with rest of the elements while (ptr2.next != null) { // If powerer of two elements are same if (ptr1.power == ptr2.next.power) { // Add their coefficients and put it in 1st element ptr1.coeff = ptr1.coeff + ptr2.next.coeff; dup = ptr2.next; ptr2.next = ptr2.next.next; } else ptr2 = ptr2.next; } ptr1 = ptr1.next; }} // Function two Multiply two polynomial Numbersfunction multiply( poly1, poly2, poly3){ // Create two pointer and store the // address of 1st and 2nd polynomials var ptr1, ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != null) { while (ptr2 != null) { let coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1.coeff * ptr2.coeff; // Add the powerer of both polynomials // and store it in power power = ptr1.power + ptr2.power; // Invoke addnode function to create // a newnode by passing three parameters poly3 = addnode(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2.next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1.next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removeDuplicates(poly3); return poly3;} // Driver Code var poly1 = null, poly2 = null, poly3 = null; // Creation of 1st Polynomial: 3x^2 + 5x^1 + 6poly1 = addnode(poly1, 3, 2);poly1 = addnode(poly1, 5, 1);poly1 = addnode(poly1, 6, 0); // Creation of 2nd polynomial: 6x^1 + 8poly2 = addnode(poly2, 6, 1);poly2 = addnode(poly2, 8, 0); // Displaying 1st polynomialdocument.write(\"1st Polynomial:- \");printList(poly1); // Displaying 2nd polynomialdocument.write(\"2nd Polynomial:- \");printList(poly2); // calling multiply functionpoly3 = multiply(poly1, poly2, poly3); // Displaying Resultant Polynomialdocument.write( \"Resultant Polynomial:- \");printList(poly3); // This code is contributed by jana_sayantan. </script>",
"e": 19549,
"s": 15990,
"text": null
},
{
"code": null,
"e": 19676,
"s": 19549,
"text": "1st Polynomial:- 3x^3+6x^1-9\n2nd Polynomial:- 9x^3-8x^2+7x^1+2\nResultant Polynomial:- 27x^6-24x^5+75x^4-123x^3+114x^2-51x^1-18"
},
{
"code": null,
"e": 19687,
"s": 19676,
"text": "andrew1234"
},
{
"code": null,
"e": 19699,
"s": 19687,
"text": "29AjayKumar"
},
{
"code": null,
"e": 19712,
"s": 19699,
"text": "aniket173000"
},
{
"code": null,
"e": 19722,
"s": 19712,
"text": "rutvik_56"
},
{
"code": null,
"e": 19736,
"s": 19722,
"text": "jana_sayantan"
},
{
"code": null,
"e": 19755,
"s": 19736,
"text": "surindertarika1234"
},
{
"code": null,
"e": 19778,
"s": 19755,
"text": "Linked-List-Polynomial"
},
{
"code": null,
"e": 19795,
"s": 19778,
"text": "maths-polynomial"
},
{
"code": null,
"e": 19819,
"s": 19795,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 19831,
"s": 19819,
"text": "Linked List"
},
{
"code": null,
"e": 19850,
"s": 19831,
"text": "Technical Scripter"
},
{
"code": null,
"e": 19862,
"s": 19850,
"text": "Linked List"
},
{
"code": null,
"e": 19960,
"s": 19862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19979,
"s": 19960,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 20011,
"s": 19979,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 20067,
"s": 20011,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 20096,
"s": 20067,
"text": "Detect loop in a linked list"
},
{
"code": null,
"e": 20126,
"s": 20096,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 20190,
"s": 20126,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 20229,
"s": 20190,
"text": "Find the middle of a given linked list"
},
{
"code": null,
"e": 20250,
"s": 20229,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 20278,
"s": 20250,
"text": "Merge Sort for Linked Lists"
}
] |
C++ Program to Implement Deque in STL
|
Double Ended Queue is a Queue data structure in which the insertion and deletion operations are performed at both the ends (front and rear). Data can be inserted at both front and rear positions and can be deleted from both front and rear positions.
Begin
Declare deque vector and iterator.
Take the input as per choice.
Call the functions within switch operation:
d.size() = Returns the size of queue.
d.push_back() = It is used to push elements into a deque from the back.
d.push_front() = It is used to push elements into a deque from the front.
d.pop_back() = It is used to pop or remove elements from a deque from the back.
d.pop_front() = It is used to pop or remove elements from a deque from the front.
d.front() = Returns the front elements of deque.
d.back() = Returns the back elements of deque.
Print the elements of deque.
End.
#include<iostream>
#include <deque>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
deque<int> d;
deque<int>::iterator it;
int c, item;
while (1) {
cout<<"1.Size of the Deque"<<endl;
cout<<"2.Insert Element at the End"<<endl;
cout<<"3.Insert Element at the Front"<<endl;
cout<<"4.Delete Element at the End"<<endl;
cout<<"5.Delete Element at the Front"<<endl;
cout<<"6.Front Element at Deque"<<endl;
cout<<"7.Last Element at Deque"<<endl;
cout<<"8.Display Deque"<<endl;
cout<<"9.Exit"<<endl;
cout<<"Enter your Choice: ";
cin>>c;
switch(c) {
case 1:
cout<<"Size of the Deque: "<<d.size()<<endl;
break;
case 2:
cout<<"Enter value to be inserted at the end: ";
cin>>item;
d.push_back(item);
break;
case 3:
cout<<"Enter value to be inserted at the front: ";
cin>>item;
d.push_front(item);
break;
case 4:
item = d.back();
d.pop_back();
cout<<"Element "<<item<<" deleted"<<endl;
break;
case 5:
item = d.front();
d.pop_front();
cout<<"Element "<<item<<" deleted"<<endl;
break;
case 6:
cout<<"Front Element of the Deque: ";
cout<<d.front()<<endl;
break;
case 7:
cout<<"Back Element of the Deque: ";
cout<<d.back()<<endl;
break;
case 8:
cout<<"Elements of Deque: ";
for (it = d.begin(); it != d.end(); it++)
cout<<*it<<" ";
cout<<endl;
break;
case 9:
exit(1);
break;
default:
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 1
Size of the Deque: 0
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 2
Enter value to be inserted at the end: 1
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 3
Enter value to be inserted at the front: 2
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 6
Front Element of the Deque: 2
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 7
Back Element of the Deque: 1
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 1
Size of the Deque: 2
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 8
Elements of Deque: 2 1
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 2
Enter value to be inserted at the end: 4
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 3
Enter value to be inserted at the front: 5
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 8
Elements of Deque: 5 2 1 4
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 4
Element 4 deleted
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 5
Element 5 deleted
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 8
Elements of Deque: 2 1
1.Size of the Deque
2.Insert Element at the End
3.Insert Element at the Front
4.Delete Element at the End
5.Delete Element at the Front
6.Front Element at Deque
7.Last Element at Deque
8.Display Deque
9.Exit
Enter your Choice: 9
|
[
{
"code": null,
"e": 1312,
"s": 1062,
"text": "Double Ended Queue is a Queue data structure in which the insertion and deletion operations are performed at both the ends (front and rear). Data can be inserted at both front and rear positions and can be deleted from both front and rear positions."
},
{
"code": null,
"e": 1936,
"s": 1312,
"text": "Begin\n Declare deque vector and iterator.\n Take the input as per choice.\n Call the functions within switch operation:\n d.size() = Returns the size of queue.\n d.push_back() = It is used to push elements into a deque from the back.\n d.push_front() = It is used to push elements into a deque from the front.\n d.pop_back() = It is used to pop or remove elements from a deque from the back.\n d.pop_front() = It is used to pop or remove elements from a deque from the front.\n d.front() = Returns the front elements of deque.\n d.back() = Returns the back elements of deque.\n Print the elements of deque.\nEnd."
},
{
"code": null,
"e": 3815,
"s": 1936,
"text": "#include<iostream>\n#include <deque>\n#include <string>\n#include <cstdlib>\nusing namespace std;\nint main() {\n deque<int> d;\n deque<int>::iterator it;\n int c, item;\n while (1) {\n cout<<\"1.Size of the Deque\"<<endl;\n cout<<\"2.Insert Element at the End\"<<endl;\n cout<<\"3.Insert Element at the Front\"<<endl;\n cout<<\"4.Delete Element at the End\"<<endl;\n cout<<\"5.Delete Element at the Front\"<<endl;\n cout<<\"6.Front Element at Deque\"<<endl;\n cout<<\"7.Last Element at Deque\"<<endl;\n cout<<\"8.Display Deque\"<<endl;\n cout<<\"9.Exit\"<<endl;\n cout<<\"Enter your Choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Size of the Deque: \"<<d.size()<<endl;\n break;\n case 2:\n cout<<\"Enter value to be inserted at the end: \";\n cin>>item;\n d.push_back(item);\n break;\n case 3:\n cout<<\"Enter value to be inserted at the front: \";\n cin>>item;\n d.push_front(item);\n break;\n case 4:\n item = d.back();\n d.pop_back();\n cout<<\"Element \"<<item<<\" deleted\"<<endl;\n break;\n case 5:\n item = d.front();\n d.pop_front();\n cout<<\"Element \"<<item<<\" deleted\"<<endl;\n break;\n case 6:\n cout<<\"Front Element of the Deque: \";\n cout<<d.front()<<endl;\n break;\n case 7:\n cout<<\"Back Element of the Deque: \";\n cout<<d.back()<<endl;\n break;\n case 8:\n cout<<\"Elements of Deque: \";\n for (it = d.begin(); it != d.end(); it++)\n cout<<*it<<\" \";\n cout<<endl;\n break;\n case 9:\n exit(1);\n break;\n default:\n cout<<\"Wrong Choice\"<<endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 7412,
"s": 3815,
"text": "1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 1\nSize of the Deque: 0\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 2\nEnter value to be inserted at the end: 1\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 3\nEnter value to be inserted at the front: 2\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 6\nFront Element of the Deque: 2\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 7\nBack Element of the Deque: 1\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 1\nSize of the Deque: 2\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 8\nElements of Deque: 2 1\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 2\nEnter value to be inserted at the end: 4\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 3\nEnter value to be inserted at the front: 5\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 8\nElements of Deque: 5 2 1 4\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 4\nElement 4 deleted\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 5\nElement 5 deleted\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\n\nEnter your Choice: 8\nElements of Deque: 2 1\n1.Size of the Deque\n2.Insert Element at the End\n3.Insert Element at the Front\n4.Delete Element at the End\n5.Delete Element at the Front\n6.Front Element at Deque\n7.Last Element at Deque\n8.Display Deque\n9.Exit\nEnter your Choice: 9"
}
] |
How to set NOW() as default value for datetime datatype in MySQL?
|
We can set the now() function as a default value with the help of dynamic default. First, we will create a table with data type” datetime”. After that, we will set now() as the default value for column “MyTime” as shown below.
Creating a table.
mysql> create table DefaultDateTimeDemo
-> (
-> MyTime datetime default CURRENT_TIMESTAMP
-> );
Query OK, 0 rows affected (0.59 sec)
After creating the above table, we won’t insert any value while using the insert command. This is done so that we can get the default date time with the help of dynamic value default.
Here is the query to insert records.
mysql> insert into DefaultDateTimeDemo values();
Query OK, 1 row affected (0.13 sec)
Now, we can check whether the default value now() is added or not. Here is the query to display records.
mysql> select *from DefaultDateTimeDemo;
The following is the output that shows the current date and time.
+---------------------+
| MyTime |
+---------------------+
| 2018-11-09 11:58:47 |
+---------------------+
1 row in set (0.00 sec)
Now, we can verify whether the result is correct or not with the help of now() method. Here is the query to check the result.
mysql> select now();
The following is the output.
+---------------------+
| now() |
+---------------------+
| 2018-11-09 11:58:40 |
+---------------------+
1 row in set (0.00 sec)
Look at the sample output above. Both of them gives the same result.
|
[
{
"code": null,
"e": 1289,
"s": 1062,
"text": "We can set the now() function as a default value with the help of dynamic default. First, we will create a table with data type” datetime”. After that, we will set now() as the default value for column “MyTime” as shown below."
},
{
"code": null,
"e": 1307,
"s": 1289,
"text": "Creating a table."
},
{
"code": null,
"e": 1449,
"s": 1307,
"text": "mysql> create table DefaultDateTimeDemo\n -> (\n -> MyTime datetime default CURRENT_TIMESTAMP\n -> );\nQuery OK, 0 rows affected (0.59 sec)"
},
{
"code": null,
"e": 1633,
"s": 1449,
"text": "After creating the above table, we won’t insert any value while using the insert command. This is done so that we can get the default date time with the help of dynamic value default."
},
{
"code": null,
"e": 1670,
"s": 1633,
"text": "Here is the query to insert records."
},
{
"code": null,
"e": 1755,
"s": 1670,
"text": "mysql> insert into DefaultDateTimeDemo values();\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1860,
"s": 1755,
"text": "Now, we can check whether the default value now() is added or not. Here is the query to display records."
},
{
"code": null,
"e": 1901,
"s": 1860,
"text": "mysql> select *from DefaultDateTimeDemo;"
},
{
"code": null,
"e": 1967,
"s": 1901,
"text": "The following is the output that shows the current date and time."
},
{
"code": null,
"e": 2112,
"s": 1967,
"text": "+---------------------+\n| MyTime |\n+---------------------+\n| 2018-11-09 11:58:47 |\n+---------------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 2238,
"s": 2112,
"text": "Now, we can verify whether the result is correct or not with the help of now() method. Here is the query to check the result."
},
{
"code": null,
"e": 2259,
"s": 2238,
"text": "mysql> select now();"
},
{
"code": null,
"e": 2288,
"s": 2259,
"text": "The following is the output."
},
{
"code": null,
"e": 2433,
"s": 2288,
"text": "+---------------------+\n| now() |\n+---------------------+\n| 2018-11-09 11:58:40 |\n+---------------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 2502,
"s": 2433,
"text": "Look at the sample output above. Both of them gives the same result."
}
] |
Python | Reverse Slicing of given string - GeeksforGeeks
|
04 Jul, 2019
Sometimes, while working with strings we might have a problem in which we need to perform the reverse slicing of string, i.e slicing the string for certain characters from the rear end. Let’s discuss certain ways in which this can be done.
Method #1 : Using join() + reversed()The combination of above function can be used to perform this particular task. In this, we reverse the string in memory and join the sliced no. of characters so as to return the string sliced from rear end.
# Python3 code to demonstrate working of# Reverse Slicing string # Using join() + reversed() # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + test_str) # initializing K K = 7 # Using join() + reversed()# Reverse Slicing string res = ''.join(reversed(test_str[0:K])) # printing result print("The reversed sliced string is : " + res)
The original string is : GeeksforGeeks
The reversed sliced string is : ofskeeG
Method #2 : Using string slicingThe string slicing can be used to perform this particular task, by using “-1” as the third argument in slicing we can make function perform the slicing from rear end hence proving to be a simple solution.
# Python3 code to demonstrate working of# Reverse Slicing string # Using string slicing # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + test_str) # initializing K K = 7 # Using string slicing# Reverse Slicing string res = test_str[(K-1)::-1] # printing result print("The reversed sliced string is : " + res)
The original string is : GeeksforGeeks
The reversed sliced string is : ofskeeG
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 24776,
"s": 24748,
"text": "\n04 Jul, 2019"
},
{
"code": null,
"e": 25016,
"s": 24776,
"text": "Sometimes, while working with strings we might have a problem in which we need to perform the reverse slicing of string, i.e slicing the string for certain characters from the rear end. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 25260,
"s": 25016,
"text": "Method #1 : Using join() + reversed()The combination of above function can be used to perform this particular task. In this, we reverse the string in memory and join the sliced no. of characters so as to return the string sliced from rear end."
},
{
"code": "# Python3 code to demonstrate working of# Reverse Slicing string # Using join() + reversed() # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + test_str) # initializing K K = 7 # Using join() + reversed()# Reverse Slicing string res = ''.join(reversed(test_str[0:K])) # printing result print(\"The reversed sliced string is : \" + res)",
"e": 25660,
"s": 25260,
"text": null
},
{
"code": null,
"e": 25740,
"s": 25660,
"text": "The original string is : GeeksforGeeks\nThe reversed sliced string is : ofskeeG\n"
},
{
"code": null,
"e": 25979,
"s": 25742,
"text": "Method #2 : Using string slicingThe string slicing can be used to perform this particular task, by using “-1” as the third argument in slicing we can make function perform the slicing from rear end hence proving to be a simple solution."
},
{
"code": "# Python3 code to demonstrate working of# Reverse Slicing string # Using string slicing # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + test_str) # initializing K K = 7 # Using string slicing# Reverse Slicing string res = test_str[(K-1)::-1] # printing result print(\"The reversed sliced string is : \" + res)",
"e": 26356,
"s": 25979,
"text": null
},
{
"code": null,
"e": 26436,
"s": 26356,
"text": "The original string is : GeeksforGeeks\nThe reversed sliced string is : ofskeeG\n"
},
{
"code": null,
"e": 26459,
"s": 26436,
"text": "Python string-programs"
},
{
"code": null,
"e": 26466,
"s": 26459,
"text": "Python"
},
{
"code": null,
"e": 26482,
"s": 26466,
"text": "Python Programs"
},
{
"code": null,
"e": 26580,
"s": 26482,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26612,
"s": 26580,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26654,
"s": 26612,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26691,
"s": 26654,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26720,
"s": 26691,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26762,
"s": 26720,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26784,
"s": 26762,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26823,
"s": 26784,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26869,
"s": 26823,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26907,
"s": 26869,
"text": "Python | Convert a list to dictionary"
}
] |
Ints indexOf() function | Guava | Java - GeeksforGeeks
|
15 Nov, 2018
Guava’s Ints.indexOf(int[] array, int target) method returns the index of the first appearance of the value target in array.
Syntax:
public static int indexOf(int[] array, int target)
Parameters: This method accepts the following parameters:
array: An array of int values, possibly empty.
target: A primitive int value.
Return Value: This method returns the least index i for which array[i] == target, or -1 if no such index exists.
Example 1:
// Java code to show implementation of// Guava's Ints.indexOf() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating an integer array int[] arr = { 1, 2, 3, 4, 3, 5 }; int target = 3; // Using Ints.indexOf(int[] array, int target) // method to get the index of first appearance // of a given element in array and return -1 // if element is not found in the array int index = Ints.indexOf(arr, target); if (index != -1) { System.out.println("Target is present at index " + index); } else { System.out.println("Target is not present" + " in the array"); } }}
Target is present at index 2
Example 2:
// Java code to show implementation of// Guava's Ints.indexOf() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating an integer array int[] arr = { 3, 5, 7, 11, 13 }; int target = 17; // Using Ints.indexOf(int[] array, int target) method // to get the index of first appearance of a // given element in array and return -1 if // element is not found in the array int index = Ints.indexOf(arr, target); if (index != -1) { System.out.println("Target is present at index " + index); } else { System.out.println("Target is not present" + " in the array"); } }}
Target is not present in the array
Reference: https://google.github.io/guava/releases/22.0/api/docs/com/google/common/primitives/Ints.html#indexOf-int:A-int-
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Overriding in Java
|
[
{
"code": null,
"e": 24418,
"s": 24390,
"text": "\n15 Nov, 2018"
},
{
"code": null,
"e": 24543,
"s": 24418,
"text": "Guava’s Ints.indexOf(int[] array, int target) method returns the index of the first appearance of the value target in array."
},
{
"code": null,
"e": 24551,
"s": 24543,
"text": "Syntax:"
},
{
"code": null,
"e": 24603,
"s": 24551,
"text": "public static int indexOf(int[] array, int target)\n"
},
{
"code": null,
"e": 24661,
"s": 24603,
"text": "Parameters: This method accepts the following parameters:"
},
{
"code": null,
"e": 24708,
"s": 24661,
"text": "array: An array of int values, possibly empty."
},
{
"code": null,
"e": 24739,
"s": 24708,
"text": "target: A primitive int value."
},
{
"code": null,
"e": 24852,
"s": 24739,
"text": "Return Value: This method returns the least index i for which array[i] == target, or -1 if no such index exists."
},
{
"code": null,
"e": 24863,
"s": 24852,
"text": "Example 1:"
},
{
"code": "// Java code to show implementation of// Guava's Ints.indexOf() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating an integer array int[] arr = { 1, 2, 3, 4, 3, 5 }; int target = 3; // Using Ints.indexOf(int[] array, int target) // method to get the index of first appearance // of a given element in array and return -1 // if element is not found in the array int index = Ints.indexOf(arr, target); if (index != -1) { System.out.println(\"Target is present at index \" + index); } else { System.out.println(\"Target is not present\" + \" in the array\"); } }}",
"e": 25712,
"s": 24863,
"text": null
},
{
"code": null,
"e": 25742,
"s": 25712,
"text": "Target is present at index 2\n"
},
{
"code": null,
"e": 25753,
"s": 25742,
"text": "Example 2:"
},
{
"code": "// Java code to show implementation of// Guava's Ints.indexOf() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating an integer array int[] arr = { 3, 5, 7, 11, 13 }; int target = 17; // Using Ints.indexOf(int[] array, int target) method // to get the index of first appearance of a // given element in array and return -1 if // element is not found in the array int index = Ints.indexOf(arr, target); if (index != -1) { System.out.println(\"Target is present at index \" + index); } else { System.out.println(\"Target is not present\" + \" in the array\"); } }}",
"e": 26602,
"s": 25753,
"text": null
},
{
"code": null,
"e": 26638,
"s": 26602,
"text": "Target is not present in the array\n"
},
{
"code": null,
"e": 26761,
"s": 26638,
"text": "Reference: https://google.github.io/guava/releases/22.0/api/docs/com/google/common/primitives/Ints.html#indexOf-int:A-int-"
},
{
"code": null,
"e": 26772,
"s": 26761,
"text": "java-guava"
},
{
"code": null,
"e": 26777,
"s": 26772,
"text": "Java"
},
{
"code": null,
"e": 26782,
"s": 26777,
"text": "Java"
},
{
"code": null,
"e": 26880,
"s": 26782,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26889,
"s": 26880,
"text": "Comments"
},
{
"code": null,
"e": 26902,
"s": 26889,
"text": "Old Comments"
},
{
"code": null,
"e": 26934,
"s": 26902,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26964,
"s": 26934,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26983,
"s": 26964,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27034,
"s": 26983,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27052,
"s": 27034,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27083,
"s": 27052,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27115,
"s": 27083,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27134,
"s": 27115,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 27154,
"s": 27134,
"text": "Stack Class in Java"
}
] |
function command in Linux with examples - GeeksforGeeks
|
04 Aug, 2021
Function is a command in linux which is used to create functions or methods.
1.using function keyword : A function in linux can be declared by using keyword function before the name of the function. Different statements can be separated by a semicolon or a new line. SYNTAX
function name { COMMANDS ; }
2.using parenthesis : A function can also be declared by using parenthesis after the name of the function. Different statements can be separated by a semicolon or a new line. SYNTAX
name () { COMMANDS ; }
3.Parameterised function :
$1 will displays the first argument that will be sent and $2 will display the second ans so on...
4.help function : It displays help information.
nidhi_biet
sagar0719kumar
linux-command
Linux-misc-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
Named Pipe or FIFO with example C program
chown command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
Start/Stop/Restart Services Using Systemctl in Linux
SED command in Linux | Set 2
|
[
{
"code": null,
"e": 24350,
"s": 24322,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 24428,
"s": 24350,
"text": "Function is a command in linux which is used to create functions or methods. "
},
{
"code": null,
"e": 24629,
"s": 24430,
"text": "1.using function keyword : A function in linux can be declared by using keyword function before the name of the function. Different statements can be separated by a semicolon or a new line. SYNTAX "
},
{
"code": null,
"e": 24658,
"s": 24629,
"text": "function name { COMMANDS ; }"
},
{
"code": null,
"e": 24846,
"s": 24662,
"text": "2.using parenthesis : A function can also be declared by using parenthesis after the name of the function. Different statements can be separated by a semicolon or a new line. SYNTAX "
},
{
"code": null,
"e": 24869,
"s": 24846,
"text": "name () { COMMANDS ; }"
},
{
"code": null,
"e": 24902,
"s": 24873,
"text": "3.Parameterised function : "
},
{
"code": null,
"e": 25002,
"s": 24902,
"text": "$1 will displays the first argument that will be sent and $2 will display the second ans so on... "
},
{
"code": null,
"e": 25052,
"s": 25002,
"text": "4.help function : It displays help information. "
},
{
"code": null,
"e": 25067,
"s": 25056,
"text": "nidhi_biet"
},
{
"code": null,
"e": 25082,
"s": 25067,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 25096,
"s": 25082,
"text": "linux-command"
},
{
"code": null,
"e": 25116,
"s": 25096,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 25123,
"s": 25116,
"text": "Picked"
},
{
"code": null,
"e": 25147,
"s": 25123,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 25158,
"s": 25147,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25177,
"s": 25158,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25275,
"s": 25177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25284,
"s": 25275,
"text": "Comments"
},
{
"code": null,
"e": 25297,
"s": 25284,
"text": "Old Comments"
},
{
"code": null,
"e": 25323,
"s": 25297,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25358,
"s": 25323,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 25395,
"s": 25358,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25435,
"s": 25395,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 25477,
"s": 25435,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 25514,
"s": 25477,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 25548,
"s": 25514,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25574,
"s": 25548,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 25627,
"s": 25574,
"text": "Start/Stop/Restart Services Using Systemctl in Linux"
}
] |
7 JavaScript Shorthand Techniques that will Save your Time - GeeksforGeeks
|
12 Jan, 2021
In this article, we will discuss 7 cool shorthand tricks in JavaScript that will save the developer time.
1. Arrow Function: JavaScript Arrow functions were introduced in ES6. The main advantage of this function is, it has shorter syntax.
Javascript
// Longhand function add(a, b) { return a + b; } // Shorthand const add = (a, b) => a + b;
2. Multi-line string: For multi line string we normally use + operator with a new line escape sequence (\n). We can do it in an easier way by using backticks (`).
Javascript
// Longhand console.log('JavaScript is a lightweight, interpreted, ' + 'object-oriented language\nwith first-class ' + 'functions, and is best known as the scripting ' + 'language for Web \npages, but it is used in many' + 'non-browser environments as well.\n'); // Shorthand console.log(`JavaScript is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for Web pages, but it is used in many non-browser environments as well.`);
3. For loop: To loop through an array, we normally use the traditional for loop. We can make use of the for...of loop to iterate through arrays. To access the index of each value we can use for...in loop.
Javascript
let myArr = [50, 60, 70, 80]; // Longhand for (let i = 0; i < myArr.length; i++) { console.log(myArr[i]); } // Shorthand // 1. for of loop for (const val of myArr) { console.log(val); } // 2. for in loop for (const index in myArr) { console.log(`index: ${index} and value: ${myArr[index]}`); }
4. String into a Number: There are built in methods like parseInt and parseFloat available to convert a string into number. It can also be done by simply providing an unary operator (+) in front of string value.
Javascript
// Longhand let a = parseInt('764'); let b = parseFloat('29.3'); // Shorthand let a = +'764'; let b = +'29.3';
5. Swap two variables
For swapping two variables, we often use a third variable. But it can be done easily with array de-structuring assignment.
Javascript
//Longhandlet x = 'Hello', y = 'World'; const temp = x; x = y; y = temp; //Shorthand [x, y] = [y, x];
6. Merging of arrays: To merge two arrays, following can be used:
Javascript
// Longhand let a1 = [2, 3]; let a2 = a1.concat([6, 8]); // Output: [2, 3, 6, 8] // Shorthand let a2 = [...a1, 6, 8]; // Output: [2, 3, 6, 8]
7. Multiple condition checking: For multiple value matching, we can put all values in array and use indexOf() or includes() method.
Javascript
// Longhand if (value === 1 || value === 'hello' || value === 2 || value === 'world') { ...} // Shorthand 1if ([1, 'hello', 2, 'world'].indexOf(value) >= 0) { ... } // Shorthand 2if ([1, 'hello', 2, 'world'].includes(value)) { ... }
JavaScript-Misc
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n12 Jan, 2021"
},
{
"code": null,
"e": 25326,
"s": 25220,
"text": "In this article, we will discuss 7 cool shorthand tricks in JavaScript that will save the developer time."
},
{
"code": null,
"e": 25459,
"s": 25326,
"text": "1. Arrow Function: JavaScript Arrow functions were introduced in ES6. The main advantage of this function is, it has shorter syntax."
},
{
"code": null,
"e": 25470,
"s": 25459,
"text": "Javascript"
},
{
"code": "// Longhand function add(a, b) { return a + b; } // Shorthand const add = (a, b) => a + b;",
"e": 25568,
"s": 25470,
"text": null
},
{
"code": null,
"e": 25731,
"s": 25568,
"text": "2. Multi-line string: For multi line string we normally use + operator with a new line escape sequence (\\n). We can do it in an easier way by using backticks (`)."
},
{
"code": null,
"e": 25742,
"s": 25731,
"text": "Javascript"
},
{
"code": "// Longhand console.log('JavaScript is a lightweight, interpreted, ' + 'object-oriented language\\nwith first-class ' + 'functions, and is best known as the scripting ' + 'language for Web \\npages, but it is used in many' + 'non-browser environments as well.\\n'); // Shorthand console.log(`JavaScript is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for Web pages, but it is used in many non-browser environments as well.`);",
"e": 26261,
"s": 25742,
"text": null
},
{
"code": null,
"e": 26466,
"s": 26261,
"text": "3. For loop: To loop through an array, we normally use the traditional for loop. We can make use of the for...of loop to iterate through arrays. To access the index of each value we can use for...in loop."
},
{
"code": null,
"e": 26477,
"s": 26466,
"text": "Javascript"
},
{
"code": "let myArr = [50, 60, 70, 80]; // Longhand for (let i = 0; i < myArr.length; i++) { console.log(myArr[i]); } // Shorthand // 1. for of loop for (const val of myArr) { console.log(val); } // 2. for in loop for (const index in myArr) { console.log(`index: ${index} and value: ${myArr[index]}`); }",
"e": 26785,
"s": 26477,
"text": null
},
{
"code": null,
"e": 26997,
"s": 26785,
"text": "4. String into a Number: There are built in methods like parseInt and parseFloat available to convert a string into number. It can also be done by simply providing an unary operator (+) in front of string value."
},
{
"code": null,
"e": 27008,
"s": 26997,
"text": "Javascript"
},
{
"code": "// Longhand let a = parseInt('764'); let b = parseFloat('29.3'); // Shorthand let a = +'764'; let b = +'29.3';",
"e": 27123,
"s": 27008,
"text": null
},
{
"code": null,
"e": 27145,
"s": 27123,
"text": "5. Swap two variables"
},
{
"code": null,
"e": 27268,
"s": 27145,
"text": "For swapping two variables, we often use a third variable. But it can be done easily with array de-structuring assignment."
},
{
"code": null,
"e": 27279,
"s": 27268,
"text": "Javascript"
},
{
"code": "//Longhandlet x = 'Hello', y = 'World'; const temp = x; x = y; y = temp; //Shorthand [x, y] = [y, x];",
"e": 27386,
"s": 27279,
"text": null
},
{
"code": null,
"e": 27453,
"s": 27386,
"text": "6. Merging of arrays: To merge two arrays, following can be used:"
},
{
"code": null,
"e": 27464,
"s": 27453,
"text": "Javascript"
},
{
"code": "// Longhand let a1 = [2, 3]; let a2 = a1.concat([6, 8]); // Output: [2, 3, 6, 8] // Shorthand let a2 = [...a1, 6, 8]; // Output: [2, 3, 6, 8]",
"e": 27614,
"s": 27464,
"text": null
},
{
"code": null,
"e": 27746,
"s": 27614,
"text": "7. Multiple condition checking: For multiple value matching, we can put all values in array and use indexOf() or includes() method."
},
{
"code": null,
"e": 27757,
"s": 27746,
"text": "Javascript"
},
{
"code": "// Longhand if (value === 1 || value === 'hello' || value === 2 || value === 'world') { ...} // Shorthand 1if ([1, 'hello', 2, 'world'].indexOf(value) >= 0) { ... } // Shorthand 2if ([1, 'hello', 2, 'world'].includes(value)) { ... }",
"e": 28005,
"s": 27757,
"text": null
},
{
"code": null,
"e": 28021,
"s": 28005,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28045,
"s": 28021,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28056,
"s": 28045,
"text": "JavaScript"
},
{
"code": null,
"e": 28075,
"s": 28056,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28092,
"s": 28075,
"text": "Web Technologies"
},
{
"code": null,
"e": 28119,
"s": 28092,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28217,
"s": 28119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28226,
"s": 28217,
"text": "Comments"
},
{
"code": null,
"e": 28239,
"s": 28226,
"text": "Old Comments"
},
{
"code": null,
"e": 28300,
"s": 28239,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28341,
"s": 28300,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28395,
"s": 28341,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28448,
"s": 28395,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 28510,
"s": 28448,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28552,
"s": 28510,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28585,
"s": 28552,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28647,
"s": 28585,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28690,
"s": 28647,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Friends Pairing Problem | Practice | GeeksforGeeks
|
Given N friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up.
Note: Since answer can be very large, return your answer mod 10^9+7.
Example 1:
Input:N = 3
Output: 4
Explanation:
{1}, {2}, {3} : All single
{1}, {2,3} : 2 and 3 paired but 1 is single.
{1,2}, {3} : 1 and 2 are paired but 3 is single.
{1,3}, {2} : 1 and 3 are paired but 2 is single.
Note that {1,2} and {2,1} are considered same.
Example 2:
Input: N = 2
Output: 2
Explanation:
{1} , {2} : All single.
{1,2} : 1 and 2 are paired.
Your Task:
You don't need to read input or print anything. Your task is to complete the function countFriendsPairings() which accepts an integer n and return number of ways in which friends can remain single or can be paired up.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 104
+1
gardnerchris1 day ago
int M=1e9+7;
if(n==1||n==2) return n;
long long prev=1, curr=2;
for(int i=3; i<=n; i++) {
long long temp=(curr%M+((i-1)*prev)%M)%M;
prev=curr;
curr=temp;
}
return curr;
+1
arthurshelby4 days ago
😉✌️🇮🇳❄️
long long int f(int n,vector<int>&dp)
{
if(n==3)
return 4;
if(n==2)
return 2;
if(n==1)
return 1;
if(dp[n]!=-1)
return dp[n];
return dp[n]=(f(n-1,dp)+(n-1)*f(n-2,dp))%1000000007;
}
int countFriendsPairings(int n)
{
// code here
vector<int>dp(n+1,-1);
return f(n,dp);
}
0
noeldcostaec193 weeks ago
O(1) Auxilary Space
O(N) Time Complexity
class Solution: def countFriendsPairings(self, n): if n<=2: return n p1=2 p2=1 temp=0 for i in range(n-2,0,-1): temp=p1 p1=p2*(n-i)+p1 p2=temp return p1%(1000000007)
+1
kronizerdeltac3 weeks ago
JAVA TABULATION CODE:
int mod = (int) 1e9 + 7;
public long countFriendsPairings_tabu(int N, long[] dp) {
for(int n = 0; n <= N; n++) {
if(n < 0)
return 0;
if(n == 0) {
dp[n] = 1;
continue;
}
int count = 0;
count += dp[n - 1] % mod;
if(n - 2 >= 0)
count += dp[n - 2] * (n - 1) % mod;
dp[n] = count % mod;
}
return dp[N];
}
public long countFriendsPairings(int n) {
long[] dp = new long[n + 1];
Arrays.fill(dp, -1);
return countFriendsPairings_tabu(n, dp) % mod;
}
0
milindprajapatmst193 weeks ago
# define ll long long
const int MOD = 1e9 + 7;
ll _add(ll x, ll y) {
return (x + y) % MOD;
}
ll _mul(ll x, ll y) {
return (x * y) % MOD;
}
class Solution {
public:
int countFriendsPairings(int n) {
ll dp[2] = {1, 1};
for (int x = 1; x <= n; x++) {
ll T = dp[0];
dp[0] = dp[1];
dp[1] = _add(dp[1], _mul(x, T));
}
return dp[0];
}
};
+3
arorapankaj4711 month ago
O(N) time, O(1) space Easiest Understandable solution.
int countFriendsPairings(int n){
int mod=1e9+7;
long long prevResult2 = 1;
long long prevResult1 = 2;
if(n == 0) return 0;
else if(n == 1) return 1;
else if(n == 2) return 2;
for(int i = 3; i<=n; i++){
long long prevResult = prevResult1 + (i-1)*prevResult2;
prevResult %= mod;
prevResult2 = prevResult1;
prevResult1 = prevResult;
}
return prevResult1;
}
-2
arunahircse231 month ago
All testcases passed :
int countFriendsPairings(int n) { // code here long long int dp[10001]; dp[0]=0; dp[1]=1; dp[2]=2; int mod=1e9+7; for(int i=3; i<n+1; i++) { dp[i]=((dp[i-1]%mod) + ( ((dp[i-2])%mod) * ((i-1)%mod) )%mod)%mod; } return dp[n]; }
0
jainmuskan5651 month ago
long long int dp[10001]; long long int mod= 1e9+7; int helper(int n){ if(n<=2){ return n; } if(dp[n]!= -1){ return dp[n]; } long long int a= helper(n-1)%mod; long long int b= ((n-1)%mod)*(helper(n-2)%mod)%mod; return dp[n]=(a+b)%mod; } int countFriendsPairings(int n) { // when nth person is single // recur for f(n-1) // if paired then n-1 * f(n-2) memset(dp,-1,sizeof(dp)); return helper(n)%mod; }
+19
bharatgupta688231 month ago
Tagging this problem easy is a criminal offence
+3
aloksinghbais022 months ago
C++ solution using memoization (top down dp) having time complexity as O(N) and space complexity as O(N) is as follows :-
Execution Time :- 0.0 / 1.1 sec
int mod = (int)1e9 + 7; long long int dp[10001]; long long int helper(int n){ if(n == 1) return (1); if(n == 2) return (2); if(dp[n] != -1) return (dp[n]); return dp[n] = (helper(n-1) + (n-1)*helper(n-2)) % mod; } int countFriendsPairings(int n){ memset(dp,-1,sizeof(dp)); return (int)helper(n); }
C++ solution using bottom up dp having time complexity as O(N) and space complexity as O(N) is as follows :-
Execution Time :- 0.0 / 1.1 sec
int countFriendsPairings(int n){ int mod = (int)1e9 + 7; long long int dp[n+1]; dp[1] = 1; dp[2] = 2; for(int i = 3; i <= n; i++){ dp[i] = (dp[i-1] + (i-1)*dp[i-2]) % mod; } return (int)dp[n]; }
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": 522,
"s": 238,
"text": "Given N friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up.\nNote: Since answer can be very large, return your answer mod 10^9+7."
},
{
"code": null,
"e": 534,
"s": 522,
"text": "\nExample 1:"
},
{
"code": null,
"e": 787,
"s": 534,
"text": "Input:N = 3\nOutput: 4\nExplanation:\n{1}, {2}, {3} : All single\n{1}, {2,3} : 2 and 3 paired but 1 is single.\n{1,2}, {3} : 1 and 2 are paired but 3 is single.\n{1,3}, {2} : 1 and 3 are paired but 2 is single.\nNote that {1,2} and {2,1} are considered same.\n"
},
{
"code": null,
"e": 799,
"s": 787,
"text": "Example 2: "
},
{
"code": null,
"e": 888,
"s": 799,
"text": "Input: N = 2\nOutput: 2\nExplanation:\n{1} , {2} : All single.\n{1,2} : 1 and 2 are paired.\n"
},
{
"code": null,
"e": 1118,
"s": 888,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countFriendsPairings() which accepts an integer n and return number of ways in which friends can remain single or can be paired up."
},
{
"code": null,
"e": 1181,
"s": 1118,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1207,
"s": 1181,
"text": "\nConstraints:\n1 ≤ N ≤ 104"
},
{
"code": null,
"e": 1210,
"s": 1207,
"text": "+1"
},
{
"code": null,
"e": 1232,
"s": 1210,
"text": "gardnerchris1 day ago"
},
{
"code": null,
"e": 1479,
"s": 1232,
"text": "\t\tint M=1e9+7;\n if(n==1||n==2) return n;\n long long prev=1, curr=2;\n for(int i=3; i<=n; i++) {\n long long temp=(curr%M+((i-1)*prev)%M)%M;\n prev=curr;\n curr=temp;\n }\n return curr;"
},
{
"code": null,
"e": 1482,
"s": 1479,
"text": "+1"
},
{
"code": null,
"e": 1505,
"s": 1482,
"text": "arthurshelby4 days ago"
},
{
"code": null,
"e": 1899,
"s": 1505,
"text": "😉✌️🇮🇳❄️\nlong long int f(int n,vector<int>&dp)\n {\n if(n==3)\n return 4;\n if(n==2)\n return 2;\n if(n==1)\n return 1;\n if(dp[n]!=-1)\n return dp[n];\n return dp[n]=(f(n-1,dp)+(n-1)*f(n-2,dp))%1000000007;\n }\n int countFriendsPairings(int n) \n { \n // code here\n vector<int>dp(n+1,-1);\n return f(n,dp);\n }"
},
{
"code": null,
"e": 1901,
"s": 1899,
"text": "0"
},
{
"code": null,
"e": 1927,
"s": 1901,
"text": "noeldcostaec193 weeks ago"
},
{
"code": null,
"e": 1947,
"s": 1927,
"text": "O(1) Auxilary Space"
},
{
"code": null,
"e": 1968,
"s": 1947,
"text": "O(N) Time Complexity"
},
{
"code": null,
"e": 2214,
"s": 1970,
"text": "class Solution: def countFriendsPairings(self, n): if n<=2: return n p1=2 p2=1 temp=0 for i in range(n-2,0,-1): temp=p1 p1=p2*(n-i)+p1 p2=temp return p1%(1000000007)"
},
{
"code": null,
"e": 2217,
"s": 2214,
"text": "+1"
},
{
"code": null,
"e": 2243,
"s": 2217,
"text": "kronizerdeltac3 weeks ago"
},
{
"code": null,
"e": 2265,
"s": 2243,
"text": "JAVA TABULATION CODE:"
},
{
"code": null,
"e": 2944,
"s": 2267,
"text": "int mod = (int) 1e9 + 7;\n public long countFriendsPairings_tabu(int N, long[] dp) {\n for(int n = 0; n <= N; n++) {\n if(n < 0)\n return 0;\n \n if(n == 0) {\n dp[n] = 1;\n continue;\n }\n \n int count = 0;\n count += dp[n - 1] % mod;\n if(n - 2 >= 0)\n count += dp[n - 2] * (n - 1) % mod;\n dp[n] = count % mod;\n }\n return dp[N];\n }\n \n public long countFriendsPairings(int n) {\n long[] dp = new long[n + 1];\n Arrays.fill(dp, -1);\n\n return countFriendsPairings_tabu(n, dp) % mod;\n }"
},
{
"code": null,
"e": 2946,
"s": 2944,
"text": "0"
},
{
"code": null,
"e": 2977,
"s": 2946,
"text": "milindprajapatmst193 weeks ago"
},
{
"code": null,
"e": 3396,
"s": 2977,
"text": "# define ll long long\nconst int MOD = 1e9 + 7;\nll _add(ll x, ll y) {\n return (x + y) % MOD;\n}\nll _mul(ll x, ll y) {\n return (x * y) % MOD;\n}\nclass Solution {\npublic:\n int countFriendsPairings(int n) { \n ll dp[2] = {1, 1};\n for (int x = 1; x <= n; x++) {\n ll T = dp[0];\n dp[0] = dp[1];\n dp[1] = _add(dp[1], _mul(x, T));\n }\n return dp[0];\n }\n}; "
},
{
"code": null,
"e": 3399,
"s": 3396,
"text": "+3"
},
{
"code": null,
"e": 3425,
"s": 3399,
"text": "arorapankaj4711 month ago"
},
{
"code": null,
"e": 3481,
"s": 3425,
"text": "O(N) time, O(1) space Easiest Understandable solution."
},
{
"code": null,
"e": 3960,
"s": 3481,
"text": "int countFriendsPairings(int n){ \n int mod=1e9+7;\n long long prevResult2 = 1;\n long long prevResult1 = 2;\n if(n == 0) return 0;\n else if(n == 1) return 1;\n else if(n == 2) return 2;\n for(int i = 3; i<=n; i++){\n long long prevResult = prevResult1 + (i-1)*prevResult2;\n prevResult %= mod;\n prevResult2 = prevResult1;\n prevResult1 = prevResult;\n }\n return prevResult1;\n }"
},
{
"code": null,
"e": 3963,
"s": 3960,
"text": "-2"
},
{
"code": null,
"e": 3988,
"s": 3963,
"text": "arunahircse231 month ago"
},
{
"code": null,
"e": 4012,
"s": 3988,
"text": "All testcases passed : "
},
{
"code": null,
"e": 4322,
"s": 4012,
"text": " int countFriendsPairings(int n) { // code here long long int dp[10001]; dp[0]=0; dp[1]=1; dp[2]=2; int mod=1e9+7; for(int i=3; i<n+1; i++) { dp[i]=((dp[i-1]%mod) + ( ((dp[i-2])%mod) * ((i-1)%mod) )%mod)%mod; } return dp[n]; }"
},
{
"code": null,
"e": 4324,
"s": 4322,
"text": "0"
},
{
"code": null,
"e": 4349,
"s": 4324,
"text": "jainmuskan5651 month ago"
},
{
"code": null,
"e": 4857,
"s": 4349,
"text": " long long int dp[10001]; long long int mod= 1e9+7; int helper(int n){ if(n<=2){ return n; } if(dp[n]!= -1){ return dp[n]; } long long int a= helper(n-1)%mod; long long int b= ((n-1)%mod)*(helper(n-2)%mod)%mod; return dp[n]=(a+b)%mod; } int countFriendsPairings(int n) { // when nth person is single // recur for f(n-1) // if paired then n-1 * f(n-2) memset(dp,-1,sizeof(dp)); return helper(n)%mod; }"
},
{
"code": null,
"e": 4861,
"s": 4857,
"text": "+19"
},
{
"code": null,
"e": 4889,
"s": 4861,
"text": "bharatgupta688231 month ago"
},
{
"code": null,
"e": 4938,
"s": 4889,
"text": "Tagging this problem easy is a criminal offence "
},
{
"code": null,
"e": 4943,
"s": 4940,
"text": "+3"
},
{
"code": null,
"e": 4971,
"s": 4943,
"text": "aloksinghbais022 months ago"
},
{
"code": null,
"e": 5094,
"s": 4971,
"text": "C++ solution using memoization (top down dp) having time complexity as O(N) and space complexity as O(N) is as follows :- "
},
{
"code": null,
"e": 5128,
"s": 5096,
"text": "Execution Time :- 0.0 / 1.1 sec"
},
{
"code": null,
"e": 5494,
"s": 5130,
"text": "int mod = (int)1e9 + 7; long long int dp[10001]; long long int helper(int n){ if(n == 1) return (1); if(n == 2) return (2); if(dp[n] != -1) return (dp[n]); return dp[n] = (helper(n-1) + (n-1)*helper(n-2)) % mod; } int countFriendsPairings(int n){ memset(dp,-1,sizeof(dp)); return (int)helper(n); }"
},
{
"code": null,
"e": 5606,
"s": 5496,
"text": "C++ solution using bottom up dp having time complexity as O(N) and space complexity as O(N) is as follows :- "
},
{
"code": null,
"e": 5640,
"s": 5608,
"text": "Execution Time :- 0.0 / 1.1 sec"
},
{
"code": null,
"e": 5905,
"s": 5642,
"text": "int countFriendsPairings(int n){ int mod = (int)1e9 + 7; long long int dp[n+1]; dp[1] = 1; dp[2] = 2; for(int i = 3; i <= n; i++){ dp[i] = (dp[i-1] + (i-1)*dp[i-2]) % mod; } return (int)dp[n]; }"
},
{
"code": null,
"e": 6051,
"s": 5905,
"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": 6087,
"s": 6051,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6097,
"s": 6087,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6107,
"s": 6097,
"text": "\nContest\n"
},
{
"code": null,
"e": 6170,
"s": 6107,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6318,
"s": 6170,
"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": 6526,
"s": 6318,
"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": 6632,
"s": 6526,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Train neural networks using AMD GPU and Keras | by Mattia Varile | Towards Data Science
|
AMD is developing a new HPC platform, called ROCm. Its ambition is to create a common, open-source environment, capable to interface both with Nvidia (using CUDA) and AMD GPUs (further information).
This tutorial will explain how to set-up a neural network environment, using AMD GPUs in a single or multiple configurations.
On the software side: we will be able to run Tensorflow v1.12.0 as a backend to Keras on top of the ROCm kernel, using Docker.
To install and deploy ROCm are required particular hardware/software configurations.
The official documentation (ROCm v2.1) suggests the following hardware solutions.
Current CPUs which support PCIe Gen3 + PCIe Atomics are:
AMD Ryzen CPUs;
The CPUs in AMD Ryzen APUs;
AMD Ryzen Threadripper CPUs
AMD EPYC CPUs;
Intel Xeon E7 v3 or newer CPUs;
Intel Xeon E5 v3 or newer CPUs;
Intel Xeon E3 v3 or newer CPUs;
Intel Core i7 v4 (i7–4xxx), Core i5 v4 (i5–4xxx), Core i3 v4 (i3–4xxx) or newer CPUs (i.e. Haswell family or newer).
Some Ivy Bridge-E systems
ROCm officially supports AMD GPUs that use the following chips:
GFX8 GPUs
“Fiji” chips, such as on the AMD Radeon R9 Fury X and Radeon Instinct MI8
“Polaris 10” chips, such as on the AMD Radeon RX 480/580 and Radeon Instinct MI6
“Polaris 11” chips, such as on the AMD Radeon RX 470/570 and Radeon Pro WX 4100
“Polaris 12” chips, such as on the AMD Radeon RX 550 and Radeon RX 540
GFX9 GPUs
“Vega 10” chips, such as on the AMD Radeon RX Vega 64 and Radeon Instinct MI25
“Vega 7nm” chips (Radeon Instinct MI50, Radeon VII)
On the software side, the current version of ROCm (v2.1), is supported only in Linux-based systems.
The ROCm 2.1.x platform supports the following operating systems:
Ubuntu 16.04.x and 18.04.x (Version 16.04.3 and newer or kernels 4.13 and newer)
CentOS 7.4, 7.5, and 7.6 (Using devtoolset-7 runtime support)
RHEL 7.4, 7.5, and 7.6 (Using devtoolset-7 runtime support)
The following hardware/software configuration has been used, by the author, to test and validate the environment:
CPU: Intel Xeon E5–2630L
RAM: 2 x 8 GB
Motherboard: MSI X99A Krait Edition
GPU: 2 x RX480 8GB + 1 x RX580 4GB
SSD: Samsung 850 Evo (256 GB)
HDD: WDC 1TB
OS: Ubuntu 18.04 LTS
In order to get everything working properly, is recommended to start the installation process, within a fresh installed operating system. The following steps are referring to Ubuntu 18.04 LTS operating system, for other OS please refer to the official documentation.
The first step is to install ROCm kernel and dependencies:
Open a new terminal CTRL + ALT + T
sudo apt updatesudo apt dist-upgradesudo apt install libnuma-devsudo reboot
To download and install ROCm stack is required to add related repositories:
wget -qO - http://repo.radeon.com/rocm/apt/debian/rocm.gpg.key | sudo apt-key add -echo 'deb [arch=amd64] http://repo.radeon.com/rocm/apt/debian/ xenial main' | sudo tee /etc/apt/sources.list.d/rocm.list
Is now required to update apt repository list and install rocm-dkms meta-package:
sudo apt updatesudo apt install rocm-dkms
The official documentation suggests creating a new video group in order to have access to GPU resources, using the current user.
Firstly, check the groups in your system, issuing:
groups
Then add yourself to the video group:
sudo usermod -a -G video $LOGNAME
You may want to ensure that any future users you add to your system are put into the “video” group by default. To do that, you can run the following commands:
echo 'ADD_EXTRA_GROUPS=1' | sudo tee -a /etc/adduser.confecho 'EXTRA_GROUPS=video' | sudo tee -a /etc/adduser.conf
Then reboot the system:
reboot
Is now suggested to test the ROCm installation issuing the following commands.
Open a new terminal CTRL + ALT + T , issue the following commands:
/opt/rocm/bin/rocminfo
the output should look as follows: link
Then double-check issuing:
/opt/rocm/opencl/bin/x86_64/clinfo
The output should look like that: link
Official documentation finally suggests to add ROCm binaries to PATH:
echo 'export PATH=$PATH:/opt/rocm/bin:/opt/rocm/profiler/bin:/opt/rocm/opencl/bin/x86_64' | sudo tee -a /etc/profile.d/rocm.sh
Congratulations! ROCm is properly installed in your system and the command:
rocm-smi
should display your hardware information and stats:
Tip: Take a look to rocm-smi -h command, to explore more functionalities and OC tools
The fastest and more reliable method to get ROCm + Tensorflow backend to work is to use the docker image provided by AMD developers.
First, is required to install Docker. In order to do that, please follow the instructions for Ubuntu systems:
docs.docker.com
Tip: To avoid inserting sudo docker <command> instead of docker <command> it’s useful to provide access to non-root users: Manage Docker as a non-root user.
It’s now time to pull the Tensorflow docker provided by AMD developers.
Open a new terminal CTRL + ALT + T and issue:
docker pull rocm/tensorflow
after a few minutes, the image will be installed in your system, ready to go.
Because of the ephemeral nature of Docker containers, once a docker session is closed all the modifications and files stored, will be deleted with the container.
For this reason is useful to create a persistent space in the physical drive for storing files and Jupyter notebooks. The simpler method is to create a folder to initialize with a docker container. To do that issue the command:
mkdir /home/$LOGNAME/tf_docker_share
This command will create a folder named tf_docker_share useful for storing and reviewing data created within the docker.
Now, execute the image in a new container session. Simply send the following command:
docker run -i -t \--network=host \--device=/dev/kfd \--device=/dev/dri \--group-add video \--cap-add=SYS_PTRACE \--security-opt seccomp=unconfined \--workdir=/tf_docker_share \-v $HOME/tf_docker_share:/tf_docker_share rocm/tensorflow:latest /bin/bash
The docker is in execution on the directory /tf_docker_share and you should see something similar to:
it means that you are now operating inside the Tensorflow-ROCm virtual system.
Jupyter is a very useful tool, for the development, debug and test of neural networks. Unfortunately, it’s not currently installed, as default, on the Tensorflow-ROCm, Docker image, published by ROCm team. It’s therefore required to manually install Jupyter.
In order to do that, within Tensorflow-ROCm virtual system prompt,
1. Issue the following command:
pip3 install jupyter
It will install the Jupyter package into the virtual system. Leave open this terminal.
2. Open a new terminal CTRL + ALT + T .
Find the CONTAINER ID issuing the command:
docker ps
A table, similar to the following should appear:
The first column represents the Container ID of the executed container. Copy that because it’s necessary for the next step.
3. It’s time to commit, to permanently write modifications of the image. From the same terminal, execute:
docker commit <container-id> rocm/tensorflow:<tag>
where tag value is an arbitrary name for example personal .
4. To double check that the image has been generated correctly, from the same terminal, issue the command:
docker images
that should result generate a table similar to the following:
It’s important to note that we will refer to this newly generated image for the rest of the tutorial.
The new docker run command, to use, will look like:
docker run -i -t \--network=host \--device=/dev/kfd \--device=/dev/dri \--group-add video \--cap-add=SYS_PTRACE \--security-opt seccomp=unconfined \--workdir=/tf_docker_share \-v $HOME/tf_docker_share:/tf_docker_share rocm/tensorflow:<tag> /bin/bash
where once again, tag value is arbitrary, for example personal .
We can finally enter the Jupyter environment. Inside it, we will create the first neural network using Tensorflow v1.12 as backend and Keras as frontend.
Firstly close all the previously executing Docker containers.
Check the already open containers:
Check the already open containers:
docker ps
2. Close all the Docker container/containers:
docker container stop <container-id1> <container-id2> ... <container-idn>
3. Close all the already open terminals.
Let’s open a new terminal CTRL + ALT + T :
Run a new Docker container (personal tag will be used as default):
Run a new Docker container (personal tag will be used as default):
docker run -i -t \--network=host \--device=/dev/kfd \--device=/dev/dri \--group-add video \--cap-add=SYS_PTRACE \--security-opt seccomp=unconfined \--workdir=/tf_docker_share \-v $HOME/tf_docker_share:/tf_docker_share rocm/tensorflow:personal /bin/bash
You should be logged into Tensorflow-ROCm docker container prompt.
2. Execute the Jupyter notebook:
jupyter notebook --allow-root --port=8889
a new browser window should appear, similar to the following:
If the new tab does not appear automatically, on the browser, go back to the terminal where jupyter notebook command has been executed. On the bottom, there is a link to follow (press: CTRL + left mouse button on it) then, a new tab in your browser redirects you to Jupyter root directory.
In the last section, of this tutorial, we will train a simple neural network on the MNIST dataset. We will firstly build a fully connected neural network.
Let’s create a new notebook, by selecting Python3 from the upper-right menu in Jupyter root directory.
A new Jupiter notebook should pop-up in a new browser tab. Rename it tofc_network by clicking Untitled on the upper left corner of the window.
Let’s check Tensorflow backend. On the first cell insert:
import tensorflow as tf; print(tf.__version__)
then press SHIFT + ENTER to execute. The output should look like:
We are using Tensorflow v1.12.0.
Let’s import some useful functions, to use next:
from tensorflow.keras.datasets import mnistfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Dropoutfrom tensorflow.keras.optimizers import RMSpropfrom tensorflow.keras.utils import to_categorical
Let’s set batch size, epochs and number of classes.
batch_size = 128num_classes = 10epochs = 10
We will now download and preprocess inputs, loading them into system memory.
# the data, split between train and test sets(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train.reshape(60000, 784)x_test = x_test.reshape(10000, 784)x_train = x_train.astype('float32')x_test = x_test.astype('float32')x_train /= 255x_test /= 255print(x_train.shape[0], 'train samples')print(x_test.shape[0], 'test samples')# convert class vectors to binary class matricesy_train = to_categorical(y_train, num_classes)y_test = to_categorical(y_test, num_classes)
It’s time to define the neural network architecture:
model = Sequential()model.add(Dense(512, activation='relu', input_shape=(784,)))model.add(Dropout(0.2))model.add(Dense(512, activation='relu'))model.add(Dropout(0.2))model.add(Dense(num_classes, activation='softmax'))
We will use a very simple, two-layer fully-connected network, with 512 neurons per layer. It’s also included a 20% drop probability on the neuron connections, in order to prevent overfitting.
Let’s print some insight into the network architecture:
model.summary()
Despite the simplicity of the problem, we have a considerable number of parameters to train (almost ~700.000), it means also considerable computational power consumption. Convolutional Neural Networks will solve the issue reducing computational complexity.
Now, compile the model:
model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])
and start training:
history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))
The neural network has been trained on a single RX 480 with a respectable 47us/step. For comparison, an Nvidia Tesla K80 is reaching 43us/step but is 10x more expensive.
As an additional step, if your system has multiple GPUs, is possible to leverage Keras capabilities, in order to reduce training time, splitting the batch among different GPUs.
To do that, first it’s required to specify the number of GPUs to use for training by, declaring an environmental variable (put the following command on a single cell and execute):
!export HIP_VISIBLE_DEVICES=0,1,...
Numbers from 0 to ... are defining which GPU to use for training. In case you want to disable GPU acceleration simply:
!export HIP_VISIBLE_DEVICES=-1
It’s also necessary to add multi_gpu_model function.
As an example, if you have 3 GPUs, the previous code will modify accordingly.
That concludes this tutorial. The next step will be to test a Convolutional Neural Network on the MNIST dataset. Comparing performances in both single and multi-GPU.
What’s relevant here, is that AMD GPUs perform quite well under computational load at a fraction of the price. GPU market is changing rapidly and ROCm gave to researchers, engineers, and startups, very powerful, open-source tools to adopt, lowering upfront costs in hardware equipment.
Article by Mattia Varile
Please feel free to comment on this article in order to improve his quality and effectiveness.
|
[
{
"code": null,
"e": 371,
"s": 172,
"text": "AMD is developing a new HPC platform, called ROCm. Its ambition is to create a common, open-source environment, capable to interface both with Nvidia (using CUDA) and AMD GPUs (further information)."
},
{
"code": null,
"e": 497,
"s": 371,
"text": "This tutorial will explain how to set-up a neural network environment, using AMD GPUs in a single or multiple configurations."
},
{
"code": null,
"e": 624,
"s": 497,
"text": "On the software side: we will be able to run Tensorflow v1.12.0 as a backend to Keras on top of the ROCm kernel, using Docker."
},
{
"code": null,
"e": 709,
"s": 624,
"text": "To install and deploy ROCm are required particular hardware/software configurations."
},
{
"code": null,
"e": 791,
"s": 709,
"text": "The official documentation (ROCm v2.1) suggests the following hardware solutions."
},
{
"code": null,
"e": 848,
"s": 791,
"text": "Current CPUs which support PCIe Gen3 + PCIe Atomics are:"
},
{
"code": null,
"e": 864,
"s": 848,
"text": "AMD Ryzen CPUs;"
},
{
"code": null,
"e": 892,
"s": 864,
"text": "The CPUs in AMD Ryzen APUs;"
},
{
"code": null,
"e": 920,
"s": 892,
"text": "AMD Ryzen Threadripper CPUs"
},
{
"code": null,
"e": 935,
"s": 920,
"text": "AMD EPYC CPUs;"
},
{
"code": null,
"e": 967,
"s": 935,
"text": "Intel Xeon E7 v3 or newer CPUs;"
},
{
"code": null,
"e": 999,
"s": 967,
"text": "Intel Xeon E5 v3 or newer CPUs;"
},
{
"code": null,
"e": 1031,
"s": 999,
"text": "Intel Xeon E3 v3 or newer CPUs;"
},
{
"code": null,
"e": 1148,
"s": 1031,
"text": "Intel Core i7 v4 (i7–4xxx), Core i5 v4 (i5–4xxx), Core i3 v4 (i3–4xxx) or newer CPUs (i.e. Haswell family or newer)."
},
{
"code": null,
"e": 1174,
"s": 1148,
"text": "Some Ivy Bridge-E systems"
},
{
"code": null,
"e": 1238,
"s": 1174,
"text": "ROCm officially supports AMD GPUs that use the following chips:"
},
{
"code": null,
"e": 1248,
"s": 1238,
"text": "GFX8 GPUs"
},
{
"code": null,
"e": 1322,
"s": 1248,
"text": "“Fiji” chips, such as on the AMD Radeon R9 Fury X and Radeon Instinct MI8"
},
{
"code": null,
"e": 1403,
"s": 1322,
"text": "“Polaris 10” chips, such as on the AMD Radeon RX 480/580 and Radeon Instinct MI6"
},
{
"code": null,
"e": 1483,
"s": 1403,
"text": "“Polaris 11” chips, such as on the AMD Radeon RX 470/570 and Radeon Pro WX 4100"
},
{
"code": null,
"e": 1554,
"s": 1483,
"text": "“Polaris 12” chips, such as on the AMD Radeon RX 550 and Radeon RX 540"
},
{
"code": null,
"e": 1564,
"s": 1554,
"text": "GFX9 GPUs"
},
{
"code": null,
"e": 1643,
"s": 1564,
"text": "“Vega 10” chips, such as on the AMD Radeon RX Vega 64 and Radeon Instinct MI25"
},
{
"code": null,
"e": 1695,
"s": 1643,
"text": "“Vega 7nm” chips (Radeon Instinct MI50, Radeon VII)"
},
{
"code": null,
"e": 1795,
"s": 1695,
"text": "On the software side, the current version of ROCm (v2.1), is supported only in Linux-based systems."
},
{
"code": null,
"e": 1861,
"s": 1795,
"text": "The ROCm 2.1.x platform supports the following operating systems:"
},
{
"code": null,
"e": 1942,
"s": 1861,
"text": "Ubuntu 16.04.x and 18.04.x (Version 16.04.3 and newer or kernels 4.13 and newer)"
},
{
"code": null,
"e": 2004,
"s": 1942,
"text": "CentOS 7.4, 7.5, and 7.6 (Using devtoolset-7 runtime support)"
},
{
"code": null,
"e": 2064,
"s": 2004,
"text": "RHEL 7.4, 7.5, and 7.6 (Using devtoolset-7 runtime support)"
},
{
"code": null,
"e": 2178,
"s": 2064,
"text": "The following hardware/software configuration has been used, by the author, to test and validate the environment:"
},
{
"code": null,
"e": 2203,
"s": 2178,
"text": "CPU: Intel Xeon E5–2630L"
},
{
"code": null,
"e": 2217,
"s": 2203,
"text": "RAM: 2 x 8 GB"
},
{
"code": null,
"e": 2253,
"s": 2217,
"text": "Motherboard: MSI X99A Krait Edition"
},
{
"code": null,
"e": 2288,
"s": 2253,
"text": "GPU: 2 x RX480 8GB + 1 x RX580 4GB"
},
{
"code": null,
"e": 2318,
"s": 2288,
"text": "SSD: Samsung 850 Evo (256 GB)"
},
{
"code": null,
"e": 2331,
"s": 2318,
"text": "HDD: WDC 1TB"
},
{
"code": null,
"e": 2352,
"s": 2331,
"text": "OS: Ubuntu 18.04 LTS"
},
{
"code": null,
"e": 2619,
"s": 2352,
"text": "In order to get everything working properly, is recommended to start the installation process, within a fresh installed operating system. The following steps are referring to Ubuntu 18.04 LTS operating system, for other OS please refer to the official documentation."
},
{
"code": null,
"e": 2678,
"s": 2619,
"text": "The first step is to install ROCm kernel and dependencies:"
},
{
"code": null,
"e": 2713,
"s": 2678,
"text": "Open a new terminal CTRL + ALT + T"
},
{
"code": null,
"e": 2789,
"s": 2713,
"text": "sudo apt updatesudo apt dist-upgradesudo apt install libnuma-devsudo reboot"
},
{
"code": null,
"e": 2865,
"s": 2789,
"text": "To download and install ROCm stack is required to add related repositories:"
},
{
"code": null,
"e": 3069,
"s": 2865,
"text": "wget -qO - http://repo.radeon.com/rocm/apt/debian/rocm.gpg.key | sudo apt-key add -echo 'deb [arch=amd64] http://repo.radeon.com/rocm/apt/debian/ xenial main' | sudo tee /etc/apt/sources.list.d/rocm.list"
},
{
"code": null,
"e": 3151,
"s": 3069,
"text": "Is now required to update apt repository list and install rocm-dkms meta-package:"
},
{
"code": null,
"e": 3193,
"s": 3151,
"text": "sudo apt updatesudo apt install rocm-dkms"
},
{
"code": null,
"e": 3322,
"s": 3193,
"text": "The official documentation suggests creating a new video group in order to have access to GPU resources, using the current user."
},
{
"code": null,
"e": 3373,
"s": 3322,
"text": "Firstly, check the groups in your system, issuing:"
},
{
"code": null,
"e": 3380,
"s": 3373,
"text": "groups"
},
{
"code": null,
"e": 3418,
"s": 3380,
"text": "Then add yourself to the video group:"
},
{
"code": null,
"e": 3452,
"s": 3418,
"text": "sudo usermod -a -G video $LOGNAME"
},
{
"code": null,
"e": 3611,
"s": 3452,
"text": "You may want to ensure that any future users you add to your system are put into the “video” group by default. To do that, you can run the following commands:"
},
{
"code": null,
"e": 3726,
"s": 3611,
"text": "echo 'ADD_EXTRA_GROUPS=1' | sudo tee -a /etc/adduser.confecho 'EXTRA_GROUPS=video' | sudo tee -a /etc/adduser.conf"
},
{
"code": null,
"e": 3750,
"s": 3726,
"text": "Then reboot the system:"
},
{
"code": null,
"e": 3757,
"s": 3750,
"text": "reboot"
},
{
"code": null,
"e": 3836,
"s": 3757,
"text": "Is now suggested to test the ROCm installation issuing the following commands."
},
{
"code": null,
"e": 3903,
"s": 3836,
"text": "Open a new terminal CTRL + ALT + T , issue the following commands:"
},
{
"code": null,
"e": 3926,
"s": 3903,
"text": "/opt/rocm/bin/rocminfo"
},
{
"code": null,
"e": 3966,
"s": 3926,
"text": "the output should look as follows: link"
},
{
"code": null,
"e": 3993,
"s": 3966,
"text": "Then double-check issuing:"
},
{
"code": null,
"e": 4028,
"s": 3993,
"text": "/opt/rocm/opencl/bin/x86_64/clinfo"
},
{
"code": null,
"e": 4067,
"s": 4028,
"text": "The output should look like that: link"
},
{
"code": null,
"e": 4137,
"s": 4067,
"text": "Official documentation finally suggests to add ROCm binaries to PATH:"
},
{
"code": null,
"e": 4264,
"s": 4137,
"text": "echo 'export PATH=$PATH:/opt/rocm/bin:/opt/rocm/profiler/bin:/opt/rocm/opencl/bin/x86_64' | sudo tee -a /etc/profile.d/rocm.sh"
},
{
"code": null,
"e": 4340,
"s": 4264,
"text": "Congratulations! ROCm is properly installed in your system and the command:"
},
{
"code": null,
"e": 4349,
"s": 4340,
"text": "rocm-smi"
},
{
"code": null,
"e": 4401,
"s": 4349,
"text": "should display your hardware information and stats:"
},
{
"code": null,
"e": 4487,
"s": 4401,
"text": "Tip: Take a look to rocm-smi -h command, to explore more functionalities and OC tools"
},
{
"code": null,
"e": 4620,
"s": 4487,
"text": "The fastest and more reliable method to get ROCm + Tensorflow backend to work is to use the docker image provided by AMD developers."
},
{
"code": null,
"e": 4730,
"s": 4620,
"text": "First, is required to install Docker. In order to do that, please follow the instructions for Ubuntu systems:"
},
{
"code": null,
"e": 4746,
"s": 4730,
"text": "docs.docker.com"
},
{
"code": null,
"e": 4903,
"s": 4746,
"text": "Tip: To avoid inserting sudo docker <command> instead of docker <command> it’s useful to provide access to non-root users: Manage Docker as a non-root user."
},
{
"code": null,
"e": 4975,
"s": 4903,
"text": "It’s now time to pull the Tensorflow docker provided by AMD developers."
},
{
"code": null,
"e": 5021,
"s": 4975,
"text": "Open a new terminal CTRL + ALT + T and issue:"
},
{
"code": null,
"e": 5049,
"s": 5021,
"text": "docker pull rocm/tensorflow"
},
{
"code": null,
"e": 5127,
"s": 5049,
"text": "after a few minutes, the image will be installed in your system, ready to go."
},
{
"code": null,
"e": 5289,
"s": 5127,
"text": "Because of the ephemeral nature of Docker containers, once a docker session is closed all the modifications and files stored, will be deleted with the container."
},
{
"code": null,
"e": 5517,
"s": 5289,
"text": "For this reason is useful to create a persistent space in the physical drive for storing files and Jupyter notebooks. The simpler method is to create a folder to initialize with a docker container. To do that issue the command:"
},
{
"code": null,
"e": 5554,
"s": 5517,
"text": "mkdir /home/$LOGNAME/tf_docker_share"
},
{
"code": null,
"e": 5675,
"s": 5554,
"text": "This command will create a folder named tf_docker_share useful for storing and reviewing data created within the docker."
},
{
"code": null,
"e": 5761,
"s": 5675,
"text": "Now, execute the image in a new container session. Simply send the following command:"
},
{
"code": null,
"e": 6012,
"s": 5761,
"text": "docker run -i -t \\--network=host \\--device=/dev/kfd \\--device=/dev/dri \\--group-add video \\--cap-add=SYS_PTRACE \\--security-opt seccomp=unconfined \\--workdir=/tf_docker_share \\-v $HOME/tf_docker_share:/tf_docker_share rocm/tensorflow:latest /bin/bash"
},
{
"code": null,
"e": 6114,
"s": 6012,
"text": "The docker is in execution on the directory /tf_docker_share and you should see something similar to:"
},
{
"code": null,
"e": 6193,
"s": 6114,
"text": "it means that you are now operating inside the Tensorflow-ROCm virtual system."
},
{
"code": null,
"e": 6452,
"s": 6193,
"text": "Jupyter is a very useful tool, for the development, debug and test of neural networks. Unfortunately, it’s not currently installed, as default, on the Tensorflow-ROCm, Docker image, published by ROCm team. It’s therefore required to manually install Jupyter."
},
{
"code": null,
"e": 6519,
"s": 6452,
"text": "In order to do that, within Tensorflow-ROCm virtual system prompt,"
},
{
"code": null,
"e": 6551,
"s": 6519,
"text": "1. Issue the following command:"
},
{
"code": null,
"e": 6572,
"s": 6551,
"text": "pip3 install jupyter"
},
{
"code": null,
"e": 6659,
"s": 6572,
"text": "It will install the Jupyter package into the virtual system. Leave open this terminal."
},
{
"code": null,
"e": 6699,
"s": 6659,
"text": "2. Open a new terminal CTRL + ALT + T ."
},
{
"code": null,
"e": 6742,
"s": 6699,
"text": "Find the CONTAINER ID issuing the command:"
},
{
"code": null,
"e": 6752,
"s": 6742,
"text": "docker ps"
},
{
"code": null,
"e": 6801,
"s": 6752,
"text": "A table, similar to the following should appear:"
},
{
"code": null,
"e": 6925,
"s": 6801,
"text": "The first column represents the Container ID of the executed container. Copy that because it’s necessary for the next step."
},
{
"code": null,
"e": 7031,
"s": 6925,
"text": "3. It’s time to commit, to permanently write modifications of the image. From the same terminal, execute:"
},
{
"code": null,
"e": 7082,
"s": 7031,
"text": "docker commit <container-id> rocm/tensorflow:<tag>"
},
{
"code": null,
"e": 7142,
"s": 7082,
"text": "where tag value is an arbitrary name for example personal ."
},
{
"code": null,
"e": 7249,
"s": 7142,
"text": "4. To double check that the image has been generated correctly, from the same terminal, issue the command:"
},
{
"code": null,
"e": 7263,
"s": 7249,
"text": "docker images"
},
{
"code": null,
"e": 7325,
"s": 7263,
"text": "that should result generate a table similar to the following:"
},
{
"code": null,
"e": 7427,
"s": 7325,
"text": "It’s important to note that we will refer to this newly generated image for the rest of the tutorial."
},
{
"code": null,
"e": 7479,
"s": 7427,
"text": "The new docker run command, to use, will look like:"
},
{
"code": null,
"e": 7729,
"s": 7479,
"text": "docker run -i -t \\--network=host \\--device=/dev/kfd \\--device=/dev/dri \\--group-add video \\--cap-add=SYS_PTRACE \\--security-opt seccomp=unconfined \\--workdir=/tf_docker_share \\-v $HOME/tf_docker_share:/tf_docker_share rocm/tensorflow:<tag> /bin/bash"
},
{
"code": null,
"e": 7794,
"s": 7729,
"text": "where once again, tag value is arbitrary, for example personal ."
},
{
"code": null,
"e": 7948,
"s": 7794,
"text": "We can finally enter the Jupyter environment. Inside it, we will create the first neural network using Tensorflow v1.12 as backend and Keras as frontend."
},
{
"code": null,
"e": 8010,
"s": 7948,
"text": "Firstly close all the previously executing Docker containers."
},
{
"code": null,
"e": 8045,
"s": 8010,
"text": "Check the already open containers:"
},
{
"code": null,
"e": 8080,
"s": 8045,
"text": "Check the already open containers:"
},
{
"code": null,
"e": 8090,
"s": 8080,
"text": "docker ps"
},
{
"code": null,
"e": 8136,
"s": 8090,
"text": "2. Close all the Docker container/containers:"
},
{
"code": null,
"e": 8210,
"s": 8136,
"text": "docker container stop <container-id1> <container-id2> ... <container-idn>"
},
{
"code": null,
"e": 8251,
"s": 8210,
"text": "3. Close all the already open terminals."
},
{
"code": null,
"e": 8294,
"s": 8251,
"text": "Let’s open a new terminal CTRL + ALT + T :"
},
{
"code": null,
"e": 8361,
"s": 8294,
"text": "Run a new Docker container (personal tag will be used as default):"
},
{
"code": null,
"e": 8428,
"s": 8361,
"text": "Run a new Docker container (personal tag will be used as default):"
},
{
"code": null,
"e": 8681,
"s": 8428,
"text": "docker run -i -t \\--network=host \\--device=/dev/kfd \\--device=/dev/dri \\--group-add video \\--cap-add=SYS_PTRACE \\--security-opt seccomp=unconfined \\--workdir=/tf_docker_share \\-v $HOME/tf_docker_share:/tf_docker_share rocm/tensorflow:personal /bin/bash"
},
{
"code": null,
"e": 8748,
"s": 8681,
"text": "You should be logged into Tensorflow-ROCm docker container prompt."
},
{
"code": null,
"e": 8781,
"s": 8748,
"text": "2. Execute the Jupyter notebook:"
},
{
"code": null,
"e": 8823,
"s": 8781,
"text": "jupyter notebook --allow-root --port=8889"
},
{
"code": null,
"e": 8885,
"s": 8823,
"text": "a new browser window should appear, similar to the following:"
},
{
"code": null,
"e": 9175,
"s": 8885,
"text": "If the new tab does not appear automatically, on the browser, go back to the terminal where jupyter notebook command has been executed. On the bottom, there is a link to follow (press: CTRL + left mouse button on it) then, a new tab in your browser redirects you to Jupyter root directory."
},
{
"code": null,
"e": 9330,
"s": 9175,
"text": "In the last section, of this tutorial, we will train a simple neural network on the MNIST dataset. We will firstly build a fully connected neural network."
},
{
"code": null,
"e": 9433,
"s": 9330,
"text": "Let’s create a new notebook, by selecting Python3 from the upper-right menu in Jupyter root directory."
},
{
"code": null,
"e": 9576,
"s": 9433,
"text": "A new Jupiter notebook should pop-up in a new browser tab. Rename it tofc_network by clicking Untitled on the upper left corner of the window."
},
{
"code": null,
"e": 9634,
"s": 9576,
"text": "Let’s check Tensorflow backend. On the first cell insert:"
},
{
"code": null,
"e": 9681,
"s": 9634,
"text": "import tensorflow as tf; print(tf.__version__)"
},
{
"code": null,
"e": 9747,
"s": 9681,
"text": "then press SHIFT + ENTER to execute. The output should look like:"
},
{
"code": null,
"e": 9780,
"s": 9747,
"text": "We are using Tensorflow v1.12.0."
},
{
"code": null,
"e": 9829,
"s": 9780,
"text": "Let’s import some useful functions, to use next:"
},
{
"code": null,
"e": 10065,
"s": 9829,
"text": "from tensorflow.keras.datasets import mnistfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Dropoutfrom tensorflow.keras.optimizers import RMSpropfrom tensorflow.keras.utils import to_categorical"
},
{
"code": null,
"e": 10117,
"s": 10065,
"text": "Let’s set batch size, epochs and number of classes."
},
{
"code": null,
"e": 10161,
"s": 10117,
"text": "batch_size = 128num_classes = 10epochs = 10"
},
{
"code": null,
"e": 10238,
"s": 10161,
"text": "We will now download and preprocess inputs, loading them into system memory."
},
{
"code": null,
"e": 10723,
"s": 10238,
"text": "# the data, split between train and test sets(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train.reshape(60000, 784)x_test = x_test.reshape(10000, 784)x_train = x_train.astype('float32')x_test = x_test.astype('float32')x_train /= 255x_test /= 255print(x_train.shape[0], 'train samples')print(x_test.shape[0], 'test samples')# convert class vectors to binary class matricesy_train = to_categorical(y_train, num_classes)y_test = to_categorical(y_test, num_classes)"
},
{
"code": null,
"e": 10776,
"s": 10723,
"text": "It’s time to define the neural network architecture:"
},
{
"code": null,
"e": 10994,
"s": 10776,
"text": "model = Sequential()model.add(Dense(512, activation='relu', input_shape=(784,)))model.add(Dropout(0.2))model.add(Dense(512, activation='relu'))model.add(Dropout(0.2))model.add(Dense(num_classes, activation='softmax'))"
},
{
"code": null,
"e": 11186,
"s": 10994,
"text": "We will use a very simple, two-layer fully-connected network, with 512 neurons per layer. It’s also included a 20% drop probability on the neuron connections, in order to prevent overfitting."
},
{
"code": null,
"e": 11242,
"s": 11186,
"text": "Let’s print some insight into the network architecture:"
},
{
"code": null,
"e": 11258,
"s": 11242,
"text": "model.summary()"
},
{
"code": null,
"e": 11515,
"s": 11258,
"text": "Despite the simplicity of the problem, we have a considerable number of parameters to train (almost ~700.000), it means also considerable computational power consumption. Convolutional Neural Networks will solve the issue reducing computational complexity."
},
{
"code": null,
"e": 11539,
"s": 11515,
"text": "Now, compile the model:"
},
{
"code": null,
"e": 11655,
"s": 11539,
"text": "model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])"
},
{
"code": null,
"e": 11675,
"s": 11655,
"text": "and start training:"
},
{
"code": null,
"e": 11872,
"s": 11675,
"text": "history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))"
},
{
"code": null,
"e": 12042,
"s": 11872,
"text": "The neural network has been trained on a single RX 480 with a respectable 47us/step. For comparison, an Nvidia Tesla K80 is reaching 43us/step but is 10x more expensive."
},
{
"code": null,
"e": 12219,
"s": 12042,
"text": "As an additional step, if your system has multiple GPUs, is possible to leverage Keras capabilities, in order to reduce training time, splitting the batch among different GPUs."
},
{
"code": null,
"e": 12399,
"s": 12219,
"text": "To do that, first it’s required to specify the number of GPUs to use for training by, declaring an environmental variable (put the following command on a single cell and execute):"
},
{
"code": null,
"e": 12435,
"s": 12399,
"text": "!export HIP_VISIBLE_DEVICES=0,1,..."
},
{
"code": null,
"e": 12554,
"s": 12435,
"text": "Numbers from 0 to ... are defining which GPU to use for training. In case you want to disable GPU acceleration simply:"
},
{
"code": null,
"e": 12585,
"s": 12554,
"text": "!export HIP_VISIBLE_DEVICES=-1"
},
{
"code": null,
"e": 12638,
"s": 12585,
"text": "It’s also necessary to add multi_gpu_model function."
},
{
"code": null,
"e": 12716,
"s": 12638,
"text": "As an example, if you have 3 GPUs, the previous code will modify accordingly."
},
{
"code": null,
"e": 12882,
"s": 12716,
"text": "That concludes this tutorial. The next step will be to test a Convolutional Neural Network on the MNIST dataset. Comparing performances in both single and multi-GPU."
},
{
"code": null,
"e": 13168,
"s": 12882,
"text": "What’s relevant here, is that AMD GPUs perform quite well under computational load at a fraction of the price. GPU market is changing rapidly and ROCm gave to researchers, engineers, and startups, very powerful, open-source tools to adopt, lowering upfront costs in hardware equipment."
},
{
"code": null,
"e": 13193,
"s": 13168,
"text": "Article by Mattia Varile"
}
] |
Scala - Currying Functions
|
Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. Curried functions are defined with multiple parameter lists, as follows −
def strcat(s1: String)(s2: String) = s1 + s2
Alternatively, you can also use the following syntax to define a curried function −
def strcat(s1: String) = (s2: String) => s1 + s2
Following is the syntax to call a curried function −
strcat("foo")("bar")
You can define more than two parameters on a curried function based on your requirement. Try the following example program to show currying concept.
object Demo {
def main(args: Array[String]) {
val str1:String = "Hello, "
val str2:String = "Scala!"
println( "str1 + str2 = " + strcat(str1)(str2) )
}
def strcat(s1: String)(s2: String) = {
s1 + s2
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
str1 + str2 = Hello, Scala!
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2193,
"s": 1998,
"text": "Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. Curried functions are defined with multiple parameter lists, as follows −"
},
{
"code": null,
"e": 2239,
"s": 2193,
"text": "def strcat(s1: String)(s2: String) = s1 + s2\n"
},
{
"code": null,
"e": 2323,
"s": 2239,
"text": "Alternatively, you can also use the following syntax to define a curried function −"
},
{
"code": null,
"e": 2373,
"s": 2323,
"text": "def strcat(s1: String) = (s2: String) => s1 + s2\n"
},
{
"code": null,
"e": 2426,
"s": 2373,
"text": "Following is the syntax to call a curried function −"
},
{
"code": null,
"e": 2448,
"s": 2426,
"text": "strcat(\"foo\")(\"bar\")\n"
},
{
"code": null,
"e": 2597,
"s": 2448,
"text": "You can define more than two parameters on a curried function based on your requirement. Try the following example program to show currying concept."
},
{
"code": null,
"e": 2845,
"s": 2597,
"text": "object Demo {\n def main(args: Array[String]) {\n val str1:String = \"Hello, \"\n val str2:String = \"Scala!\"\n \n println( \"str1 + str2 = \" + strcat(str1)(str2) )\n }\n\n def strcat(s1: String)(s2: String) = {\n s1 + s2\n }\n}"
},
{
"code": null,
"e": 2952,
"s": 2845,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 2986,
"s": 2952,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 3015,
"s": 2986,
"text": "str1 + str2 = Hello, Scala!\n"
},
{
"code": null,
"e": 3048,
"s": 3015,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3067,
"s": 3048,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3102,
"s": 3067,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3123,
"s": 3102,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 3158,
"s": 3123,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3176,
"s": 3158,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3211,
"s": 3176,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3229,
"s": 3211,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3264,
"s": 3229,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3282,
"s": 3264,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3317,
"s": 3282,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3340,
"s": 3317,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3347,
"s": 3340,
"text": " Print"
},
{
"code": null,
"e": 3358,
"s": 3347,
"text": " Add Notes"
}
] |
Camera App with Flask and OpenCV. Apply Snapchat like filters with OpenCV and flask. | Towards Data Science
|
In this blog post, we are going to build a camera app using flask framework wherein we can click pictures, record videos, apply filters like greyscale, negative and ‘face only’ filter like the one that appears on Snapchat. I have used a very basic design for the front-end since the main motive behind the project was to familiarize myself with the flask web-framework and also include live videostream. The same can be scaled up to add many more features.
Demo:
We make use of concepts like threading, HTTP request-response, global variables, error handling and face detection. Let’s look at how all these play out in a detailed manner.
Firstly, the front-end is a basic HTML file with buttons to take inputs and image source tag to display output frames after pre-processing in the back-end. Buttons in the file posts data to the server. The file also displays a few instructions to use the app. This file is saved inside the ‘templates’ folder in the project directory.
As for the back-end, it is a single python script which does all the magic. It is saved in the project directory. Let’s look at parts of the file separately in order to understand it’s working.
Initialization:
In the code above, we import all necessary modules.
Flask is a micro web-framework which works like a bridge between front and back-end. From flask, we import ‘Response’ and ‘request’ modules to handle HTTP response-requests. ‘render_template’ is used to render the HTML file shown before. OpenCV is the module used to perform all the computer vision tasks. ‘Thread’ module is used to spawn new threads.
We then declare all the global variables that act like a ‘toggle switch’ to perform different tasks like capture image, start/stop recording and applying filters. Initialize the variables to 0 to set everything to false.
In line 18, we try to create a folder named ‘shots’ if it doesn’t exist. This is where all the captured images are saved.
Line 24 loads a pretrained face detection model for future uses and line 27 creates an instance of the Flask app. Line 30 creates a video capture object for the built-in camera.
Functions:
‘record’ function is used to start recording i.e. write frames into an avi file while ‘rec’ variable is set to true. It uses ‘out’ which is an object for video writer initialized later. (Note: If you feel recorded video is fast or slow, fiddle around with the value of time.sleep).
‘detect_face()’ takes camera frames as input and returns a cropped out frame containing just the face detected in that frame. It uses the pretrained face detection model loaded earlier.(Please visit this website to get an in-depth understanding of how this is being done).
‘gen_frames’ is an important function wherein the actual frame capture(through the camera) and processing is done. It runs in an infinite while loop. Line 4 captures frames from the camera object. If frame capture is successful, it checks if any of the filter switches are true. If ‘face’, ‘neg’ or ‘grey’ are true, face filter, negative filter and greyscale filter are applied on the read frame respectively.
If ‘capture’ variable is set to true, it is reset to false(global variable) and the current frame is saved in ‘png’ format. If ‘rec’ is true, frame is copied to ‘rec_frame’ global variable which is saved into a video file when triggered.
Line 25 encodes the frame into the memory buffer and is then converted into an array of bytes. Line 27 yields the frame data in a format required to be sent as a HTTP response.
HTTP Routes:
This is where the front-end communicates with the server. The communication happens in ‘GET’ and ‘POST’ methods through URL routes.
‘@app. route(‘/’)’ is a Python decorator that Flask provides to assign URLs to functions in our app easily. Route ‘/’ is the root URL and ‘index()’ function is called when root URL is entered. ‘index.html’ file is rendered from the function into the webpage.
Route ‘/video_feed’ is set as the source for image in the html file. This function returns response chunks of frames yielded by ‘gen_frames()’ on a loop.
Route ‘/requests’ is assigned to the ‘tasks()’ function which handles all the switches and video recording. This route has both ‘POST’ and ‘GET’ methods i.e. it accepts information and also sends information. All previous routes were ‘GET’ by default.
If HTTP method from the client side is ‘POST’, ‘request.form.get’ accepts data from the buttons pressed by the user and reverses the previous state of the global variables that act like switches in the ‘gen_frame’ function. For example, when user presses ‘Grey’ button, ‘grey’ global variable is set to True thereby turning the frames to greyscale in the ‘gen_frames’ function. When the ‘Grey’ button is pressed again, ‘grey’ is set to false turning the frames back to normal.
Recording the frames into a video while also running the flask app is quite tricky. The easiest solution is to start a new thread.
A thread is a separate flow of execution. This means that your program will have two things happening at once. A thread shares information like data segment, code segment, files etc. with its peer threads while it contains its own registers, stack, counter etc.
In our case, ‘record()’ function has it’s own while loop, so that loop runs in the new thread. First, we create a ‘VideoWriter’ object when ‘rec’ is true. In line 37, we initialize a new thread with target being ‘record()’ function and line 38 starts the new thread where ‘record()’ function is run. When record button is pressed again, ‘VideoWriter’ object is released and the recording stops to save the video in the root directory.
Finally, if HTTP method from client side is ‘GET’, ‘index.html’ template is rendered.
Main function:
‘app.run()’ is used to start the flask app in its default address: http://127.0.0.1:5000/. You can set a different host and port number by adding ‘host’ and ‘port’ arguments to the function ‘run’. Setting host to broadcast address 0.0.0.0 would make the app visible in the whole local area network(wifi, etc). So, you can access the app from your mobile device if it’s connected to the same Wi-Fi. This makes a good ‘SPY CAM’.
To run this app, you should have python, flask and OpenCV installed on your PC. To start the app, move to the project directory in the command prompt. Type and enter:
python camera_flask_app.py
Now, copy-paste http://127.0.0.1:5000/ into your favorite internet browser and that’s it.
You can add more features like AI filters to build a Snapchat-esque app . You can also enhance the user interface making it more interactive and colorful. You can get the source code for this project in my GitHub account.
|
[
{
"code": null,
"e": 629,
"s": 172,
"text": "In this blog post, we are going to build a camera app using flask framework wherein we can click pictures, record videos, apply filters like greyscale, negative and ‘face only’ filter like the one that appears on Snapchat. I have used a very basic design for the front-end since the main motive behind the project was to familiarize myself with the flask web-framework and also include live videostream. The same can be scaled up to add many more features."
},
{
"code": null,
"e": 635,
"s": 629,
"text": "Demo:"
},
{
"code": null,
"e": 810,
"s": 635,
"text": "We make use of concepts like threading, HTTP request-response, global variables, error handling and face detection. Let’s look at how all these play out in a detailed manner."
},
{
"code": null,
"e": 1145,
"s": 810,
"text": "Firstly, the front-end is a basic HTML file with buttons to take inputs and image source tag to display output frames after pre-processing in the back-end. Buttons in the file posts data to the server. The file also displays a few instructions to use the app. This file is saved inside the ‘templates’ folder in the project directory."
},
{
"code": null,
"e": 1339,
"s": 1145,
"text": "As for the back-end, it is a single python script which does all the magic. It is saved in the project directory. Let’s look at parts of the file separately in order to understand it’s working."
},
{
"code": null,
"e": 1355,
"s": 1339,
"text": "Initialization:"
},
{
"code": null,
"e": 1407,
"s": 1355,
"text": "In the code above, we import all necessary modules."
},
{
"code": null,
"e": 1759,
"s": 1407,
"text": "Flask is a micro web-framework which works like a bridge between front and back-end. From flask, we import ‘Response’ and ‘request’ modules to handle HTTP response-requests. ‘render_template’ is used to render the HTML file shown before. OpenCV is the module used to perform all the computer vision tasks. ‘Thread’ module is used to spawn new threads."
},
{
"code": null,
"e": 1980,
"s": 1759,
"text": "We then declare all the global variables that act like a ‘toggle switch’ to perform different tasks like capture image, start/stop recording and applying filters. Initialize the variables to 0 to set everything to false."
},
{
"code": null,
"e": 2102,
"s": 1980,
"text": "In line 18, we try to create a folder named ‘shots’ if it doesn’t exist. This is where all the captured images are saved."
},
{
"code": null,
"e": 2280,
"s": 2102,
"text": "Line 24 loads a pretrained face detection model for future uses and line 27 creates an instance of the Flask app. Line 30 creates a video capture object for the built-in camera."
},
{
"code": null,
"e": 2291,
"s": 2280,
"text": "Functions:"
},
{
"code": null,
"e": 2573,
"s": 2291,
"text": "‘record’ function is used to start recording i.e. write frames into an avi file while ‘rec’ variable is set to true. It uses ‘out’ which is an object for video writer initialized later. (Note: If you feel recorded video is fast or slow, fiddle around with the value of time.sleep)."
},
{
"code": null,
"e": 2846,
"s": 2573,
"text": "‘detect_face()’ takes camera frames as input and returns a cropped out frame containing just the face detected in that frame. It uses the pretrained face detection model loaded earlier.(Please visit this website to get an in-depth understanding of how this is being done)."
},
{
"code": null,
"e": 3256,
"s": 2846,
"text": "‘gen_frames’ is an important function wherein the actual frame capture(through the camera) and processing is done. It runs in an infinite while loop. Line 4 captures frames from the camera object. If frame capture is successful, it checks if any of the filter switches are true. If ‘face’, ‘neg’ or ‘grey’ are true, face filter, negative filter and greyscale filter are applied on the read frame respectively."
},
{
"code": null,
"e": 3494,
"s": 3256,
"text": "If ‘capture’ variable is set to true, it is reset to false(global variable) and the current frame is saved in ‘png’ format. If ‘rec’ is true, frame is copied to ‘rec_frame’ global variable which is saved into a video file when triggered."
},
{
"code": null,
"e": 3671,
"s": 3494,
"text": "Line 25 encodes the frame into the memory buffer and is then converted into an array of bytes. Line 27 yields the frame data in a format required to be sent as a HTTP response."
},
{
"code": null,
"e": 3684,
"s": 3671,
"text": "HTTP Routes:"
},
{
"code": null,
"e": 3816,
"s": 3684,
"text": "This is where the front-end communicates with the server. The communication happens in ‘GET’ and ‘POST’ methods through URL routes."
},
{
"code": null,
"e": 4075,
"s": 3816,
"text": "‘@app. route(‘/’)’ is a Python decorator that Flask provides to assign URLs to functions in our app easily. Route ‘/’ is the root URL and ‘index()’ function is called when root URL is entered. ‘index.html’ file is rendered from the function into the webpage."
},
{
"code": null,
"e": 4229,
"s": 4075,
"text": "Route ‘/video_feed’ is set as the source for image in the html file. This function returns response chunks of frames yielded by ‘gen_frames()’ on a loop."
},
{
"code": null,
"e": 4481,
"s": 4229,
"text": "Route ‘/requests’ is assigned to the ‘tasks()’ function which handles all the switches and video recording. This route has both ‘POST’ and ‘GET’ methods i.e. it accepts information and also sends information. All previous routes were ‘GET’ by default."
},
{
"code": null,
"e": 4958,
"s": 4481,
"text": "If HTTP method from the client side is ‘POST’, ‘request.form.get’ accepts data from the buttons pressed by the user and reverses the previous state of the global variables that act like switches in the ‘gen_frame’ function. For example, when user presses ‘Grey’ button, ‘grey’ global variable is set to True thereby turning the frames to greyscale in the ‘gen_frames’ function. When the ‘Grey’ button is pressed again, ‘grey’ is set to false turning the frames back to normal."
},
{
"code": null,
"e": 5089,
"s": 4958,
"text": "Recording the frames into a video while also running the flask app is quite tricky. The easiest solution is to start a new thread."
},
{
"code": null,
"e": 5351,
"s": 5089,
"text": "A thread is a separate flow of execution. This means that your program will have two things happening at once. A thread shares information like data segment, code segment, files etc. with its peer threads while it contains its own registers, stack, counter etc."
},
{
"code": null,
"e": 5786,
"s": 5351,
"text": "In our case, ‘record()’ function has it’s own while loop, so that loop runs in the new thread. First, we create a ‘VideoWriter’ object when ‘rec’ is true. In line 37, we initialize a new thread with target being ‘record()’ function and line 38 starts the new thread where ‘record()’ function is run. When record button is pressed again, ‘VideoWriter’ object is released and the recording stops to save the video in the root directory."
},
{
"code": null,
"e": 5872,
"s": 5786,
"text": "Finally, if HTTP method from client side is ‘GET’, ‘index.html’ template is rendered."
},
{
"code": null,
"e": 5887,
"s": 5872,
"text": "Main function:"
},
{
"code": null,
"e": 6314,
"s": 5887,
"text": "‘app.run()’ is used to start the flask app in its default address: http://127.0.0.1:5000/. You can set a different host and port number by adding ‘host’ and ‘port’ arguments to the function ‘run’. Setting host to broadcast address 0.0.0.0 would make the app visible in the whole local area network(wifi, etc). So, you can access the app from your mobile device if it’s connected to the same Wi-Fi. This makes a good ‘SPY CAM’."
},
{
"code": null,
"e": 6481,
"s": 6314,
"text": "To run this app, you should have python, flask and OpenCV installed on your PC. To start the app, move to the project directory in the command prompt. Type and enter:"
},
{
"code": null,
"e": 6508,
"s": 6481,
"text": "python camera_flask_app.py"
},
{
"code": null,
"e": 6598,
"s": 6508,
"text": "Now, copy-paste http://127.0.0.1:5000/ into your favorite internet browser and that’s it."
}
] |
Python – Making a Reddit bot with PRAW
|
03 Jul, 2020
Reddit is a network of communities based on people’s interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them.A Reddit bot is something that automatically responds to a user’s post or automatically posts things at certain intervals. This could depend on what content the users post. It can be triggered by certain key phrases and also depends on various subreddits regarding their content.In order to implement a Reddit bot, we will use the Python Reddit API Wrapper (PRAW). It allows us to login to the Reddit API to directly interact with the backend of the website. More information about this library can be found here – PRAW – Python Reddit API Wrapper.
Our bot will tell the similar words for a given word. We will use the enchant module’s suggest() method to find the similar words.
Algorithm :
Import the modules praw and enchant.Create an authorized Reddit instance with valid parameters.Choose the subreddit where the bot is to be live on.Choose a word that will trigger the bot in that subreddit.Inspect every comment in the subreddit for the trigger phrase.On finding the trigger phrase, extract the word from the comment and find its similar words using the enchant module.Reply to the comment with the similar words.
Import the modules praw and enchant.
Create an authorized Reddit instance with valid parameters.
Choose the subreddit where the bot is to be live on.
Choose a word that will trigger the bot in that subreddit.
Inspect every comment in the subreddit for the trigger phrase.
On finding the trigger phrase, extract the word from the comment and find its similar words using the enchant module.
Reply to the comment with the similar words.
# import the modulesimport prawimport enchant # initialize with appropriate valuesclient_id = ""client_secret = ""username = ""password = ""user_agent = "" # creating an authorized reddit instancereddit = praw.Reddit(client_id = client_id, client_secret = client_secret, username = username, password = password, user_agent = user_agent) # the subreddit where the bot is to be live ontarget_sub = "GRE"subreddit = reddit.subreddit(target_sub) # phrase to trigger the bottrigger_phrase = "! GfGBot" # enchant dictionaryd = enchant.Dict("en_US") # check every comment in the subredditfor comment in subreddit.stream.comments(): # check the trigger_phrase in each comment if trigger_phrase in comment.body: # extract the word from the comment word = comment.body.replace(trigger_phrase, "") # initialize the reply text reply_text = "" # find the similar words similar_words = d.suggest(word) for similar in similar_words: reply_text += similar + " " # comment the similar words comment.reply(reply_text)
Triggering the bot :
The bot replying with the similar words :
Python-projects
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 773,
"s": 28,
"text": "Reddit is a network of communities based on people’s interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them.A Reddit bot is something that automatically responds to a user’s post or automatically posts things at certain intervals. This could depend on what content the users post. It can be triggered by certain key phrases and also depends on various subreddits regarding their content.In order to implement a Reddit bot, we will use the Python Reddit API Wrapper (PRAW). It allows us to login to the Reddit API to directly interact with the backend of the website. More information about this library can be found here – PRAW – Python Reddit API Wrapper."
},
{
"code": null,
"e": 904,
"s": 773,
"text": "Our bot will tell the similar words for a given word. We will use the enchant module’s suggest() method to find the similar words."
},
{
"code": null,
"e": 916,
"s": 904,
"text": "Algorithm :"
},
{
"code": null,
"e": 1345,
"s": 916,
"text": "Import the modules praw and enchant.Create an authorized Reddit instance with valid parameters.Choose the subreddit where the bot is to be live on.Choose a word that will trigger the bot in that subreddit.Inspect every comment in the subreddit for the trigger phrase.On finding the trigger phrase, extract the word from the comment and find its similar words using the enchant module.Reply to the comment with the similar words."
},
{
"code": null,
"e": 1382,
"s": 1345,
"text": "Import the modules praw and enchant."
},
{
"code": null,
"e": 1442,
"s": 1382,
"text": "Create an authorized Reddit instance with valid parameters."
},
{
"code": null,
"e": 1495,
"s": 1442,
"text": "Choose the subreddit where the bot is to be live on."
},
{
"code": null,
"e": 1554,
"s": 1495,
"text": "Choose a word that will trigger the bot in that subreddit."
},
{
"code": null,
"e": 1617,
"s": 1554,
"text": "Inspect every comment in the subreddit for the trigger phrase."
},
{
"code": null,
"e": 1735,
"s": 1617,
"text": "On finding the trigger phrase, extract the word from the comment and find its similar words using the enchant module."
},
{
"code": null,
"e": 1780,
"s": 1735,
"text": "Reply to the comment with the similar words."
},
{
"code": "# import the modulesimport prawimport enchant # initialize with appropriate valuesclient_id = \"\"client_secret = \"\"username = \"\"password = \"\"user_agent = \"\" # creating an authorized reddit instancereddit = praw.Reddit(client_id = client_id, client_secret = client_secret, username = username, password = password, user_agent = user_agent) # the subreddit where the bot is to be live ontarget_sub = \"GRE\"subreddit = reddit.subreddit(target_sub) # phrase to trigger the bottrigger_phrase = \"! GfGBot\" # enchant dictionaryd = enchant.Dict(\"en_US\") # check every comment in the subredditfor comment in subreddit.stream.comments(): # check the trigger_phrase in each comment if trigger_phrase in comment.body: # extract the word from the comment word = comment.body.replace(trigger_phrase, \"\") # initialize the reply text reply_text = \"\" # find the similar words similar_words = d.suggest(word) for similar in similar_words: reply_text += similar + \" \" # comment the similar words comment.reply(reply_text)",
"e": 2969,
"s": 1780,
"text": null
},
{
"code": null,
"e": 2990,
"s": 2969,
"text": "Triggering the bot :"
},
{
"code": null,
"e": 3032,
"s": 2990,
"text": "The bot replying with the similar words :"
},
{
"code": null,
"e": 3048,
"s": 3032,
"text": "Python-projects"
},
{
"code": null,
"e": 3055,
"s": 3048,
"text": "Python"
},
{
"code": null,
"e": 3153,
"s": 3055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3171,
"s": 3153,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3213,
"s": 3171,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3248,
"s": 3213,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3274,
"s": 3248,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3306,
"s": 3274,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3335,
"s": 3306,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3362,
"s": 3335,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3383,
"s": 3362,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3406,
"s": 3383,
"text": "Introduction To PYTHON"
}
] |
File.OpenText() Method in C# with Examples
|
10 Nov, 2021
File.OpenText(String) is an inbuilt File class method which is used to open an existing UTF-8 encoded text file for reading.Syntax:
public static System.IO.StreamReader OpenText (string path);
Parameter: This function accepts a parameter which is illustrated below:
path: This is the specified text file which is going to be opened for reading.
Exceptions:
UnauthorizedAccessException: The caller does not have the required permission.
ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
ArgumentNullException: The path is null.
PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: The specified path is invalid.
FileNotFoundException: The file specified in the path was not found.
NotSupportedException: The path is in an invalid format.
Return Value: Returns a StreamReader on the specified path.Below are the programs to illustrate the File.OpenText(String) method.Program 1: Before running the below code, a text file file.txt is created with some contents shown below-
Below code open the text file file.txt for reading.
C#
// C# program to illustrate the usage// of File.OpenText(String) method // Using System and System.IO// namespacesusing System;using System.IO; class Test { public static void Main() { // Specifying a text file string path = @"file.txt"; // Opening the file for reading using(StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine()) != null) { // printing the file contents Console.WriteLine(s); } } }}
Executing:
GeeksforGeeks
Program 2: Initially, a file file.txt is created with some contents shown below-
This below code will overwrite the file contents with other specified contents then final contents will be printed.
C#
// C# program to illustrate the usage// of File.OpenText(String) method // Using System and System.IO// namespacesusing System;using System.IO; class Test { public static void Main() { // Specifying a text file string path = @"file.txt"; // Checking the existence of file if (File.Exists(path)) { using(StreamWriter sw = File.CreateText(path)) { // Overwriting the file with below // specified contents sw.WriteLine("GFG is a CS portal."); } } // Opening the file for reading using(StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine()) != null) { // printing the overwritten content Console.WriteLine(s); } } }}
Executing:
GFG is a CS portal.
arorakashish0911
clintra
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 162,
"s": 28,
"text": "File.OpenText(String) is an inbuilt File class method which is used to open an existing UTF-8 encoded text file for reading.Syntax: "
},
{
"code": null,
"e": 223,
"s": 162,
"text": "public static System.IO.StreamReader OpenText (string path);"
},
{
"code": null,
"e": 298,
"s": 223,
"text": "Parameter: This function accepts a parameter which is illustrated below: "
},
{
"code": null,
"e": 377,
"s": 298,
"text": "path: This is the specified text file which is going to be opened for reading."
},
{
"code": null,
"e": 390,
"s": 377,
"text": "Exceptions: "
},
{
"code": null,
"e": 469,
"s": 390,
"text": "UnauthorizedAccessException: The caller does not have the required permission."
},
{
"code": null,
"e": 615,
"s": 469,
"text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars."
},
{
"code": null,
"e": 656,
"s": 615,
"text": "ArgumentNullException: The path is null."
},
{
"code": null,
"e": 759,
"s": 656,
"text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 818,
"s": 759,
"text": "DirectoryNotFoundException: The specified path is invalid."
},
{
"code": null,
"e": 887,
"s": 818,
"text": "FileNotFoundException: The file specified in the path was not found."
},
{
"code": null,
"e": 944,
"s": 887,
"text": "NotSupportedException: The path is in an invalid format."
},
{
"code": null,
"e": 1179,
"s": 944,
"text": "Return Value: Returns a StreamReader on the specified path.Below are the programs to illustrate the File.OpenText(String) method.Program 1: Before running the below code, a text file file.txt is created with some contents shown below-"
},
{
"code": null,
"e": 1231,
"s": 1179,
"text": "Below code open the text file file.txt for reading."
},
{
"code": null,
"e": 1234,
"s": 1231,
"text": "C#"
},
{
"code": "// C# program to illustrate the usage// of File.OpenText(String) method // Using System and System.IO// namespacesusing System;using System.IO; class Test { public static void Main() { // Specifying a text file string path = @\"file.txt\"; // Opening the file for reading using(StreamReader sr = File.OpenText(path)) { string s = \"\"; while ((s = sr.ReadLine()) != null) { // printing the file contents Console.WriteLine(s); } } }}",
"e": 1778,
"s": 1234,
"text": null
},
{
"code": null,
"e": 1791,
"s": 1778,
"text": "Executing: "
},
{
"code": null,
"e": 1805,
"s": 1791,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1886,
"s": 1805,
"text": "Program 2: Initially, a file file.txt is created with some contents shown below-"
},
{
"code": null,
"e": 2002,
"s": 1886,
"text": "This below code will overwrite the file contents with other specified contents then final contents will be printed."
},
{
"code": null,
"e": 2005,
"s": 2002,
"text": "C#"
},
{
"code": "// C# program to illustrate the usage// of File.OpenText(String) method // Using System and System.IO// namespacesusing System;using System.IO; class Test { public static void Main() { // Specifying a text file string path = @\"file.txt\"; // Checking the existence of file if (File.Exists(path)) { using(StreamWriter sw = File.CreateText(path)) { // Overwriting the file with below // specified contents sw.WriteLine(\"GFG is a CS portal.\"); } } // Opening the file for reading using(StreamReader sr = File.OpenText(path)) { string s = \"\"; while ((s = sr.ReadLine()) != null) { // printing the overwritten content Console.WriteLine(s); } } }}",
"e": 2861,
"s": 2005,
"text": null
},
{
"code": null,
"e": 2873,
"s": 2861,
"text": "Executing: "
},
{
"code": null,
"e": 2893,
"s": 2873,
"text": "GFG is a CS portal."
},
{
"code": null,
"e": 2910,
"s": 2893,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2918,
"s": 2910,
"text": "clintra"
},
{
"code": null,
"e": 2939,
"s": 2918,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 2942,
"s": 2939,
"text": "C#"
},
{
"code": null,
"e": 3040,
"s": 2942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3083,
"s": 3040,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 3132,
"s": 3083,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 3155,
"s": 3132,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 3171,
"s": 3155,
"text": "C# | List Class"
},
{
"code": null,
"e": 3199,
"s": 3171,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 3260,
"s": 3199,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 3283,
"s": 3260,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 3305,
"s": 3283,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 3330,
"s": 3305,
"text": "Lambda Expressions in C#"
}
] |
Groovy - If/Else Statement
|
The next decision-making statement we will see is the if/else statement. The general form of this statement is −
if(condition) {
statement #1
statement #2
...
} else{
statement #3
statement #4
}
The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true it then executes the statements thereafter and stops before the else condition and exits out of the loop. If the condition is false it then executes the statements in the else statement block and then exits the loop. The following diagram shows the flow of the if statement.
Following is an example of a if/else statement −
class Example {
static void main(String[] args) {
// Initializing a local variable
int a = 2
//Check for the boolean condition
if (a<100) {
//If the condition is true print the following statement
println("The value is less than 100");
} else {
//If the condition is false print the following statement
println("The value is greater than 100");
}
}
}
In the above example, we are first initializing a variable to a value of 2. We are then evaluating the value of the variable and then deciding on which println statement should be executed. The output of the above code would be
The value is less than 100.
|
[
{
"code": null,
"e": 2485,
"s": 2372,
"text": "The next decision-making statement we will see is the if/else statement. The general form of this statement is −"
},
{
"code": null,
"e": 2591,
"s": 2485,
"text": "if(condition) { \n statement #1 \n statement #2 \n ... \n} else{ \n statement #3 \n statement #4 \n}\n"
},
{
"code": null,
"e": 2989,
"s": 2591,
"text": "The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true it then executes the statements thereafter and stops before the else condition and exits out of the loop. If the condition is false it then executes the statements in the else statement block and then exits the loop. The following diagram shows the flow of the if statement."
},
{
"code": null,
"e": 3038,
"s": 2989,
"text": "Following is an example of a if/else statement −"
},
{
"code": null,
"e": 3482,
"s": 3038,
"text": "class Example { \n static void main(String[] args) { \n // Initializing a local variable \n int a = 2\n\t\t\n //Check for the boolean condition \n if (a<100) { \n //If the condition is true print the following statement \n println(\"The value is less than 100\"); \n } else { \n //If the condition is false print the following statement \n println(\"The value is greater than 100\"); \n } \n } \n}"
},
{
"code": null,
"e": 3710,
"s": 3482,
"text": "In the above example, we are first initializing a variable to a value of 2. We are then evaluating the value of the variable and then deciding on which println statement should be executed. The output of the above code would be"
}
] |
Minimum sprinkers required to be turned on to water the plants
|
13 Jun, 2022
Given an array arr[] consisting of N integers, where the ith element represents the range of a sprinkler i.e [i-arr[i], i+arr[i]] it can water, the task is to find the minimum number of the sprinkler to be turned on to water every plant at the gallery. If it is not possible to water every plant, then print -1.Note: If arr[i] = -1, then the sprinkler cannot be turned on.
Examples:
Input: arr[ ] = {-1, 2, 2, -1, 0, 0}Output: 2Explanation: One of the possible way is:
Turn on the sprinkler at index 2, it can water the plants in the range [0, 4].
Turn on the sprinkler at index 5, it can water the plants in the range [5, 5].
Therefore, turning two sprinklers on can water all the plants. Also, it is the minimum possible count of sprinklers to be turned on.
Input: arr[ ] = {2, 3, 4, -1, 2, 0, 0, -1, 0}Output: -1
Approach: The above problem can be solved using the greedy technique. The idea is to first sort the range by left boundary and then traversing ranges from left and in each iteration select the rightmost boundary a sprinkler can cover having the left boundary in the current range. Follow the steps below to solve the problem:
Initialize a vector<pair<int, int>> say V to store the range of every sprinkler as a pair.
Traverse the array arr[] and if arr[i] is not equal to -1 then push the pair (i-arr[i], i+arr[i]) in the vector V.
Sort the vector of pairs in ascending order by the first element.
Initialize 2 variables say res, and maxRight to store the minimum sprinklers to be turned on and to store the rightmost boundary of an array.
Initialize a variable say i as 0 to iterate over the V.
Iterate until maxRight is less than N and perform the following steps:If i is equal to V.size() or V[i].first is greater than maxRight then print -1 and return.Store the right boundary of the current sprinkler in the variable say currMax.Now iterate until i+1 is less than V.size() and V[i+1].first is less than or equal to maxRight then in each iteration increment i by 1 and update currMax as currMax = max(currMax, V[i].second).If currMax is less than the maxRight then print -1 and return.Update maxRight as maxRight = currMax+1 then Increment res and i by 1.
If i is equal to V.size() or V[i].first is greater than maxRight then print -1 and return.
Store the right boundary of the current sprinkler in the variable say currMax.
Now iterate until i+1 is less than V.size() and V[i+1].first is less than or equal to maxRight then in each iteration increment i by 1 and update currMax as currMax = max(currMax, V[i].second).
If currMax is less than the maxRight then print -1 and return.
Update maxRight as maxRight = currMax+1 then Increment res and i by 1.
Finally, after completing the above step, print the res as the answer.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum number of// sprinkler to be turned onint minSprinklers(int arr[], int N){ // Stores the leftmost and rightmost // point of every sprinklers vector<pair<int, int> > V; // Traverse the array arr[] for (int i = 0; i < N; i++) { if (arr[i] > -1) { V.push_back( pair<int, int>(i - arr[i], i + arr[i])); } } // Sort the array sprinklers in // ascending order by first element sort(V.begin(), V.end()); // Stores the rightmost range // of a sprinkler int maxRight = 0; // Stores minimum sprinklers // to be turned on int res = 0; int i = 0; // Iterate until maxRight is // less than N while (maxRight < N) { // If i is equal to V.size() // or V[i].first is greater // than maxRight if (i == V.size() || V[i].first > maxRight) { return -1; } // Stores the rightmost boundary // of current sprinkler int currMax = V[i].second; // Iterate until i+1 is less // than V.size() and V[i+1].first // is less than or equal to maxRight while (i + 1 < V.size() && V[i + 1].first <= maxRight) { // Increment i by 1 i++; // Update currMax currMax = max(currMax, V[i].second); } // If currMax is less than the maxRight if (currMax < maxRight) { // Return -1 return -1; } // Increment res by 1 res++; // Update maxRight maxRight = currMax + 1; // Increment i by 1 i++; } // Return res as answer return res;} // Drive code.int main(){ // Input int arr[] = { -1, 2, 2, -1, 0, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << minSprinklers(arr, N);}
// Java program for the above approachimport java.io.*;import java.util.*; class pair { int x; int y; pair(int x1, int y1) { x = x1; y = y1; }} class GFG { // Function to find minimum number of // sprinkler to be turned on static int minSprinklers(int arr[], int N) { // Stores the leftmost and rightmost // point of every sprinklers ArrayList<pair> V = new ArrayList<pair>(); // Traverse the array arr[] for (int i = 0; i < N; i++) { if (arr[i] > -1) { V.add(new pair(i - arr[i], i + arr[i])); } } // Sort the array sprinklers in // ascending order by first element Collections.sort(V, new Comparator<pair>() { @Override public int compare(pair p1, pair p2) { return p1.x - p2.x; } }); // Stores the rightmost range // of a sprinkler int maxRight = 0; // Stores minimum sprinklers // to be turned on int res = 0; int i = 0; // Iterate until maxRight is // less than N while (maxRight < N) { // If i is equal to V.size() // or V[i].first is greater // than maxRight if (i == V.size() || V.get(i).x > maxRight) { return -1; } // Stores the rightmost boundary // of current sprinkler int currMax = V.get(i).y; // Iterate until i+1 is less // than V.size() and V[i+1].first // is less than or equal to maxRight while (i + 1 < V.size() && V.get(i + 1).x <= maxRight) { // Increment i by 1 i++; // Update currMax currMax = Math.max(currMax, V.get(i).y); } // If currMax is less than the maxRight if (currMax < maxRight) { // Return -1 return -1; } // Increment res by 1 res++; // Update maxRight maxRight = currMax + 1; // Increment i by 1 i++; } // Return res as answer return res; } // Driver code public static void main(String[] args) { int arr[] = { -1, 2, 2, -1, 0, 0 }; int N = 6; // Function call System.out.println(minSprinklers(arr, N)); }} // This code is contributed by Manu Pathria
# Python program for the above approach # Function to find minimum number of# sprinkler to be turned on def minSprinklers(arr, N): # Stores the leftmost and rightmost # point of every sprinklers V = [] # Traverse the array arr[] for i in range(N): if (arr[i] > -1): V.append([i - arr[i], i + arr[i]]) # Sort the array sprinklers in # ascending order by first element V.sort() # Stores the rightmost range # of a sprinkler maxRight = 0 # Stores minimum sprinklers # to be turned on res = 0 i = 0 # Iterate until maxRight is # less than N while (maxRight < N): # If i is equal to V.size() # or V[i][0] is greater # than maxRight if (i == len(V) or V[i][0] > maxRight): return -1 # Stores the rightmost boundary # of current sprinkler currMax = V[i][1] # Iterate until i+1 is less # than V.size() and V[i+1][0] # is less than or equal to maxRight while (i + 1 < len(V) and V[i + 1][0] <= maxRight): # Increment i by 1 i += 1 # Update currMax currMax = max(currMax, V[i][1]) # If currMax is less than the maxRight if (currMax < maxRight): # Return -1 return -1 # Increment res by 1 res += 1 # Update maxRight maxRight = currMax + 1 # Increment i by 1 i += 1 # Return res as answer return res # Drive code. # Inputarr = [-1, 2, 2, -1, 0, 0]N = len(arr) # Function callprint(minSprinklers(arr, N)) # This code is contributed by _saurabh_jaiswal.
<script> // JavaScript program for the above approach // Function to find minimum number of// sprinkler to be turned onfunction minSprinklers(arr, N) { // Stores the leftmost and rightmost // point of every sprinklers let V = []; // Traverse the array arr[] for (let i = 0; i < N; i++) { if (arr[i] > -1) { V.push([i - arr[i], i + arr[i]]); } } // Sort the array sprinklers in // ascending order by first element V.sort((a, b) => a - b); // Stores the rightmost range // of a sprinkler let maxRight = 0; // Stores minimum sprinklers // to be turned on let res = 0; let i = 0; // Iterate until maxRight is // less than N while (maxRight < N) { // If i is equal to V.size() // or V[i][0] is greater // than maxRight if (i == V.length || V[i][0] > maxRight) { return -1; } // Stores the rightmost boundary // of current sprinkler let currMax = V[i][1]; // Iterate until i+1 is less // than V.size() and V[i+1][0] // is less than or equal to maxRight while (i + 1 < V.length && V[i + 1][0] <= maxRight) { // Increment i by 1 i++; // Update currMax currMax = Math.max(currMax, V[i][1]); } // If currMax is less than the maxRight if (currMax < maxRight) { // Return -1 return -1; } // Increment res by 1 res++; // Update maxRight maxRight = currMax + 1; // Increment i by 1 i++; } // Return res as answer return res;} // Drive code. // Inputlet arr = [-1, 2, 2, -1, 0, 0];let N = arr.length; // Function calldocument.write(minSprinklers(arr, N)); </script>
2
Time Complexity: O(N * log(N))Auxiliary Space: O(N)
manupathria
sankcan55
gfgking
_saurabh_jaiswal
abhinavroygfg
nikhil__yadav
Amazon
Flipkart
interview-preparation
Arrays
Mathematical
Sorting
Flipkart
Amazon
Arrays
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 425,
"s": 52,
"text": "Given an array arr[] consisting of N integers, where the ith element represents the range of a sprinkler i.e [i-arr[i], i+arr[i]] it can water, the task is to find the minimum number of the sprinkler to be turned on to water every plant at the gallery. If it is not possible to water every plant, then print -1.Note: If arr[i] = -1, then the sprinkler cannot be turned on."
},
{
"code": null,
"e": 435,
"s": 425,
"text": "Examples:"
},
{
"code": null,
"e": 521,
"s": 435,
"text": "Input: arr[ ] = {-1, 2, 2, -1, 0, 0}Output: 2Explanation: One of the possible way is:"
},
{
"code": null,
"e": 600,
"s": 521,
"text": "Turn on the sprinkler at index 2, it can water the plants in the range [0, 4]."
},
{
"code": null,
"e": 679,
"s": 600,
"text": "Turn on the sprinkler at index 5, it can water the plants in the range [5, 5]."
},
{
"code": null,
"e": 812,
"s": 679,
"text": "Therefore, turning two sprinklers on can water all the plants. Also, it is the minimum possible count of sprinklers to be turned on."
},
{
"code": null,
"e": 868,
"s": 812,
"text": "Input: arr[ ] = {2, 3, 4, -1, 2, 0, 0, -1, 0}Output: -1"
},
{
"code": null,
"e": 1194,
"s": 868,
"text": "Approach: The above problem can be solved using the greedy technique. The idea is to first sort the range by left boundary and then traversing ranges from left and in each iteration select the rightmost boundary a sprinkler can cover having the left boundary in the current range. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1285,
"s": 1194,
"text": "Initialize a vector<pair<int, int>> say V to store the range of every sprinkler as a pair."
},
{
"code": null,
"e": 1400,
"s": 1285,
"text": "Traverse the array arr[] and if arr[i] is not equal to -1 then push the pair (i-arr[i], i+arr[i]) in the vector V."
},
{
"code": null,
"e": 1466,
"s": 1400,
"text": "Sort the vector of pairs in ascending order by the first element."
},
{
"code": null,
"e": 1608,
"s": 1466,
"text": "Initialize 2 variables say res, and maxRight to store the minimum sprinklers to be turned on and to store the rightmost boundary of an array."
},
{
"code": null,
"e": 1664,
"s": 1608,
"text": "Initialize a variable say i as 0 to iterate over the V."
},
{
"code": null,
"e": 2228,
"s": 1664,
"text": "Iterate until maxRight is less than N and perform the following steps:If i is equal to V.size() or V[i].first is greater than maxRight then print -1 and return.Store the right boundary of the current sprinkler in the variable say currMax.Now iterate until i+1 is less than V.size() and V[i+1].first is less than or equal to maxRight then in each iteration increment i by 1 and update currMax as currMax = max(currMax, V[i].second).If currMax is less than the maxRight then print -1 and return.Update maxRight as maxRight = currMax+1 then Increment res and i by 1."
},
{
"code": null,
"e": 2319,
"s": 2228,
"text": "If i is equal to V.size() or V[i].first is greater than maxRight then print -1 and return."
},
{
"code": null,
"e": 2398,
"s": 2319,
"text": "Store the right boundary of the current sprinkler in the variable say currMax."
},
{
"code": null,
"e": 2592,
"s": 2398,
"text": "Now iterate until i+1 is less than V.size() and V[i+1].first is less than or equal to maxRight then in each iteration increment i by 1 and update currMax as currMax = max(currMax, V[i].second)."
},
{
"code": null,
"e": 2655,
"s": 2592,
"text": "If currMax is less than the maxRight then print -1 and return."
},
{
"code": null,
"e": 2726,
"s": 2655,
"text": "Update maxRight as maxRight = currMax+1 then Increment res and i by 1."
},
{
"code": null,
"e": 2797,
"s": 2726,
"text": "Finally, after completing the above step, print the res as the answer."
},
{
"code": null,
"e": 2848,
"s": 2797,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2852,
"s": 2848,
"text": "C++"
},
{
"code": null,
"e": 2857,
"s": 2852,
"text": "Java"
},
{
"code": null,
"e": 2865,
"s": 2857,
"text": "Python3"
},
{
"code": null,
"e": 2876,
"s": 2865,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum number of// sprinkler to be turned onint minSprinklers(int arr[], int N){ // Stores the leftmost and rightmost // point of every sprinklers vector<pair<int, int> > V; // Traverse the array arr[] for (int i = 0; i < N; i++) { if (arr[i] > -1) { V.push_back( pair<int, int>(i - arr[i], i + arr[i])); } } // Sort the array sprinklers in // ascending order by first element sort(V.begin(), V.end()); // Stores the rightmost range // of a sprinkler int maxRight = 0; // Stores minimum sprinklers // to be turned on int res = 0; int i = 0; // Iterate until maxRight is // less than N while (maxRight < N) { // If i is equal to V.size() // or V[i].first is greater // than maxRight if (i == V.size() || V[i].first > maxRight) { return -1; } // Stores the rightmost boundary // of current sprinkler int currMax = V[i].second; // Iterate until i+1 is less // than V.size() and V[i+1].first // is less than or equal to maxRight while (i + 1 < V.size() && V[i + 1].first <= maxRight) { // Increment i by 1 i++; // Update currMax currMax = max(currMax, V[i].second); } // If currMax is less than the maxRight if (currMax < maxRight) { // Return -1 return -1; } // Increment res by 1 res++; // Update maxRight maxRight = currMax + 1; // Increment i by 1 i++; } // Return res as answer return res;} // Drive code.int main(){ // Input int arr[] = { -1, 2, 2, -1, 0, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << minSprinklers(arr, N);}",
"e": 4806,
"s": 2876,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class pair { int x; int y; pair(int x1, int y1) { x = x1; y = y1; }} class GFG { // Function to find minimum number of // sprinkler to be turned on static int minSprinklers(int arr[], int N) { // Stores the leftmost and rightmost // point of every sprinklers ArrayList<pair> V = new ArrayList<pair>(); // Traverse the array arr[] for (int i = 0; i < N; i++) { if (arr[i] > -1) { V.add(new pair(i - arr[i], i + arr[i])); } } // Sort the array sprinklers in // ascending order by first element Collections.sort(V, new Comparator<pair>() { @Override public int compare(pair p1, pair p2) { return p1.x - p2.x; } }); // Stores the rightmost range // of a sprinkler int maxRight = 0; // Stores minimum sprinklers // to be turned on int res = 0; int i = 0; // Iterate until maxRight is // less than N while (maxRight < N) { // If i is equal to V.size() // or V[i].first is greater // than maxRight if (i == V.size() || V.get(i).x > maxRight) { return -1; } // Stores the rightmost boundary // of current sprinkler int currMax = V.get(i).y; // Iterate until i+1 is less // than V.size() and V[i+1].first // is less than or equal to maxRight while (i + 1 < V.size() && V.get(i + 1).x <= maxRight) { // Increment i by 1 i++; // Update currMax currMax = Math.max(currMax, V.get(i).y); } // If currMax is less than the maxRight if (currMax < maxRight) { // Return -1 return -1; } // Increment res by 1 res++; // Update maxRight maxRight = currMax + 1; // Increment i by 1 i++; } // Return res as answer return res; } // Driver code public static void main(String[] args) { int arr[] = { -1, 2, 2, -1, 0, 0 }; int N = 6; // Function call System.out.println(minSprinklers(arr, N)); }} // This code is contributed by Manu Pathria",
"e": 7311,
"s": 4806,
"text": null
},
{
"code": "# Python program for the above approach # Function to find minimum number of# sprinkler to be turned on def minSprinklers(arr, N): # Stores the leftmost and rightmost # point of every sprinklers V = [] # Traverse the array arr[] for i in range(N): if (arr[i] > -1): V.append([i - arr[i], i + arr[i]]) # Sort the array sprinklers in # ascending order by first element V.sort() # Stores the rightmost range # of a sprinkler maxRight = 0 # Stores minimum sprinklers # to be turned on res = 0 i = 0 # Iterate until maxRight is # less than N while (maxRight < N): # If i is equal to V.size() # or V[i][0] is greater # than maxRight if (i == len(V) or V[i][0] > maxRight): return -1 # Stores the rightmost boundary # of current sprinkler currMax = V[i][1] # Iterate until i+1 is less # than V.size() and V[i+1][0] # is less than or equal to maxRight while (i + 1 < len(V) and V[i + 1][0] <= maxRight): # Increment i by 1 i += 1 # Update currMax currMax = max(currMax, V[i][1]) # If currMax is less than the maxRight if (currMax < maxRight): # Return -1 return -1 # Increment res by 1 res += 1 # Update maxRight maxRight = currMax + 1 # Increment i by 1 i += 1 # Return res as answer return res # Drive code. # Inputarr = [-1, 2, 2, -1, 0, 0]N = len(arr) # Function callprint(minSprinklers(arr, N)) # This code is contributed by _saurabh_jaiswal.",
"e": 8957,
"s": 7311,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find minimum number of// sprinkler to be turned onfunction minSprinklers(arr, N) { // Stores the leftmost and rightmost // point of every sprinklers let V = []; // Traverse the array arr[] for (let i = 0; i < N; i++) { if (arr[i] > -1) { V.push([i - arr[i], i + arr[i]]); } } // Sort the array sprinklers in // ascending order by first element V.sort((a, b) => a - b); // Stores the rightmost range // of a sprinkler let maxRight = 0; // Stores minimum sprinklers // to be turned on let res = 0; let i = 0; // Iterate until maxRight is // less than N while (maxRight < N) { // If i is equal to V.size() // or V[i][0] is greater // than maxRight if (i == V.length || V[i][0] > maxRight) { return -1; } // Stores the rightmost boundary // of current sprinkler let currMax = V[i][1]; // Iterate until i+1 is less // than V.size() and V[i+1][0] // is less than or equal to maxRight while (i + 1 < V.length && V[i + 1][0] <= maxRight) { // Increment i by 1 i++; // Update currMax currMax = Math.max(currMax, V[i][1]); } // If currMax is less than the maxRight if (currMax < maxRight) { // Return -1 return -1; } // Increment res by 1 res++; // Update maxRight maxRight = currMax + 1; // Increment i by 1 i++; } // Return res as answer return res;} // Drive code. // Inputlet arr = [-1, 2, 2, -1, 0, 0];let N = arr.length; // Function calldocument.write(minSprinklers(arr, N)); </script>",
"e": 10752,
"s": 8957,
"text": null
},
{
"code": null,
"e": 10754,
"s": 10752,
"text": "2"
},
{
"code": null,
"e": 10809,
"s": 10756,
"text": " Time Complexity: O(N * log(N))Auxiliary Space: O(N)"
},
{
"code": null,
"e": 10821,
"s": 10809,
"text": "manupathria"
},
{
"code": null,
"e": 10831,
"s": 10821,
"text": "sankcan55"
},
{
"code": null,
"e": 10839,
"s": 10831,
"text": "gfgking"
},
{
"code": null,
"e": 10856,
"s": 10839,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 10870,
"s": 10856,
"text": "abhinavroygfg"
},
{
"code": null,
"e": 10884,
"s": 10870,
"text": "nikhil__yadav"
},
{
"code": null,
"e": 10891,
"s": 10884,
"text": "Amazon"
},
{
"code": null,
"e": 10900,
"s": 10891,
"text": "Flipkart"
},
{
"code": null,
"e": 10922,
"s": 10900,
"text": "interview-preparation"
},
{
"code": null,
"e": 10929,
"s": 10922,
"text": "Arrays"
},
{
"code": null,
"e": 10942,
"s": 10929,
"text": "Mathematical"
},
{
"code": null,
"e": 10950,
"s": 10942,
"text": "Sorting"
},
{
"code": null,
"e": 10959,
"s": 10950,
"text": "Flipkart"
},
{
"code": null,
"e": 10966,
"s": 10959,
"text": "Amazon"
},
{
"code": null,
"e": 10973,
"s": 10966,
"text": "Arrays"
},
{
"code": null,
"e": 10986,
"s": 10973,
"text": "Mathematical"
},
{
"code": null,
"e": 10994,
"s": 10986,
"text": "Sorting"
},
{
"code": null,
"e": 11092,
"s": 10994,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11160,
"s": 11092,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 11204,
"s": 11160,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 11236,
"s": 11204,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 11284,
"s": 11236,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 11298,
"s": 11284,
"text": "Linear Search"
},
{
"code": null,
"e": 11328,
"s": 11298,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 11371,
"s": 11328,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 11431,
"s": 11371,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 11446,
"s": 11431,
"text": "C++ Data Types"
}
] |
JavaFX | Background Class
|
04 Sep, 2018
Background class is a part of JavaFX. Background class sets the background of a region. Every background is composed of several fills or background images but cannot be null but it may be empty. Background class is immutable, so you can freely reuse the same Background on many different Regions.
Constructors of the class:
Background(BackgroundFill... f): Creates a new background object with specified fills.Background(BackgroundFill[] fills, BackgroundImage[] images): Creates a new background object with specified fills and background image.Background(BackgroundImage... i): Creates a new background object with specified background images.Background(List fills, List images): Creates a new background object with list of specified fills and background images.
Background(BackgroundFill... f): Creates a new background object with specified fills.
Background(BackgroundFill[] fills, BackgroundImage[] images): Creates a new background object with specified fills and background image.
Background(BackgroundImage... i): Creates a new background object with specified background images.
Background(List fills, List images): Creates a new background object with list of specified fills and background images.
Commonly Used Methods:
Below programs illustrate the use of Background class:
Java program to set a fill for the background of a container: In this program we will create a Background named background with specified BackgroundFill and add this to the background. We will create an HBox named hbox, a Label named label, TextField named textfield and a Button named button . Now add the label, textfield and button to the HBox. We will set the background of hbox using the setBackground() function.Now set the alignment of HBox to Pos.CENTER and also add some spacing between the nodes using setSpacing() method. We will create a Scene named scene and add the HBox to the scene. The scene will be set to the stage using the setScene() function. We will call the show() function to display the results.// Java program to set a fill for the background // of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group;import javafx.scene.paint.*; public class Background_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("creating Background"); // create a label Label label = new Label("Name : "); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button("OK"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a background fill BackgroundFill background_fill = new BackgroundFill(Color.PINK, CornerRadii.EMPTY, Insets.EMPTY); // create Background Background background = new Background(background_fill); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java program to add an image to the background of a container: In this program we will create a Background named background with specified BackgroundImage and add this image to the background of the container. Import the image using the FileInputStream and then convert the file into Image object Use this Image object to create a BackgroundImage. We will create an HBox named hbox, a Label named label, TextField named textfield and a Button named button . Now add the label, textfield, and button to the HBox. Set the background of the hbox using the setBackground() function. Set the alignment of HBox to Pos.CENTER and also add some spacing between the nodes using setSpacing() method. We will create a Scene named scene and add the HBox to the scene. The scene will be set to the stage using the setScene() function. Finally call the show() method to display the result.// Java program to add an image to // the background of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group; public class Background_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("creating Background"); // create a label Label label = new Label("Name : "); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button("OK"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a input stream FileInputStream input = new FileInputStream("f:\\gfg.png"); // create a image Image image = new Image(input); // create a background image BackgroundImage backgroundimage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT); // create Background Background background = new Background(backgroundimage); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
Java program to set a fill for the background of a container: In this program we will create a Background named background with specified BackgroundFill and add this to the background. We will create an HBox named hbox, a Label named label, TextField named textfield and a Button named button . Now add the label, textfield and button to the HBox. We will set the background of hbox using the setBackground() function.Now set the alignment of HBox to Pos.CENTER and also add some spacing between the nodes using setSpacing() method. We will create a Scene named scene and add the HBox to the scene. The scene will be set to the stage using the setScene() function. We will call the show() function to display the results.// Java program to set a fill for the background // of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group;import javafx.scene.paint.*; public class Background_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("creating Background"); // create a label Label label = new Label("Name : "); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button("OK"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a background fill BackgroundFill background_fill = new BackgroundFill(Color.PINK, CornerRadii.EMPTY, Insets.EMPTY); // create Background Background background = new Background(background_fill); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java program to set a fill for the background // of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group;import javafx.scene.paint.*; public class Background_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("creating Background"); // create a label Label label = new Label("Name : "); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button("OK"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a background fill BackgroundFill background_fill = new BackgroundFill(Color.PINK, CornerRadii.EMPTY, Insets.EMPTY); // create Background Background background = new Background(background_fill); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java program to add an image to the background of a container: In this program we will create a Background named background with specified BackgroundImage and add this image to the background of the container. Import the image using the FileInputStream and then convert the file into Image object Use this Image object to create a BackgroundImage. We will create an HBox named hbox, a Label named label, TextField named textfield and a Button named button . Now add the label, textfield, and button to the HBox. Set the background of the hbox using the setBackground() function. Set the alignment of HBox to Pos.CENTER and also add some spacing between the nodes using setSpacing() method. We will create a Scene named scene and add the HBox to the scene. The scene will be set to the stage using the setScene() function. Finally call the show() method to display the result.// Java program to add an image to // the background of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group; public class Background_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("creating Background"); // create a label Label label = new Label("Name : "); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button("OK"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a input stream FileInputStream input = new FileInputStream("f:\\gfg.png"); // create a image Image image = new Image(input); // create a background image BackgroundImage backgroundimage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT); // create Background Background background = new Background(backgroundimage); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java program to add an image to // the background of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group; public class Background_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("creating Background"); // create a label Label label = new Label("Name : "); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button("OK"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a input stream FileInputStream input = new FileInputStream("f:\\gfg.png"); // create a image Image image = new Image(input); // create a background image BackgroundImage backgroundimage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT); // create Background Background background = new Background(backgroundimage); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note: The above programs might not run in an online IDE. Please use an offline compiler.
Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Background.html
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Sep, 2018"
},
{
"code": null,
"e": 351,
"s": 54,
"text": "Background class is a part of JavaFX. Background class sets the background of a region. Every background is composed of several fills or background images but cannot be null but it may be empty. Background class is immutable, so you can freely reuse the same Background on many different Regions."
},
{
"code": null,
"e": 378,
"s": 351,
"text": "Constructors of the class:"
},
{
"code": null,
"e": 820,
"s": 378,
"text": "Background(BackgroundFill... f): Creates a new background object with specified fills.Background(BackgroundFill[] fills, BackgroundImage[] images): Creates a new background object with specified fills and background image.Background(BackgroundImage... i): Creates a new background object with specified background images.Background(List fills, List images): Creates a new background object with list of specified fills and background images."
},
{
"code": null,
"e": 907,
"s": 820,
"text": "Background(BackgroundFill... f): Creates a new background object with specified fills."
},
{
"code": null,
"e": 1044,
"s": 907,
"text": "Background(BackgroundFill[] fills, BackgroundImage[] images): Creates a new background object with specified fills and background image."
},
{
"code": null,
"e": 1144,
"s": 1044,
"text": "Background(BackgroundImage... i): Creates a new background object with specified background images."
},
{
"code": null,
"e": 1265,
"s": 1144,
"text": "Background(List fills, List images): Creates a new background object with list of specified fills and background images."
},
{
"code": null,
"e": 1288,
"s": 1265,
"text": "Commonly Used Methods:"
},
{
"code": null,
"e": 1343,
"s": 1288,
"text": "Below programs illustrate the use of Background class:"
},
{
"code": null,
"e": 7468,
"s": 1343,
"text": "Java program to set a fill for the background of a container: In this program we will create a Background named background with specified BackgroundFill and add this to the background. We will create an HBox named hbox, a Label named label, TextField named textfield and a Button named button . Now add the label, textfield and button to the HBox. We will set the background of hbox using the setBackground() function.Now set the alignment of HBox to Pos.CENTER and also add some spacing between the nodes using setSpacing() method. We will create a Scene named scene and add the HBox to the scene. The scene will be set to the stage using the setScene() function. We will call the show() function to display the results.// Java program to set a fill for the background // of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group;import javafx.scene.paint.*; public class Background_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"creating Background\"); // create a label Label label = new Label(\"Name : \"); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button(\"OK\"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a background fill BackgroundFill background_fill = new BackgroundFill(Color.PINK, CornerRadii.EMPTY, Insets.EMPTY); // create Background Background background = new Background(background_fill); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java program to add an image to the background of a container: In this program we will create a Background named background with specified BackgroundImage and add this image to the background of the container. Import the image using the FileInputStream and then convert the file into Image object Use this Image object to create a BackgroundImage. We will create an HBox named hbox, a Label named label, TextField named textfield and a Button named button . Now add the label, textfield, and button to the HBox. Set the background of the hbox using the setBackground() function. Set the alignment of HBox to Pos.CENTER and also add some spacing between the nodes using setSpacing() method. We will create a Scene named scene and add the HBox to the scene. The scene will be set to the stage using the setScene() function. Finally call the show() method to display the result.// Java program to add an image to // the background of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group; public class Background_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"creating Background\"); // create a label Label label = new Label(\"Name : \"); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button(\"OK\"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a input stream FileInputStream input = new FileInputStream(\"f:\\\\gfg.png\"); // create a image Image image = new Image(input); // create a background image BackgroundImage backgroundimage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT); // create Background Background background = new Background(backgroundimage); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": null,
"e": 10269,
"s": 7468,
"text": "Java program to set a fill for the background of a container: In this program we will create a Background named background with specified BackgroundFill and add this to the background. We will create an HBox named hbox, a Label named label, TextField named textfield and a Button named button . Now add the label, textfield and button to the HBox. We will set the background of hbox using the setBackground() function.Now set the alignment of HBox to Pos.CENTER and also add some spacing between the nodes using setSpacing() method. We will create a Scene named scene and add the HBox to the scene. The scene will be set to the stage using the setScene() function. We will call the show() function to display the results.// Java program to set a fill for the background // of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group;import javafx.scene.paint.*; public class Background_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"creating Background\"); // create a label Label label = new Label(\"Name : \"); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button(\"OK\"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a background fill BackgroundFill background_fill = new BackgroundFill(Color.PINK, CornerRadii.EMPTY, Insets.EMPTY); // create Background Background background = new Background(background_fill); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java program to set a fill for the background // of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group;import javafx.scene.paint.*; public class Background_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"creating Background\"); // create a label Label label = new Label(\"Name : \"); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button(\"OK\"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a background fill BackgroundFill background_fill = new BackgroundFill(Color.PINK, CornerRadii.EMPTY, Insets.EMPTY); // create Background Background background = new Background(background_fill); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 12342,
"s": 10269,
"text": null
},
{
"code": null,
"e": 12350,
"s": 12342,
"text": "Output:"
},
{
"code": null,
"e": 15675,
"s": 12350,
"text": "Java program to add an image to the background of a container: In this program we will create a Background named background with specified BackgroundImage and add this image to the background of the container. Import the image using the FileInputStream and then convert the file into Image object Use this Image object to create a BackgroundImage. We will create an HBox named hbox, a Label named label, TextField named textfield and a Button named button . Now add the label, textfield, and button to the HBox. Set the background of the hbox using the setBackground() function. Set the alignment of HBox to Pos.CENTER and also add some spacing between the nodes using setSpacing() method. We will create a Scene named scene and add the HBox to the scene. The scene will be set to the stage using the setScene() function. Finally call the show() method to display the result.// Java program to add an image to // the background of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group; public class Background_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"creating Background\"); // create a label Label label = new Label(\"Name : \"); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button(\"OK\"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a input stream FileInputStream input = new FileInputStream(\"f:\\\\gfg.png\"); // create a image Image image = new Image(input); // create a background image BackgroundImage backgroundimage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT); // create Background Background background = new Background(backgroundimage); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java program to add an image to // the background of a containerimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.image.*;import java.io.*;import javafx.geometry.*;import javafx.scene.Group; public class Background_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"creating Background\"); // create a label Label label = new Label(\"Name : \"); // create a text field TextField textfield = new TextField(); // set preferred column count textfield.setPrefColumnCount(10); // create a button Button button = new Button(\"OK\"); // add the label, text field and button HBox hbox = new HBox(label, textfield, button); // set spacing hbox.setSpacing(10); // set alignment for the HBox hbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(hbox, 280, 280); // create a input stream FileInputStream input = new FileInputStream(\"f:\\\\gfg.png\"); // create a image Image image = new Image(input); // create a background image BackgroundImage backgroundimage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT); // create Background Background background = new Background(backgroundimage); // set background hbox.setBackground(background); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 18118,
"s": 15675,
"text": null
},
{
"code": null,
"e": 18126,
"s": 18118,
"text": "Output:"
},
{
"code": null,
"e": 18215,
"s": 18126,
"text": "Note: The above programs might not run in an online IDE. Please use an offline compiler."
},
{
"code": null,
"e": 18306,
"s": 18215,
"text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Background.html"
},
{
"code": null,
"e": 18313,
"s": 18306,
"text": "JavaFX"
},
{
"code": null,
"e": 18318,
"s": 18313,
"text": "Java"
},
{
"code": null,
"e": 18323,
"s": 18318,
"text": "Java"
},
{
"code": null,
"e": 18421,
"s": 18323,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18472,
"s": 18421,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 18503,
"s": 18472,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 18522,
"s": 18503,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 18552,
"s": 18522,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 18572,
"s": 18552,
"text": "Collections in Java"
},
{
"code": null,
"e": 18587,
"s": 18572,
"text": "Stream In Java"
},
{
"code": null,
"e": 18619,
"s": 18587,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 18643,
"s": 18619,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 18655,
"s": 18643,
"text": "Set in Java"
}
] |
Differences between ArrayList and Vector in Java
|
Both ArrayList and Vector are implementation of List interface in Java. Both classes keeps the insertion order. But there are certain differences as well.
Following are the important differences between ArrayList and Vector method.
import java.util.ArrayList;
import java.util.Vector;
import java.util.List;
public class JavaTester {
public static void main(String args[]) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
List<String> list1 = new Vector<>();
list1.add("A");
list1.add("B");
list1.add("C");
list1.add("D");
System.out.println(list);
System.out.println(list1);
}
}
[A, B, C, D]
[A, B, C, D]
|
[
{
"code": null,
"e": 1342,
"s": 1187,
"text": "Both ArrayList and Vector are implementation of List interface in Java. Both classes keeps the insertion order. But there are certain differences as well."
},
{
"code": null,
"e": 1419,
"s": 1342,
"text": "Following are the important differences between ArrayList and Vector method."
},
{
"code": null,
"e": 1897,
"s": 1419,
"text": "import java.util.ArrayList;\nimport java.util.Vector;\nimport java.util.List;\npublic class JavaTester {\n public static void main(String args[]) {\n List<String> list = new ArrayList<>();\n list.add(\"A\");\n list.add(\"B\");\n list.add(\"C\");\n list.add(\"D\");\n List<String> list1 = new Vector<>();\n list1.add(\"A\");\n list1.add(\"B\");\n list1.add(\"C\");\n list1.add(\"D\");\n System.out.println(list);\n System.out.println(list1);\n }\n}"
},
{
"code": null,
"e": 1923,
"s": 1897,
"text": "[A, B, C, D]\n[A, B, C, D]"
}
] |
How to remove timezone information from DateTime object in Python
|
09 Dec, 2021
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone.
In this article, we will discuss how to remove timezone information from the DateTime object.
datetime.now(tz=None): Returns the current local date and time.
datetime.replace(): Returns a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.
To remove timestamp, tzinfo has to be set None when calling replace() function.
First, create a DateTime object with current time using datetime.now(). The DateTime object was then modified to contain the timezone information as well using the timezone.utc. The DateTime object with timezone information is then manipulated using the .replace() method to remove the timezone information using the tzinfo parameter.
Syntax:
replace(tzinfo=None)
Example:
Python
from datetime import datetime, timezone # Get the datetime object using datetime# moduledt_obj_w_tz = datetime.now()print(dt_obj_w_tz) # Add timezone information to the datetime# objectdt_obj_w_tz = dt_obj_w_tz.replace(tzinfo=timezone.utc)print(dt_obj_w_tz) # Remove the timezone information from the datetime# objectdt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)print(dt_obj_wo_tz)
Output:
2021-08-10 12:51:42.093388
2021-08-10 12:51:42.093388+00:00
2021-08-10 12:51:42.09338
However, the datetime object with timestamp can be created by providing tz parameter.
Example:
Python
from datetime import datetime, timezone # Get the datetime object with timezone# informationdt_obj_w_tz = datetime.now(tz=timezone.utc)print(dt_obj_w_tz) # Remove the timezone information from the# datetime objectdt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)print(dt_obj_wo_tz)
Output:
2021-08-10 07:21:57.838856+00:00
2021-08-10 07:21:57.838856
surindertarika1234
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 296,
"s": 28,
"text": "Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone."
},
{
"code": null,
"e": 390,
"s": 296,
"text": "In this article, we will discuss how to remove timezone information from the DateTime object."
},
{
"code": null,
"e": 454,
"s": 390,
"text": "datetime.now(tz=None): Returns the current local date and time."
},
{
"code": null,
"e": 610,
"s": 454,
"text": "datetime.replace(): Returns a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified."
},
{
"code": null,
"e": 690,
"s": 610,
"text": "To remove timestamp, tzinfo has to be set None when calling replace() function."
},
{
"code": null,
"e": 1025,
"s": 690,
"text": "First, create a DateTime object with current time using datetime.now(). The DateTime object was then modified to contain the timezone information as well using the timezone.utc. The DateTime object with timezone information is then manipulated using the .replace() method to remove the timezone information using the tzinfo parameter."
},
{
"code": null,
"e": 1033,
"s": 1025,
"text": "Syntax:"
},
{
"code": null,
"e": 1054,
"s": 1033,
"text": "replace(tzinfo=None)"
},
{
"code": null,
"e": 1063,
"s": 1054,
"text": "Example:"
},
{
"code": null,
"e": 1070,
"s": 1063,
"text": "Python"
},
{
"code": "from datetime import datetime, timezone # Get the datetime object using datetime# moduledt_obj_w_tz = datetime.now()print(dt_obj_w_tz) # Add timezone information to the datetime# objectdt_obj_w_tz = dt_obj_w_tz.replace(tzinfo=timezone.utc)print(dt_obj_w_tz) # Remove the timezone information from the datetime# objectdt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)print(dt_obj_wo_tz)",
"e": 1454,
"s": 1070,
"text": null
},
{
"code": null,
"e": 1463,
"s": 1454,
"text": "Output: "
},
{
"code": null,
"e": 1549,
"s": 1463,
"text": "2021-08-10 12:51:42.093388\n2021-08-10 12:51:42.093388+00:00\n2021-08-10 12:51:42.09338"
},
{
"code": null,
"e": 1635,
"s": 1549,
"text": "However, the datetime object with timestamp can be created by providing tz parameter."
},
{
"code": null,
"e": 1644,
"s": 1635,
"text": "Example:"
},
{
"code": null,
"e": 1651,
"s": 1644,
"text": "Python"
},
{
"code": "from datetime import datetime, timezone # Get the datetime object with timezone# informationdt_obj_w_tz = datetime.now(tz=timezone.utc)print(dt_obj_w_tz) # Remove the timezone information from the# datetime objectdt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)print(dt_obj_wo_tz)",
"e": 1931,
"s": 1651,
"text": null
},
{
"code": null,
"e": 1939,
"s": 1931,
"text": "Output:"
},
{
"code": null,
"e": 1999,
"s": 1939,
"text": "2021-08-10 07:21:57.838856+00:00\n2021-08-10 07:21:57.838856"
},
{
"code": null,
"e": 2018,
"s": 1999,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2025,
"s": 2018,
"text": "Picked"
},
{
"code": null,
"e": 2041,
"s": 2025,
"text": "Python-datetime"
},
{
"code": null,
"e": 2048,
"s": 2041,
"text": "Python"
}
] |
Program to count vowels, consonant, digits and special characters in string.
|
08 Mar, 2022
Given a string and the task is to count vowels, consonant, digits and special character in string. Special character also contains the white space.Examples:
Input : str = "geeks for geeks121"
Output : Vowels: 5
Consonant: 8
Digit: 3
Special Character: 2
Input : str = " A1 B@ d adc"
Output : Vowels: 2
Consonant: 4
Digit: 1
Special Character: 6
C++
Java
Python3
C#
Javascript
// Program to count vowels, consonant, digits and// special character in a given string.#include <bits/stdc++.h>using namespace std; // Function to count number of vowels, consonant, // digitsand special character in a string.void countCharacterType(string str){ // Declare the variable vowels, consonant, digit // and special characters int vowels = 0, consonant = 0, specialChar = 0, digit = 0; // str.length() function to count number of // character in given string. for (int i = 0; i < str.length(); i++) { char ch = str[i]; if ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ) { // To handle upper case letters ch = tolower(ch); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels++; else consonant++; } else if (ch >= '0' && ch <= '9') digit++; else specialChar++; } cout << "Vowels: " << vowels << endl; cout << "Consonant: " << consonant << endl; cout << "Digit: " << digit << endl; cout << "Special Character: " << specialChar << endl;} // Driver function.int main(){ string str = "geeks for geeks121"; countCharacterType(str); return 0;}
// Java Program to count vowels, consonant, digits and// special character in a given stringimport java.io.*; public class GFG { // Function to count number of vowels, consonant, // digitsand special character in a string. static void countCharacterType(String str) { // Declare the variable vowels, consonant, digit // and special characters int vowels = 0, consonant = 0, specialChar = 0, digit = 0; // str.length() function to count number of // character in given string. for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ) { // To handle upper case letters ch = Character.toLowerCase(ch); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels++; else consonant++; } else if (ch >= '0' && ch <= '9') digit++; else specialChar++; } System.out.println("Vowels: " + vowels); System.out.println("Consonant: " + consonant); System.out.println("Digit: " + digit); System.out.println("Special Character: " + specialChar); } // Driver function. static public void main (String[] args) { String str = "geeks for geeks121"; countCharacterType(str); }} // This code is contributed by vt_m.
# Python3 Program to count vowels,# consonant, digits and special# character in a given string. # Function to count number of vowels,# consonant, digits and special# character in a string.def countCharacterType(str): # Declare the variable vowels, # consonant, digit and special # characters vowels = 0 consonant = 0 specialChar = 0 digit = 0 # str.length() function to count # number of character in given string. for i in range(0, len(str)): ch = str[i] if ( (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') ): # To handle upper case letters ch = ch.lower() if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): vowels += 1 else: consonant += 1 elif (ch >= '0' and ch <= '9'): digit += 1 else: specialChar += 1 print("Vowels:", vowels) print("Consonant:", consonant) print("Digit:", digit) print("Special Character:", specialChar) # Driver function.str = "geeks for geeks121"countCharacterType(str) # This code is contributed by# Smitha Dinesh Semwal
// Program to count vowels, consonant,// digits and special character in// a given stringusing System;using System.Globalization; class GFG { // Function to count number of // vowels, consonant, digitsand // special character in a string. static void countCharacterType(string str) { // Declare the variable vowels, consonant, // digit and special characters int vowels = 0, consonant = 0, specialChar = 0, digit = 0; // str.length() function to count number of // character in given string. for (int i = 0; i < str.Length; i++) { char ch = str[i]; if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { // To handle upper case letters ch = char.ToLower(ch); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels++; else consonant++; } else if (ch >= '0' && ch <= '9') digit++; else specialChar++; } Console.WriteLine("Vowels: " + vowels); Console.WriteLine("Consonant: " + consonant); Console.WriteLine("Digit: " + digit); Console.WriteLine("Special Character: " + specialChar); } // Driver function. static public void Main() { string str = "geeks for geeks121"; countCharacterType(str); }} // This code is contributed by vt_m.
<script> // Program to count vowels, consonant, // digits and // special character in a given string. // Function to count number of vowels, consonant, // digitsand special character in a string. function countCharacterType(str) { // Declare the variable vowels, // consonant, digit // and special characters var vowels = 0, consonant = 0, specialChar = 0, digit = 0; // str.length() function to count number of // character in given string. for (var i = 0; i < str.length; i++) { var ch = str[i]; if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z")) { // To handle upper case letters ch = ch.toLowerCase(); if (ch == "a" || ch == "e" || ch == "i" || ch == "o" || ch == "u") vowels++; else consonant++; } else if (ch >= "0" && ch <= "9") digit++; else specialChar++; } document.write("Vowels: " + vowels + "<br>"); document.write("Consonant: " + consonant + "<br>"); document.write("Digit: " + digit + "<br>"); document.write("Special Character: " + specialChar + "<br>"); } // Driver function. var str = "geeks for geeks121"; countCharacterType(str); </script>
Output:
Vowels: 5
Consonant: 8
Digit: 3
Special Character: 2
Time Complexity: O(N)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Auxiliary Space: O(1)
Program to count vowels, consonant, digits and special characters in string | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersProgram to count vowels, consonant, digits and special characters in string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=2302sAlMZ8g" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
rdtank
sandiptosen001
rohitsingh07052
CBSE - Class 11
school-programming
vowel-consonant
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 212,
"s": 53,
"text": "Given a string and the task is to count vowels, consonant, digits and special character in string. Special character also contains the white space.Examples: "
},
{
"code": null,
"e": 456,
"s": 212,
"text": "Input : str = \"geeks for geeks121\"\nOutput : Vowels: 5\n Consonant: 8\n Digit: 3\n Special Character: 2\n\nInput : str = \" A1 B@ d adc\"\nOutput : Vowels: 2\n Consonant: 4\n Digit: 1\n Special Character: 6"
},
{
"code": null,
"e": 464,
"s": 460,
"text": "C++"
},
{
"code": null,
"e": 469,
"s": 464,
"text": "Java"
},
{
"code": null,
"e": 477,
"s": 469,
"text": "Python3"
},
{
"code": null,
"e": 480,
"s": 477,
"text": "C#"
},
{
"code": null,
"e": 491,
"s": 480,
"text": "Javascript"
},
{
"code": "// Program to count vowels, consonant, digits and// special character in a given string.#include <bits/stdc++.h>using namespace std; // Function to count number of vowels, consonant, // digitsand special character in a string.void countCharacterType(string str){ // Declare the variable vowels, consonant, digit // and special characters int vowels = 0, consonant = 0, specialChar = 0, digit = 0; // str.length() function to count number of // character in given string. for (int i = 0; i < str.length(); i++) { char ch = str[i]; if ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ) { // To handle upper case letters ch = tolower(ch); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels++; else consonant++; } else if (ch >= '0' && ch <= '9') digit++; else specialChar++; } cout << \"Vowels: \" << vowels << endl; cout << \"Consonant: \" << consonant << endl; cout << \"Digit: \" << digit << endl; cout << \"Special Character: \" << specialChar << endl;} // Driver function.int main(){ string str = \"geeks for geeks121\"; countCharacterType(str); return 0;}",
"e": 1791,
"s": 491,
"text": null
},
{
"code": "// Java Program to count vowels, consonant, digits and// special character in a given stringimport java.io.*; public class GFG { // Function to count number of vowels, consonant, // digitsand special character in a string. static void countCharacterType(String str) { // Declare the variable vowels, consonant, digit // and special characters int vowels = 0, consonant = 0, specialChar = 0, digit = 0; // str.length() function to count number of // character in given string. for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ) { // To handle upper case letters ch = Character.toLowerCase(ch); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels++; else consonant++; } else if (ch >= '0' && ch <= '9') digit++; else specialChar++; } System.out.println(\"Vowels: \" + vowels); System.out.println(\"Consonant: \" + consonant); System.out.println(\"Digit: \" + digit); System.out.println(\"Special Character: \" + specialChar); } // Driver function. static public void main (String[] args) { String str = \"geeks for geeks121\"; countCharacterType(str); }} // This code is contributed by vt_m.",
"e": 3371,
"s": 1791,
"text": null
},
{
"code": "# Python3 Program to count vowels,# consonant, digits and special# character in a given string. # Function to count number of vowels,# consonant, digits and special# character in a string.def countCharacterType(str): # Declare the variable vowels, # consonant, digit and special # characters vowels = 0 consonant = 0 specialChar = 0 digit = 0 # str.length() function to count # number of character in given string. for i in range(0, len(str)): ch = str[i] if ( (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') ): # To handle upper case letters ch = ch.lower() if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): vowels += 1 else: consonant += 1 elif (ch >= '0' and ch <= '9'): digit += 1 else: specialChar += 1 print(\"Vowels:\", vowels) print(\"Consonant:\", consonant) print(\"Digit:\", digit) print(\"Special Character:\", specialChar) # Driver function.str = \"geeks for geeks121\"countCharacterType(str) # This code is contributed by# Smitha Dinesh Semwal",
"e": 4574,
"s": 3371,
"text": null
},
{
"code": "// Program to count vowels, consonant,// digits and special character in// a given stringusing System;using System.Globalization; class GFG { // Function to count number of // vowels, consonant, digitsand // special character in a string. static void countCharacterType(string str) { // Declare the variable vowels, consonant, // digit and special characters int vowels = 0, consonant = 0, specialChar = 0, digit = 0; // str.length() function to count number of // character in given string. for (int i = 0; i < str.Length; i++) { char ch = str[i]; if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { // To handle upper case letters ch = char.ToLower(ch); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels++; else consonant++; } else if (ch >= '0' && ch <= '9') digit++; else specialChar++; } Console.WriteLine(\"Vowels: \" + vowels); Console.WriteLine(\"Consonant: \" + consonant); Console.WriteLine(\"Digit: \" + digit); Console.WriteLine(\"Special Character: \" + specialChar); } // Driver function. static public void Main() { string str = \"geeks for geeks121\"; countCharacterType(str); }} // This code is contributed by vt_m.",
"e": 6081,
"s": 4574,
"text": null
},
{
"code": "<script> // Program to count vowels, consonant, // digits and // special character in a given string. // Function to count number of vowels, consonant, // digitsand special character in a string. function countCharacterType(str) { // Declare the variable vowels, // consonant, digit // and special characters var vowels = 0, consonant = 0, specialChar = 0, digit = 0; // str.length() function to count number of // character in given string. for (var i = 0; i < str.length; i++) { var ch = str[i]; if ((ch >= \"a\" && ch <= \"z\") || (ch >= \"A\" && ch <= \"Z\")) { // To handle upper case letters ch = ch.toLowerCase(); if (ch == \"a\" || ch == \"e\" || ch == \"i\" || ch == \"o\" || ch == \"u\") vowels++; else consonant++; } else if (ch >= \"0\" && ch <= \"9\") digit++; else specialChar++; } document.write(\"Vowels: \" + vowels + \"<br>\"); document.write(\"Consonant: \" + consonant + \"<br>\"); document.write(\"Digit: \" + digit + \"<br>\"); document.write(\"Special Character: \" + specialChar + \"<br>\"); } // Driver function. var str = \"geeks for geeks121\"; countCharacterType(str); </script>",
"e": 7434,
"s": 6081,
"text": null
},
{
"code": null,
"e": 7443,
"s": 7434,
"text": "Output: "
},
{
"code": null,
"e": 7496,
"s": 7443,
"text": "Vowels: 5\nConsonant: 8\nDigit: 3\nSpecial Character: 2"
},
{
"code": null,
"e": 7518,
"s": 7496,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 7527,
"s": 7518,
"text": "Chapters"
},
{
"code": null,
"e": 7554,
"s": 7527,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 7604,
"s": 7554,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 7627,
"s": 7604,
"text": "captions off, selected"
},
{
"code": null,
"e": 7635,
"s": 7627,
"text": "English"
},
{
"code": null,
"e": 7659,
"s": 7635,
"text": "This is a modal window."
},
{
"code": null,
"e": 7728,
"s": 7659,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 7750,
"s": 7728,
"text": "End of dialog window."
},
{
"code": null,
"e": 7773,
"s": 7750,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 8741,
"s": 7773,
"text": "Program to count vowels, consonant, digits and special characters in string | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersProgram to count vowels, consonant, digits and special characters in string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:07•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=2302sAlMZ8g\" 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": 8750,
"s": 8743,
"text": "rdtank"
},
{
"code": null,
"e": 8765,
"s": 8750,
"text": "sandiptosen001"
},
{
"code": null,
"e": 8781,
"s": 8765,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 8797,
"s": 8781,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 8816,
"s": 8797,
"text": "school-programming"
},
{
"code": null,
"e": 8832,
"s": 8816,
"text": "vowel-consonant"
},
{
"code": null,
"e": 8851,
"s": 8832,
"text": "School Programming"
},
{
"code": null,
"e": 8859,
"s": 8851,
"text": "Strings"
},
{
"code": null,
"e": 8867,
"s": 8859,
"text": "Strings"
}
] |
How to Combine Multiple Base Images Using Single Dockerfile?
|
23 Oct, 2020
If you are working on a large micro-service project using Docker Containers, the development cycle consists of some phases. Now, maintaining different dockerfiles for different phases of the development uses up lots of resources, leads to redundancy as several project components might contain common files. It really becomes unnecessary to use separate dockerfiles for the build phase, development phase, release phase, and, testing phase.
In later versions of Docker, it provides the use of multi-stage dockerfiles. Using multi-stage dockerfiles, you can use several base images as well as previous intermediate image layers to build a new image layer. Basically, it allows you to create a complete hierarchy of Docker instructions that could be used to create different sets of images with different functionalities but all in a single dockerfile. Use of two commands – FROM and AS, in particular, allows you to create a multi-stage dockerfile. It allows you to create multiple image layers on top of the previous layers and the AS command provides a virtual name to the intermediate image layer. The last FROM command in the dockerfile creates the actual final image.
In this article, we will see an example of a multi-stage dockerfile and how you can use it in your Docker projects.
To begin with, let’s consider the dockerfile below.
#Create the base OS image
FROM python:3 AS base
#Update the OS ubuntu image
RUN apt-get -y update
#Install packages
RUN apt-get -y install firefox \
&& apt-get -y install vim
#Create another image layer on top of base to install requirements
FROM base AS requirements
#Install the requirements
RUN pip3 install -r requirements.txt
#Create an intermediate image layer for testing purpose
FROM requirements as test
#Create the build context
COPY /usr/src/my-app /desktop/my-app
#Test the final app
CMD ["python3", "index.py"]
Let’s go through the above dockerfile step by step.
First, we have pulled the python 3 base images directly from the Docker registry. It also sets the base image’s OS to be Ubuntu by default. We have used a virtual name called “base” for this image layer.Then, we run an apt update on the Ubuntu OS.After that, we install some basic packages such as Firefox browser and vim text editor.Using the base image, we create another image layer on top of it called “requirements” which installs the dependencies from a separate file called “requirements.txt”.Using this image as the base image, we have created another intermediate image layer called “test” which creates the build context and copies the files and directories, and finally runs the python application for testing.
First, we have pulled the python 3 base images directly from the Docker registry. It also sets the base image’s OS to be Ubuntu by default. We have used a virtual name called “base” for this image layer.
Then, we run an apt update on the Ubuntu OS.
After that, we install some basic packages such as Firefox browser and vim text editor.
Using the base image, we create another image layer on top of it called “requirements” which installs the dependencies from a separate file called “requirements.txt”.
Using this image as the base image, we have created another intermediate image layer called “test” which creates the build context and copies the files and directories, and finally runs the python application for testing.
In the requirements file, we mention the dependencies that we want to install.
flask
pandas
numpy
The main file that we want to run and have specified in the dockerfile’s CMD arguments is the index.py file. In the index.py file, we simply include a print statement for demonstration purposes.
print("geeksforgeeks")
To build the Docker Image, we use the Docker Build command.
sudo docker build -t sample-image .
Building the Image
After we have successfully built the Docker Image, we can run the container using the Docker run command.
sudo docker run -it sample-image
Running the Container
We can clearly see how the combination of FROM and AS commands can help us create a unique hierarchy for all our projects or project components. Basically, it allows us to perform inheritance of image components including hierarchical or multiple inheritances based on how you combine those commands.
This proves to be very helpful because it allows you to perform all the tasks using a single dockerfile thus making version management easier, it gives a better overview of the whole project, it reduces the overall size of the final image by eliminating the need to use the same files in the different image since there is only one final image now.
To conclude, in this article we discussed how to use Docker multi-stage builds to use and inherit multiple bases and customize image layers in a single dockerfile.
Docker Container
linux
Advanced Computer Subject
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Getting Started with System Design
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 470,
"s": 28,
"text": "If you are working on a large micro-service project using Docker Containers, the development cycle consists of some phases. Now, maintaining different dockerfiles for different phases of the development uses up lots of resources, leads to redundancy as several project components might contain common files. It really becomes unnecessary to use separate dockerfiles for the build phase, development phase, release phase, and, testing phase. "
},
{
"code": null,
"e": 1201,
"s": 470,
"text": "In later versions of Docker, it provides the use of multi-stage dockerfiles. Using multi-stage dockerfiles, you can use several base images as well as previous intermediate image layers to build a new image layer. Basically, it allows you to create a complete hierarchy of Docker instructions that could be used to create different sets of images with different functionalities but all in a single dockerfile. Use of two commands – FROM and AS, in particular, allows you to create a multi-stage dockerfile. It allows you to create multiple image layers on top of the previous layers and the AS command provides a virtual name to the intermediate image layer. The last FROM command in the dockerfile creates the actual final image."
},
{
"code": null,
"e": 1317,
"s": 1201,
"text": "In this article, we will see an example of a multi-stage dockerfile and how you can use it in your Docker projects."
},
{
"code": null,
"e": 1369,
"s": 1317,
"text": "To begin with, let’s consider the dockerfile below."
},
{
"code": null,
"e": 1902,
"s": 1369,
"text": "#Create the base OS image\nFROM python:3 AS base\n\n#Update the OS ubuntu image\nRUN apt-get -y update\n\n#Install packages\nRUN apt-get -y install firefox \\\n&& apt-get -y install vim\n\n#Create another image layer on top of base to install requirements\nFROM base AS requirements\n\n#Install the requirements\nRUN pip3 install -r requirements.txt\n\n#Create an intermediate image layer for testing purpose\nFROM requirements as test\n\n#Create the build context\nCOPY /usr/src/my-app /desktop/my-app\n\n#Test the final app\nCMD [\"python3\", \"index.py\"]\n\n"
},
{
"code": null,
"e": 1954,
"s": 1902,
"text": "Let’s go through the above dockerfile step by step."
},
{
"code": null,
"e": 2676,
"s": 1954,
"text": "First, we have pulled the python 3 base images directly from the Docker registry. It also sets the base image’s OS to be Ubuntu by default. We have used a virtual name called “base” for this image layer.Then, we run an apt update on the Ubuntu OS.After that, we install some basic packages such as Firefox browser and vim text editor.Using the base image, we create another image layer on top of it called “requirements” which installs the dependencies from a separate file called “requirements.txt”.Using this image as the base image, we have created another intermediate image layer called “test” which creates the build context and copies the files and directories, and finally runs the python application for testing."
},
{
"code": null,
"e": 2880,
"s": 2676,
"text": "First, we have pulled the python 3 base images directly from the Docker registry. It also sets the base image’s OS to be Ubuntu by default. We have used a virtual name called “base” for this image layer."
},
{
"code": null,
"e": 2925,
"s": 2880,
"text": "Then, we run an apt update on the Ubuntu OS."
},
{
"code": null,
"e": 3013,
"s": 2925,
"text": "After that, we install some basic packages such as Firefox browser and vim text editor."
},
{
"code": null,
"e": 3180,
"s": 3013,
"text": "Using the base image, we create another image layer on top of it called “requirements” which installs the dependencies from a separate file called “requirements.txt”."
},
{
"code": null,
"e": 3402,
"s": 3180,
"text": "Using this image as the base image, we have created another intermediate image layer called “test” which creates the build context and copies the files and directories, and finally runs the python application for testing."
},
{
"code": null,
"e": 3481,
"s": 3402,
"text": "In the requirements file, we mention the dependencies that we want to install."
},
{
"code": null,
"e": 3501,
"s": 3481,
"text": "flask\npandas\nnumpy\n"
},
{
"code": null,
"e": 3696,
"s": 3501,
"text": "The main file that we want to run and have specified in the dockerfile’s CMD arguments is the index.py file. In the index.py file, we simply include a print statement for demonstration purposes."
},
{
"code": null,
"e": 3720,
"s": 3696,
"text": "print(\"geeksforgeeks\")\n"
},
{
"code": null,
"e": 3780,
"s": 3720,
"text": "To build the Docker Image, we use the Docker Build command."
},
{
"code": null,
"e": 3817,
"s": 3780,
"text": "sudo docker build -t sample-image .\n"
},
{
"code": null,
"e": 3836,
"s": 3817,
"text": "Building the Image"
},
{
"code": null,
"e": 3942,
"s": 3836,
"text": "After we have successfully built the Docker Image, we can run the container using the Docker run command."
},
{
"code": null,
"e": 3976,
"s": 3942,
"text": "sudo docker run -it sample-image\n"
},
{
"code": null,
"e": 3998,
"s": 3976,
"text": "Running the Container"
},
{
"code": null,
"e": 4299,
"s": 3998,
"text": "We can clearly see how the combination of FROM and AS commands can help us create a unique hierarchy for all our projects or project components. Basically, it allows us to perform inheritance of image components including hierarchical or multiple inheritances based on how you combine those commands."
},
{
"code": null,
"e": 4648,
"s": 4299,
"text": "This proves to be very helpful because it allows you to perform all the tasks using a single dockerfile thus making version management easier, it gives a better overview of the whole project, it reduces the overall size of the final image by eliminating the need to use the same files in the different image since there is only one final image now."
},
{
"code": null,
"e": 4813,
"s": 4648,
"text": "To conclude, in this article we discussed how to use Docker multi-stage builds to use and inherit multiple bases and customize image layers in a single dockerfile. "
},
{
"code": null,
"e": 4830,
"s": 4813,
"text": "Docker Container"
},
{
"code": null,
"e": 4836,
"s": 4830,
"text": "linux"
},
{
"code": null,
"e": 4862,
"s": 4836,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 4873,
"s": 4862,
"text": "Linux-Unix"
},
{
"code": null,
"e": 4971,
"s": 4873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5007,
"s": 4971,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5031,
"s": 5007,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 5075,
"s": 5031,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 5111,
"s": 5075,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 5146,
"s": 5111,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 5186,
"s": 5146,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 5226,
"s": 5186,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 5253,
"s": 5226,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 5288,
"s": 5253,
"text": "cut command in Linux with examples"
}
] |
Policemen catch thieves
|
08 Jun, 2022
Given an array of size n that has the following specifications:
Each element in the array contains either a policeman or a thief.Each policeman can catch only one thief.A policeman cannot catch a thief who is more than K units away from the policeman.
Each element in the array contains either a policeman or a thief.
Each policeman can catch only one thief.
A policeman cannot catch a thief who is more than K units away from the policeman.
We need to find the maximum number of thieves that can be caught.Examples:
Input : arr[] = {'P', 'T', 'T', 'P', 'T'},
k = 1.
Output : 2.
Here maximum 2 thieves can be caught, first
policeman catches first thief and second police-
man can catch either second or third thief.
Input : arr[] = {'T', 'T', 'P', 'P', 'T', 'P'},
k = 2.
Output : 3.
Input : arr[] = {'P', 'T', 'P', 'T', 'T', 'P'},
k = 3.
Output : 3.
A brute force approach would be to check all feasible sets of combinations of police and thief and return the maximum size set among them. Its time complexity is exponential and it can be optimized if we observe an important property. An efficient solution is to use a greedy algorithm. But which greedy property to use can be tricky. We can try using: “For each policeman from the left catch the nearest possible thief.” This works for example three given above but fails for example two as it outputs 2 which is incorrect. We may also try: “For each policeman from the left catch the farthest possible thief”. This works for example two given above but fails for example three as it outputs 2 which is incorrect. A symmetric argument can be applied to show that traversing for these from the right side of the array also fails. We can observe that thinking irrespective of the policeman and focusing on just the allotment works: 1. Get the lowest index of policeman p and thief t. Make an allotment if |p-t| <= k and increment to the next p and t found. 2. Otherwise increment min(p, t) to the next p or t found. 3. Repeat above two steps until next p and t are found. 4. Return the number of allotments made.Below is the implementation of the above algorithm. It uses vectors to store the indices of police and thief in the array and processes them.
C++
Java
C#
Python3
Javascript
// C++ program to find maximum number of thieves// caught#include<bits/stdc++.h>using namespace std; // Returns maximum number of thieves that can// be caught.int policeThief(char arr[], int n, int k){ int res = 0; vector<int> thi; vector<int> pol; // store indices in the vector for (int i = 0; i < n; i++) { if (arr[i] == 'P') pol.push_back(i); else if (arr[i] == 'T') thi.push_back(i); } // track lowest current indices of // thief: thi[l], police: pol[r] int l = 0, r = 0; while (l < thi.size() && r < pol.size()) { // can be caught if (abs(thi[l++] - pol[r++]) <= k) res++; // increment the minimum index else if (thi[l] < pol[r]) l++; else r++; } return res;} int main(){ int k, n; char arr1[] = { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = sizeof(arr1) / sizeof(arr1[0]); cout << "Maximum thieves caught: " << policeThief(arr1, n, k) << endl; char arr2[] = { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = sizeof(arr2) / sizeof(arr2[0]); cout << "Maximum thieves caught: " << policeThief(arr2, n, k) << endl; char arr3[] = { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = sizeof(arr3) / sizeof(arr3[0]); cout << "Maximum thieves caught: " << policeThief(arr3, n, k) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find maximum number of// thieves caughtimport java.util.*;import java.io.*; class GFG{ // Returns maximum number of thieves // that can be caught. static int policeThief(char arr[], int n, int k) { int res = 0; ArrayList<Integer> thi = new ArrayList<Integer>(); ArrayList<Integer> pol = new ArrayList<Integer>(); // store indices in the ArrayList for (int i = 0; i < n; i++) { if (arr[i] == 'P') pol.add(i); else if (arr[i] == 'T') thi.add(i); } // track lowest current indices of // thief: thi[l], police: pol[r] int l = 0, r = 0; while (l < thi.size() && r < pol.size()) { // can be caught if (Math.abs(thi.get(l++) - pol.get(r++)) <= k) res++; // increment the minimum index else if (thi.get(l) < pol.get(r)) l++; else r++; } return res; } public static void main(String args[]) { int k, n; char arr1[] = new char[] { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = arr1.length; System.out.println("Maximum thieves caught: " + policeThief(arr1, n, k)); char arr2[] = new char[] { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = arr2.length; System.out.println("Maximum thieves caught: " + policeThief(arr2, n, k)); char arr3[] = new char[] { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = arr3.length; System.out.println("Maximum thieves caught: " + policeThief(arr3, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129)
// C# program to find maximum number of// thieves caughtusing System;using System.Collections.Generic; public class GFG{ // Returns maximum number of thieves // that can be caught. static int policeThief(char[] arr, int n, int k) { int res = 0; List<int> thi = new List<int>(); List<int> pol = new List<int>(); // store indices in the ArrayList for (int i = 0; i < n; i++) { if (arr[i] == 'P') pol.Add(i); else if (arr[i] == 'T') thi.Add(i); } // track lowest current indices of // thief: thi[l], police: pol[r] int l = 0, r = 0; while (l < thi.Count && r < pol.Count) { // can be caught if (Math.Abs(thi[l++] - pol[r++]) <= k){ res++; }else{ if (thi[l] < pol[r]){ l++; }else{ r++; } } } return res; } static public void Main (){ int k, n; char[] arr1 = { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = arr1.Length; Console.Write("Maximum thieves caught: " + policeThief(arr1, n, k)+"\n"); char[] arr2 = { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = arr2.Length; Console.Write("Maximum thieves caught: " + policeThief(arr2, n, k)+"\n"); char[] arr3 = { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = arr3.Length; Console.Write("Maximum thieves caught: " + policeThief(arr3, n, k)+"\n"); }} //This code is contributed by shruti456rawal
# Python3 program to find maximum# number of thieves caught # Returns maximum number of thieves# that can be caught.def policeThief(arr, n, k): i = 0 l = 0 r = 0 res = 0 thi = [] pol = [] # store indices in list while i < n: if arr[i] == 'P': pol.append(i) elif arr[i] == 'T': thi.append(i) i += 1 # track lowest current indices of # thief: thi[l], police: pol[r] while l < len(thi) and r < len(pol): # can be caught if (abs( thi[l] - pol[r] ) <= k): res += 1 l += 1 r += 1 # increment the minimum index elif thi[l] < pol[r]: l += 1 else: r += 1 return res # Driver programif __name__=='__main__': arr1 = ['P', 'T', 'T', 'P', 'T'] k = 2 n = len(arr1) print(("Maximum thieves caught: {}". format(policeThief(arr1, n, k)))) arr2 = ['T', 'T', 'P', 'P', 'T', 'P'] k = 2 n = len(arr2) print(("Maximum thieves caught: {}". format(policeThief(arr2, n, k)))) arr3 = ['P', 'T', 'P', 'T', 'T', 'P'] k = 3 n = len(arr3) print(("Maximum thieves caught: {}". format(policeThief(arr3, n, k)))) # This code is contributed by `jahid_nadim`
<script> // JavaScript program to find maximum// number of thieves caught // Returns maximum number of thieves// that can be caught.function policeThief(arr, n, k){ let i = 0 let l = 0 let r = 0 let res = 0 let thi = [] let pol = [] // store indices in list while(i < n){ if(arr[i] == 'P') pol.push(i) else if(arr[i] == 'T') thi.push(i) i += 1 } // track lowest current indices of // thief: thi[l], police: pol[r] while(l < thi.length && r < pol.length){ // can be caught if (Math.abs( thi[l] - pol[r] ) <= k){ res += 1 l += 1 r += 1 } // increment the minimum index else if(thi[l] < pol[r]) l += 1 else r += 1 } return res} // Driver programlet arr1 = ['P', 'T', 'T', 'P', 'T']let k = 2let n = arr1.lengthdocument.write("Maximum thieves caught: ",policeThief(arr1, n, k),"</br>") let arr2 = ['T', 'T', 'P', 'P', 'T', 'P']k = 2n = arr2.lengthdocument.write("Maximum thieves caught: ",policeThief(arr2, n, k),"</br>") let arr3 = ['P', 'T', 'P', 'T', 'T', 'P']k = 3n = arr3.lengthdocument.write("Maximum thieves caught: ",policeThief(arr3, n, k),"</br>") // This code is contributed by shinjanpatra </script>
Maximum thieves caught: 2
Maximum thieves caught: 3
Maximum thieves caught: 3
Time Complexity: O(N) Auxiliary Space: O(N)
Following method works in O(1) space complexity
Approach:
This approach takes the following steps:
First find the left most police and thief and store the indices. There can be two cases:CASE 1: If the distance between the police and thief <= k (given), the thief can be caught, so increment the res counterCASE 2: If the distance between the police and thief >= k, the current thief cannot be caught by the current policeFor CASE 2, if the police is behind the thief, we need to find the next police and check if it can catch the current thiefif the thief is behind the police, we need to find the next thief and check if the current police can catch the thiefRepeat the process until we find the next police and thief pair, and increment result counter if conditions are met, i,e, CASE 1.
First find the left most police and thief and store the indices. There can be two cases:
CASE 1: If the distance between the police and thief <= k (given), the thief can be caught, so increment the res counter
CASE 2: If the distance between the police and thief >= k, the current thief cannot be caught by the current policeFor CASE 2, if the police is behind the thief, we need to find the next police and check if it can catch the current thiefif the thief is behind the police, we need to find the next thief and check if the current police can catch the thief
For CASE 2, if the police is behind the thief, we need to find the next police and check if it can catch the current thiefif the thief is behind the police, we need to find the next thief and check if the current police can catch the thief
For CASE 2, if the police is behind the thief, we need to find the next police and check if it can catch the current thief
if the thief is behind the police, we need to find the next thief and check if the current police can catch the thief
Repeat the process until we find the next police and thief pair, and increment result counter if conditions are met, i,e, CASE 1.
Algorithm:1. Initialize the current lowest indices of policeman in pol and thief in thi variable as -1.2 Find the lowest index of policeman and thief.3 If lowest index of either policeman or thief remain -1 then return 0.4 If |pol – thi| <=k then make an allotment and find the next policeman and thief.5 Else increment the min(pol , thi) to the next policeman or thief found.6 Repeat the above two steps until we can find the next policeman and thief.7 Return the number of allotments made.Below is the implementation of the above algorithm.
C++
C
Java
Javascript
Python3
// C++ program to find maximum number of thieves caught#include <bits/stdc++.h>using namespace std; // Returns maximum number of thieves that can be caught.int policeThief(char arr[], int n, int k){ // Initialize the current lowest indices of // policeman in pol and thief in thi variable as -1 int pol = -1, thi = -1, res = 0; // Find the lowest index of policemen for (int i = 0; i < n; i++) { if (arr[i] == 'P') { pol = i; break; } } // Find the lowest index of thief for (int i = 0; i < n; i++) { if (arr[i] == 'T') { thi = i; break; } } // If lowest index of either policemen or thief remain // -1 then return 0 if (thi == -1 || pol == -1) return 0; while (pol < n && thi < n) { // can be caught if (abs(pol - thi) <= k) { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; res++; } // increment the current min(pol , thi) to // the next policeman or thief found else if (thi < pol) { thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; } else { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; } } return res;} int main(){ int k, n; char arr1[] = { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = sizeof(arr1) / sizeof(arr1[0]); cout << "Maximum thieves caught: " << policeThief(arr1, n, k) << endl; char arr2[] = { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = sizeof(arr2) / sizeof(arr2[0]); cout << "Maximum thieves caught: " << policeThief(arr2, n, k) << endl; char arr3[] = { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = sizeof(arr3) / sizeof(arr3[0]); cout << "Maximum thieves caught: " << policeThief(arr3, n, k) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find maximum number of thieves// caught#include <stdio.h>#include <math.h>#include <stdlib.h> // Returns maximum number of thieves that can// be caught.int policeThief(char arr[], int n, int k){ // Initialize the current lowest indices of // policeman in pol and thief in thi variable as -1 int pol = -1, thi = -1, res = 0; // Find the lowest index of policemen for (int i = 0; i < n; i++) { if (arr[i] == 'P') { pol = i; break; } } // Find the lowest index of thief for (int i = 0; i < n; i++) { if (arr[i] == 'T') { thi = i; break; } } // If lowest index of either policemen or thief remain // -1 then return 0 if (thi == -1 || pol == -1) return 0; while (pol < n && thi < n) { // can be caught if (abs(pol - thi) <= k) { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; res++; } // increment the current min(pol , thi) to // the next policeman or thief found else if (thi < pol) { thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; } else { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; } } return res;} // Driver Code Starts. int main(){ int k, n; char arr1[] = { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = sizeof(arr1) / sizeof(arr1[0]); printf("Maximum thieves caught: %d\n", policeThief(arr1, n, k)); char arr2[] = { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = sizeof(arr2) / sizeof(arr2[0]); printf("Maximum thieves caught: %d\n", policeThief(arr2, n, k)); char arr3[] = { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = sizeof(arr3) / sizeof(arr3[0]); printf("Maximum thieves caught: %d\n", policeThief(arr3, n, k)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find maximum number of// thieves caughtimport java.io.*;import java.util.*; class GFG { // Returns maximum number of thieves that can be caught. static int policeThief(char arr[], int n, int k) { int pol = -1, thi = -1, res = 0; // store the first index of police in pol for (int i = 0; i < n; i++) { if (arr[i] == 'P') { pol = i; break; } } // store the first index of thief in thi for (int i = 0; i < n; i++) { if (arr[i] == 'T') { thi = i; break; } } // return 0 if no police OR no thief found if (thi == -1 || pol == -1) return 0; // loop to increase res iff distance between police // and thief <= k while (pol < n && thi < n) { // thief can be caught if (Math.abs(pol - thi) <= k) { pol++; // to find the index of next police for next // iteration while (pol < n && arr[pol] != 'P') pol++; // to find the index of next thief for next // iteration thi = thi + 1; while (thi < n && arr[thi] != 'T') thi++; // increment res, as the thief has been // caugh res++; } // thief cannot be caught as dist > k else if (thi < pol) { // as index of thief is behind police, we // need to find the next thief and check if // it can be caught by the current police // (it will be checked in the next // iteration) Hence, find the index of next // thief thi++; while (thi < n && arr[thi] != 'T') thi++; } else { // as the index of police is behind the // thief, it cannot catch the thief. Hence, // we need the index of next police and // check if it can catch the current thief // (it will be checked in the next // iteration) pol++; while (pol < n && arr[pol] != 'P') pol++; } } return res; } // Driver code starts public static void main(String[] args) { char arr1[] = { 'P', 'T', 'T', 'P', 'T' }; int n = arr1.length; int k = 2; System.out.println("Maximum thieves caught: " + policeThief(arr1, n, k)); char arr2[] = { 'T', 'T', 'P', 'P', 'T', 'P' }; n = arr2.length; k = 2; System.out.println("Maximum thieves caught: " + policeThief(arr2, n, k)); char arr3[] = { 'P', 'T', 'P', 'T', 'T', 'P' }; n = arr3.length; k = 3; System.out.println("Maximum thieves caught: " + policeThief(arr3, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129)
<script> // JavaScript program to find maximum number of thieves caught // Returns maximum number of thieves that can be caught.function policeThief(arr, n, k){ // Initialize the current lowest indices of // policeman in pol and thief in thi variable as -1 let pol = -1, thi = -1, res = 0; // Find the lowest index of policemen for (let i = 0; i < n; i++) { if (arr[i] == 'P') { pol = i; break; } } // Find the lowest index of thief for (let i = 0; i < n; i++) { if (arr[i] == 'T') { thi = i; break; } } // If lowest index of either policemen or thief remain // -1 then return 0 if (thi == -1 || pol == -1) return 0; while (pol < n && thi < n) { // can be caught if (Math.abs(pol - thi) <= k) { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; res++; } // increment the current min(pol , thi) to // the next policeman or thief found else if (thi < pol) { thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; } else { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; } } return res;} // driver codelet k, n;let arr1 = [ 'P', 'T', 'T', 'P', 'T' ];k = 2;n = arr1.length;document.write("Maximum thieves caught: ",policeThief(arr1, n, k),"</br>"); let arr2 = [ 'T', 'T', 'P', 'P', 'T', 'P' ];k = 2;n = arr2.length;document.write("Maximum thieves caught: ",policeThief(arr2, n, k),"</br>"); let arr3 = [ 'P', 'T', 'P', 'T', 'T', 'P' ];k = 3;n = arr3.length;document.write("Maximum thieves caught: ",policeThief(arr3, n, k),"</br>"); // This code is contributed by shinjanpatra </script>
# Python program to find maximum number of thieves caught # Returns maximum number of thieves that can be caught.def policeThief(arr, n, k): # Initialize the current lowest indices of # policeman in pol and thief in thi variable as -1 pol,thi,res = -1,-1,0 # Find the lowest index of policemen for i in range(n): if (arr[i] == 'P'): pol = i break # Find the lowest index of thief for i in range(n): if (arr[i] == 'T'): thi = i break # If lowest index of either policemen or thief remain # -1 then return 0 if (thi == -1 or pol == -1): return 0 while (pol < n and thi < n): # can be caught if (abs(pol - thi) <= k): pol = pol + 1 while (pol < n and arr[pol] != 'P'): pol = pol + 1 thi = thi + 1 while (thi < n and arr[thi] != 'T'): thi = thi + 1 res += 1 # increment the current min(pol , thi) to # the next policeman or thief found elif (thi < pol): thi = thi + 1 while (thi < n and arr[thi] != 'T'): thi = thi + 1 else: pol = pol + 1 while (pol < n and arr[pol] != 'P'): pol = pol + 1 return res # driver code arr1 = [ 'P', 'T', 'T', 'P', 'T' ];k = 2;n = len(arr1)print("Maximum thieves caught: " + str(policeThief(arr1, n, k))) arr2 = [ 'T', 'T', 'P', 'P', 'T', 'P' ];k = 2;n = len(arr2)print("Maximum thieves caught: "+ str(policeThief(arr2, n, k))) arr3 = [ 'P', 'T', 'P', 'T', 'T', 'P' ];k = 3;n = len(arr3)print("Maximum thieves caught: "+ str(policeThief(arr3, n, k))) # This code is contributed by shinjanpatra
Maximum thieves caught: 2
Maximum thieves caught: 3
Maximum thieves caught: 3
Time Complexity: O(N) Auxiliary Space: O(1)
This article is contributed by Satish Srinivas. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jahid_nadim
sankalpvairat2
sandeepsingh27
harshjusharma
surindertarika1234
simmytarika5
surinderdawra388
adityakumar129
shinjanpatra
shruti456rawal
National Instruments
Greedy
National Instruments
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for array rotation
Write a program to print all permutations of a given string
Coin Change | DP-7
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Minimum Number of Platforms Required for a Railway/Bus Station
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
Difference between Prim's and Kruskal's algorithm for MST
3 Different ways to print Fibonacci series in Java
Minimize the maximum difference between the heights
Maximize difference between the Sum of the two halves of the Array after removal of N elements
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 119,
"s": 54,
"text": "Given an array of size n that has the following specifications: "
},
{
"code": null,
"e": 307,
"s": 119,
"text": "Each element in the array contains either a policeman or a thief.Each policeman can catch only one thief.A policeman cannot catch a thief who is more than K units away from the policeman."
},
{
"code": null,
"e": 373,
"s": 307,
"text": "Each element in the array contains either a policeman or a thief."
},
{
"code": null,
"e": 414,
"s": 373,
"text": "Each policeman can catch only one thief."
},
{
"code": null,
"e": 497,
"s": 414,
"text": "A policeman cannot catch a thief who is more than K units away from the policeman."
},
{
"code": null,
"e": 574,
"s": 497,
"text": "We need to find the maximum number of thieves that can be caught.Examples: "
},
{
"code": null,
"e": 946,
"s": 574,
"text": "Input : arr[] = {'P', 'T', 'T', 'P', 'T'},\n k = 1.\nOutput : 2.\nHere maximum 2 thieves can be caught, first\npoliceman catches first thief and second police-\nman can catch either second or third thief.\n\nInput : arr[] = {'T', 'T', 'P', 'P', 'T', 'P'}, \n k = 2.\nOutput : 3.\n\nInput : arr[] = {'P', 'T', 'P', 'T', 'T', 'P'},\n k = 3.\nOutput : 3."
},
{
"code": null,
"e": 2301,
"s": 946,
"text": "A brute force approach would be to check all feasible sets of combinations of police and thief and return the maximum size set among them. Its time complexity is exponential and it can be optimized if we observe an important property. An efficient solution is to use a greedy algorithm. But which greedy property to use can be tricky. We can try using: “For each policeman from the left catch the nearest possible thief.” This works for example three given above but fails for example two as it outputs 2 which is incorrect. We may also try: “For each policeman from the left catch the farthest possible thief”. This works for example two given above but fails for example three as it outputs 2 which is incorrect. A symmetric argument can be applied to show that traversing for these from the right side of the array also fails. We can observe that thinking irrespective of the policeman and focusing on just the allotment works: 1. Get the lowest index of policeman p and thief t. Make an allotment if |p-t| <= k and increment to the next p and t found. 2. Otherwise increment min(p, t) to the next p or t found. 3. Repeat above two steps until next p and t are found. 4. Return the number of allotments made.Below is the implementation of the above algorithm. It uses vectors to store the indices of police and thief in the array and processes them. "
},
{
"code": null,
"e": 2305,
"s": 2301,
"text": "C++"
},
{
"code": null,
"e": 2310,
"s": 2305,
"text": "Java"
},
{
"code": null,
"e": 2313,
"s": 2310,
"text": "C#"
},
{
"code": null,
"e": 2321,
"s": 2313,
"text": "Python3"
},
{
"code": null,
"e": 2332,
"s": 2321,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum number of thieves// caught#include<bits/stdc++.h>using namespace std; // Returns maximum number of thieves that can// be caught.int policeThief(char arr[], int n, int k){ int res = 0; vector<int> thi; vector<int> pol; // store indices in the vector for (int i = 0; i < n; i++) { if (arr[i] == 'P') pol.push_back(i); else if (arr[i] == 'T') thi.push_back(i); } // track lowest current indices of // thief: thi[l], police: pol[r] int l = 0, r = 0; while (l < thi.size() && r < pol.size()) { // can be caught if (abs(thi[l++] - pol[r++]) <= k) res++; // increment the minimum index else if (thi[l] < pol[r]) l++; else r++; } return res;} int main(){ int k, n; char arr1[] = { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = sizeof(arr1) / sizeof(arr1[0]); cout << \"Maximum thieves caught: \" << policeThief(arr1, n, k) << endl; char arr2[] = { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = sizeof(arr2) / sizeof(arr2[0]); cout << \"Maximum thieves caught: \" << policeThief(arr2, n, k) << endl; char arr3[] = { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = sizeof(arr3) / sizeof(arr3[0]); cout << \"Maximum thieves caught: \" << policeThief(arr3, n, k) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 3649,
"s": 2332,
"text": null
},
{
"code": "// Java program to find maximum number of// thieves caughtimport java.util.*;import java.io.*; class GFG{ // Returns maximum number of thieves // that can be caught. static int policeThief(char arr[], int n, int k) { int res = 0; ArrayList<Integer> thi = new ArrayList<Integer>(); ArrayList<Integer> pol = new ArrayList<Integer>(); // store indices in the ArrayList for (int i = 0; i < n; i++) { if (arr[i] == 'P') pol.add(i); else if (arr[i] == 'T') thi.add(i); } // track lowest current indices of // thief: thi[l], police: pol[r] int l = 0, r = 0; while (l < thi.size() && r < pol.size()) { // can be caught if (Math.abs(thi.get(l++) - pol.get(r++)) <= k) res++; // increment the minimum index else if (thi.get(l) < pol.get(r)) l++; else r++; } return res; } public static void main(String args[]) { int k, n; char arr1[] = new char[] { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = arr1.length; System.out.println(\"Maximum thieves caught: \" + policeThief(arr1, n, k)); char arr2[] = new char[] { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = arr2.length; System.out.println(\"Maximum thieves caught: \" + policeThief(arr2, n, k)); char arr3[] = new char[] { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = arr3.length; System.out.println(\"Maximum thieves caught: \" + policeThief(arr3, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 5150,
"s": 3649,
"text": null
},
{
"code": "// C# program to find maximum number of// thieves caughtusing System;using System.Collections.Generic; public class GFG{ // Returns maximum number of thieves // that can be caught. static int policeThief(char[] arr, int n, int k) { int res = 0; List<int> thi = new List<int>(); List<int> pol = new List<int>(); // store indices in the ArrayList for (int i = 0; i < n; i++) { if (arr[i] == 'P') pol.Add(i); else if (arr[i] == 'T') thi.Add(i); } // track lowest current indices of // thief: thi[l], police: pol[r] int l = 0, r = 0; while (l < thi.Count && r < pol.Count) { // can be caught if (Math.Abs(thi[l++] - pol[r++]) <= k){ res++; }else{ if (thi[l] < pol[r]){ l++; }else{ r++; } } } return res; } static public void Main (){ int k, n; char[] arr1 = { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = arr1.Length; Console.Write(\"Maximum thieves caught: \" + policeThief(arr1, n, k)+\"\\n\"); char[] arr2 = { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = arr2.Length; Console.Write(\"Maximum thieves caught: \" + policeThief(arr2, n, k)+\"\\n\"); char[] arr3 = { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = arr3.Length; Console.Write(\"Maximum thieves caught: \" + policeThief(arr3, n, k)+\"\\n\"); }} //This code is contributed by shruti456rawal",
"e": 6760,
"s": 5150,
"text": null
},
{
"code": "# Python3 program to find maximum# number of thieves caught # Returns maximum number of thieves# that can be caught.def policeThief(arr, n, k): i = 0 l = 0 r = 0 res = 0 thi = [] pol = [] # store indices in list while i < n: if arr[i] == 'P': pol.append(i) elif arr[i] == 'T': thi.append(i) i += 1 # track lowest current indices of # thief: thi[l], police: pol[r] while l < len(thi) and r < len(pol): # can be caught if (abs( thi[l] - pol[r] ) <= k): res += 1 l += 1 r += 1 # increment the minimum index elif thi[l] < pol[r]: l += 1 else: r += 1 return res # Driver programif __name__=='__main__': arr1 = ['P', 'T', 'T', 'P', 'T'] k = 2 n = len(arr1) print((\"Maximum thieves caught: {}\". format(policeThief(arr1, n, k)))) arr2 = ['T', 'T', 'P', 'P', 'T', 'P'] k = 2 n = len(arr2) print((\"Maximum thieves caught: {}\". format(policeThief(arr2, n, k)))) arr3 = ['P', 'T', 'P', 'T', 'T', 'P'] k = 3 n = len(arr3) print((\"Maximum thieves caught: {}\". format(policeThief(arr3, n, k)))) # This code is contributed by `jahid_nadim`",
"e": 8042,
"s": 6760,
"text": null
},
{
"code": "<script> // JavaScript program to find maximum// number of thieves caught // Returns maximum number of thieves// that can be caught.function policeThief(arr, n, k){ let i = 0 let l = 0 let r = 0 let res = 0 let thi = [] let pol = [] // store indices in list while(i < n){ if(arr[i] == 'P') pol.push(i) else if(arr[i] == 'T') thi.push(i) i += 1 } // track lowest current indices of // thief: thi[l], police: pol[r] while(l < thi.length && r < pol.length){ // can be caught if (Math.abs( thi[l] - pol[r] ) <= k){ res += 1 l += 1 r += 1 } // increment the minimum index else if(thi[l] < pol[r]) l += 1 else r += 1 } return res} // Driver programlet arr1 = ['P', 'T', 'T', 'P', 'T']let k = 2let n = arr1.lengthdocument.write(\"Maximum thieves caught: \",policeThief(arr1, n, k),\"</br>\") let arr2 = ['T', 'T', 'P', 'P', 'T', 'P']k = 2n = arr2.lengthdocument.write(\"Maximum thieves caught: \",policeThief(arr2, n, k),\"</br>\") let arr3 = ['P', 'T', 'P', 'T', 'T', 'P']k = 3n = arr3.lengthdocument.write(\"Maximum thieves caught: \",policeThief(arr3, n, k),\"</br>\") // This code is contributed by shinjanpatra </script>",
"e": 9356,
"s": 8042,
"text": null
},
{
"code": null,
"e": 9434,
"s": 9356,
"text": "Maximum thieves caught: 2\nMaximum thieves caught: 3\nMaximum thieves caught: 3"
},
{
"code": null,
"e": 9478,
"s": 9434,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9526,
"s": 9478,
"text": "Following method works in O(1) space complexity"
},
{
"code": null,
"e": 9536,
"s": 9526,
"text": "Approach:"
},
{
"code": null,
"e": 9577,
"s": 9536,
"text": "This approach takes the following steps:"
},
{
"code": null,
"e": 10269,
"s": 9577,
"text": "First find the left most police and thief and store the indices. There can be two cases:CASE 1: If the distance between the police and thief <= k (given), the thief can be caught, so increment the res counterCASE 2: If the distance between the police and thief >= k, the current thief cannot be caught by the current policeFor CASE 2, if the police is behind the thief, we need to find the next police and check if it can catch the current thiefif the thief is behind the police, we need to find the next thief and check if the current police can catch the thiefRepeat the process until we find the next police and thief pair, and increment result counter if conditions are met, i,e, CASE 1."
},
{
"code": null,
"e": 10358,
"s": 10269,
"text": "First find the left most police and thief and store the indices. There can be two cases:"
},
{
"code": null,
"e": 10479,
"s": 10358,
"text": "CASE 1: If the distance between the police and thief <= k (given), the thief can be caught, so increment the res counter"
},
{
"code": null,
"e": 10834,
"s": 10479,
"text": "CASE 2: If the distance between the police and thief >= k, the current thief cannot be caught by the current policeFor CASE 2, if the police is behind the thief, we need to find the next police and check if it can catch the current thiefif the thief is behind the police, we need to find the next thief and check if the current police can catch the thief"
},
{
"code": null,
"e": 11074,
"s": 10834,
"text": "For CASE 2, if the police is behind the thief, we need to find the next police and check if it can catch the current thiefif the thief is behind the police, we need to find the next thief and check if the current police can catch the thief"
},
{
"code": null,
"e": 11197,
"s": 11074,
"text": "For CASE 2, if the police is behind the thief, we need to find the next police and check if it can catch the current thief"
},
{
"code": null,
"e": 11315,
"s": 11197,
"text": "if the thief is behind the police, we need to find the next thief and check if the current police can catch the thief"
},
{
"code": null,
"e": 11445,
"s": 11315,
"text": "Repeat the process until we find the next police and thief pair, and increment result counter if conditions are met, i,e, CASE 1."
},
{
"code": null,
"e": 11988,
"s": 11445,
"text": "Algorithm:1. Initialize the current lowest indices of policeman in pol and thief in thi variable as -1.2 Find the lowest index of policeman and thief.3 If lowest index of either policeman or thief remain -1 then return 0.4 If |pol – thi| <=k then make an allotment and find the next policeman and thief.5 Else increment the min(pol , thi) to the next policeman or thief found.6 Repeat the above two steps until we can find the next policeman and thief.7 Return the number of allotments made.Below is the implementation of the above algorithm."
},
{
"code": null,
"e": 11992,
"s": 11988,
"text": "C++"
},
{
"code": null,
"e": 11994,
"s": 11992,
"text": "C"
},
{
"code": null,
"e": 11999,
"s": 11994,
"text": "Java"
},
{
"code": null,
"e": 12010,
"s": 11999,
"text": "Javascript"
},
{
"code": null,
"e": 12018,
"s": 12010,
"text": "Python3"
},
{
"code": "// C++ program to find maximum number of thieves caught#include <bits/stdc++.h>using namespace std; // Returns maximum number of thieves that can be caught.int policeThief(char arr[], int n, int k){ // Initialize the current lowest indices of // policeman in pol and thief in thi variable as -1 int pol = -1, thi = -1, res = 0; // Find the lowest index of policemen for (int i = 0; i < n; i++) { if (arr[i] == 'P') { pol = i; break; } } // Find the lowest index of thief for (int i = 0; i < n; i++) { if (arr[i] == 'T') { thi = i; break; } } // If lowest index of either policemen or thief remain // -1 then return 0 if (thi == -1 || pol == -1) return 0; while (pol < n && thi < n) { // can be caught if (abs(pol - thi) <= k) { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; res++; } // increment the current min(pol , thi) to // the next policeman or thief found else if (thi < pol) { thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; } else { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; } } return res;} int main(){ int k, n; char arr1[] = { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = sizeof(arr1) / sizeof(arr1[0]); cout << \"Maximum thieves caught: \" << policeThief(arr1, n, k) << endl; char arr2[] = { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = sizeof(arr2) / sizeof(arr2[0]); cout << \"Maximum thieves caught: \" << policeThief(arr2, n, k) << endl; char arr3[] = { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = sizeof(arr3) / sizeof(arr3[0]); cout << \"Maximum thieves caught: \" << policeThief(arr3, n, k) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 13890,
"s": 12018,
"text": null
},
{
"code": "// C program to find maximum number of thieves// caught#include <stdio.h>#include <math.h>#include <stdlib.h> // Returns maximum number of thieves that can// be caught.int policeThief(char arr[], int n, int k){ // Initialize the current lowest indices of // policeman in pol and thief in thi variable as -1 int pol = -1, thi = -1, res = 0; // Find the lowest index of policemen for (int i = 0; i < n; i++) { if (arr[i] == 'P') { pol = i; break; } } // Find the lowest index of thief for (int i = 0; i < n; i++) { if (arr[i] == 'T') { thi = i; break; } } // If lowest index of either policemen or thief remain // -1 then return 0 if (thi == -1 || pol == -1) return 0; while (pol < n && thi < n) { // can be caught if (abs(pol - thi) <= k) { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; res++; } // increment the current min(pol , thi) to // the next policeman or thief found else if (thi < pol) { thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; } else { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; } } return res;} // Driver Code Starts. int main(){ int k, n; char arr1[] = { 'P', 'T', 'T', 'P', 'T' }; k = 2; n = sizeof(arr1) / sizeof(arr1[0]); printf(\"Maximum thieves caught: %d\\n\", policeThief(arr1, n, k)); char arr2[] = { 'T', 'T', 'P', 'P', 'T', 'P' }; k = 2; n = sizeof(arr2) / sizeof(arr2[0]); printf(\"Maximum thieves caught: %d\\n\", policeThief(arr2, n, k)); char arr3[] = { 'P', 'T', 'P', 'T', 'T', 'P' }; k = 3; n = sizeof(arr3) / sizeof(arr3[0]); printf(\"Maximum thieves caught: %d\\n\", policeThief(arr3, n, k)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 15781,
"s": 13890,
"text": null
},
{
"code": "// Java program to find maximum number of// thieves caughtimport java.io.*;import java.util.*; class GFG { // Returns maximum number of thieves that can be caught. static int policeThief(char arr[], int n, int k) { int pol = -1, thi = -1, res = 0; // store the first index of police in pol for (int i = 0; i < n; i++) { if (arr[i] == 'P') { pol = i; break; } } // store the first index of thief in thi for (int i = 0; i < n; i++) { if (arr[i] == 'T') { thi = i; break; } } // return 0 if no police OR no thief found if (thi == -1 || pol == -1) return 0; // loop to increase res iff distance between police // and thief <= k while (pol < n && thi < n) { // thief can be caught if (Math.abs(pol - thi) <= k) { pol++; // to find the index of next police for next // iteration while (pol < n && arr[pol] != 'P') pol++; // to find the index of next thief for next // iteration thi = thi + 1; while (thi < n && arr[thi] != 'T') thi++; // increment res, as the thief has been // caugh res++; } // thief cannot be caught as dist > k else if (thi < pol) { // as index of thief is behind police, we // need to find the next thief and check if // it can be caught by the current police // (it will be checked in the next // iteration) Hence, find the index of next // thief thi++; while (thi < n && arr[thi] != 'T') thi++; } else { // as the index of police is behind the // thief, it cannot catch the thief. Hence, // we need the index of next police and // check if it can catch the current thief // (it will be checked in the next // iteration) pol++; while (pol < n && arr[pol] != 'P') pol++; } } return res; } // Driver code starts public static void main(String[] args) { char arr1[] = { 'P', 'T', 'T', 'P', 'T' }; int n = arr1.length; int k = 2; System.out.println(\"Maximum thieves caught: \" + policeThief(arr1, n, k)); char arr2[] = { 'T', 'T', 'P', 'P', 'T', 'P' }; n = arr2.length; k = 2; System.out.println(\"Maximum thieves caught: \" + policeThief(arr2, n, k)); char arr3[] = { 'P', 'T', 'P', 'T', 'T', 'P' }; n = arr3.length; k = 3; System.out.println(\"Maximum thieves caught: \" + policeThief(arr3, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 18852,
"s": 15781,
"text": null
},
{
"code": "<script> // JavaScript program to find maximum number of thieves caught // Returns maximum number of thieves that can be caught.function policeThief(arr, n, k){ // Initialize the current lowest indices of // policeman in pol and thief in thi variable as -1 let pol = -1, thi = -1, res = 0; // Find the lowest index of policemen for (let i = 0; i < n; i++) { if (arr[i] == 'P') { pol = i; break; } } // Find the lowest index of thief for (let i = 0; i < n; i++) { if (arr[i] == 'T') { thi = i; break; } } // If lowest index of either policemen or thief remain // -1 then return 0 if (thi == -1 || pol == -1) return 0; while (pol < n && thi < n) { // can be caught if (Math.abs(pol - thi) <= k) { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; res++; } // increment the current min(pol , thi) to // the next policeman or thief found else if (thi < pol) { thi = thi + 1; while (thi < n && arr[thi] != 'T') thi = thi + 1; } else { pol = pol + 1; while (pol < n && arr[pol] != 'P') pol = pol + 1; } } return res;} // driver codelet k, n;let arr1 = [ 'P', 'T', 'T', 'P', 'T' ];k = 2;n = arr1.length;document.write(\"Maximum thieves caught: \",policeThief(arr1, n, k),\"</br>\"); let arr2 = [ 'T', 'T', 'P', 'P', 'T', 'P' ];k = 2;n = arr2.length;document.write(\"Maximum thieves caught: \",policeThief(arr2, n, k),\"</br>\"); let arr3 = [ 'P', 'T', 'P', 'T', 'T', 'P' ];k = 3;n = arr3.length;document.write(\"Maximum thieves caught: \",policeThief(arr3, n, k),\"</br>\"); // This code is contributed by shinjanpatra </script>",
"e": 20610,
"s": 18852,
"text": null
},
{
"code": "# Python program to find maximum number of thieves caught # Returns maximum number of thieves that can be caught.def policeThief(arr, n, k): # Initialize the current lowest indices of # policeman in pol and thief in thi variable as -1 pol,thi,res = -1,-1,0 # Find the lowest index of policemen for i in range(n): if (arr[i] == 'P'): pol = i break # Find the lowest index of thief for i in range(n): if (arr[i] == 'T'): thi = i break # If lowest index of either policemen or thief remain # -1 then return 0 if (thi == -1 or pol == -1): return 0 while (pol < n and thi < n): # can be caught if (abs(pol - thi) <= k): pol = pol + 1 while (pol < n and arr[pol] != 'P'): pol = pol + 1 thi = thi + 1 while (thi < n and arr[thi] != 'T'): thi = thi + 1 res += 1 # increment the current min(pol , thi) to # the next policeman or thief found elif (thi < pol): thi = thi + 1 while (thi < n and arr[thi] != 'T'): thi = thi + 1 else: pol = pol + 1 while (pol < n and arr[pol] != 'P'): pol = pol + 1 return res # driver code arr1 = [ 'P', 'T', 'T', 'P', 'T' ];k = 2;n = len(arr1)print(\"Maximum thieves caught: \" + str(policeThief(arr1, n, k))) arr2 = [ 'T', 'T', 'P', 'P', 'T', 'P' ];k = 2;n = len(arr2)print(\"Maximum thieves caught: \"+ str(policeThief(arr2, n, k))) arr3 = [ 'P', 'T', 'P', 'T', 'T', 'P' ];k = 3;n = len(arr3)print(\"Maximum thieves caught: \"+ str(policeThief(arr3, n, k))) # This code is contributed by shinjanpatra",
"e": 22349,
"s": 20610,
"text": null
},
{
"code": null,
"e": 22427,
"s": 22349,
"text": "Maximum thieves caught: 2\nMaximum thieves caught: 3\nMaximum thieves caught: 3"
},
{
"code": null,
"e": 22471,
"s": 22427,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 22895,
"s": 22471,
"text": "This article is contributed by Satish Srinivas. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 22907,
"s": 22895,
"text": "jahid_nadim"
},
{
"code": null,
"e": 22922,
"s": 22907,
"text": "sankalpvairat2"
},
{
"code": null,
"e": 22937,
"s": 22922,
"text": "sandeepsingh27"
},
{
"code": null,
"e": 22951,
"s": 22937,
"text": "harshjusharma"
},
{
"code": null,
"e": 22970,
"s": 22951,
"text": "surindertarika1234"
},
{
"code": null,
"e": 22983,
"s": 22970,
"text": "simmytarika5"
},
{
"code": null,
"e": 23000,
"s": 22983,
"text": "surinderdawra388"
},
{
"code": null,
"e": 23015,
"s": 23000,
"text": "adityakumar129"
},
{
"code": null,
"e": 23028,
"s": 23015,
"text": "shinjanpatra"
},
{
"code": null,
"e": 23043,
"s": 23028,
"text": "shruti456rawal"
},
{
"code": null,
"e": 23064,
"s": 23043,
"text": "National Instruments"
},
{
"code": null,
"e": 23071,
"s": 23064,
"text": "Greedy"
},
{
"code": null,
"e": 23092,
"s": 23071,
"text": "National Instruments"
},
{
"code": null,
"e": 23099,
"s": 23092,
"text": "Greedy"
},
{
"code": null,
"e": 23197,
"s": 23099,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 23224,
"s": 23197,
"text": "Program for array rotation"
},
{
"code": null,
"e": 23284,
"s": 23224,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 23303,
"s": 23284,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 23384,
"s": 23303,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 23447,
"s": 23384,
"text": "Minimum Number of Platforms Required for a Railway/Bus Station"
},
{
"code": null,
"e": 23518,
"s": 23447,
"text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8"
},
{
"code": null,
"e": 23576,
"s": 23518,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 23627,
"s": 23576,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 23679,
"s": 23627,
"text": "Minimize the maximum difference between the heights"
}
] |
Underscore.js _.whereWhere Function
|
24 Nov, 2021
The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke, etc even without using any built-in objects.
The _.findWhere() function is used to have a list of all the elements that matches the given property. The _.findWhere() function is used to search a content in the whole list of sections. The section which contains the content will be displayed.
Syntax:
_.findWhere(list, properties)
Parameters: It takes two arguments:
List: This parameter contains the list of items.
Property: This parameter contains the test condition.
Return value: The details of the element selected from the list are returned. Only the first element matched will be given as output.
Difference between _.findWhere() and _.where() function: Both the functions takes an array name and the property to match but the _.where() function displays all the matches whereas, _.findWhere) function matches only the first match.
Searching a property in an array: The ._findWhere() function takes the array elements one by one and matches the given property is same or not. If the property matches it displays the rest of the details of that particular element. After the property is matched the first time the _.findWhere() function ends. It only displays the first match.
Example:
HTML
<html> <head> <title>_.findWhere() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> var users = [{id: 1, name: "harry"}, {id: 2, name: "jerry"}]; _.findWhere(users, {id:2}).name = 'tom'; console.log(users); </script> </body> </html>
Output:
Passing a list of elements with a number of different properties to _.findWhere() function: Firstly, declare the array with all the elements and their specific properties. Then pass the array name along with the property which needs to match to the _.findWhere() function. All the rest properties will be displayed as output of that specific element.
Example:
HTML
<html> <head> <title>_.findWhere() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> var goal = [ { "category" : "other", "title" : "harry University", "value" : 50000, "id":"1" }, { "category" : "traveling", "title" : "tommy University", "value" : 50000, "id":"2" }, { "category" : "education", "title" : "jerry University", "value" : 50000, "id":"3" }, { "category" : "business", "title" : "Charlie University", "value" : 50000, "id":"4" } ] console.log(_.findWhere(goal, {category: "education"})); </script> </body> </html>
Output:
Passing an array with ‘true/false’ as a property to the _.findWhere() function: First declare the array (here array is ‘people’). It is the property (here, ‘hasLong’) be defines as ‘true’ or ‘false’. Choose one condition to check like here ‘hasLongHairs’. Console.log display the final answer.
Example:
HTML
<html> <head> <title>_.findWhere() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> var people = [ {"name": "sakshi", "hasLong": "false"}, {"name": "aishwarya", "hasLong": "true"}, {"name": "akansha", "hasLong": "true"}, {"name": "preeti", "hasLong": "true"} ] console.log(_.findWhere(people, {hasLong: "true"})); </script> </body></html>
Output:
Passing an array of numbers as property to _.findWhere() function together: It also follows the same procedure of firstly declaring the array with all the properties and the giving the array name and the property of matching to the _.findWhere() function.
Example:
HTML
<html> <head> <title>_.findWhere() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> var users = [{"num":"1"}, {"num":"2"}, {"num":"3"}, {"num":"4"}, {"num":"5"}]; console.log(_.findWhere(users, {num:"2"})); </script> </body> </html>
Output:
arorakashish0911
JavaScript - Underscore.js
JavaScript
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke, etc even without using any built-in objects. "
},
{
"code": null,
"e": 477,
"s": 229,
"text": "The _.findWhere() function is used to have a list of all the elements that matches the given property. The _.findWhere() function is used to search a content in the whole list of sections. The section which contains the content will be displayed. "
},
{
"code": null,
"e": 487,
"s": 477,
"text": "Syntax: "
},
{
"code": null,
"e": 520,
"s": 487,
"text": "_.findWhere(list, properties) \n\n"
},
{
"code": null,
"e": 557,
"s": 520,
"text": "Parameters: It takes two arguments: "
},
{
"code": null,
"e": 606,
"s": 557,
"text": "List: This parameter contains the list of items."
},
{
"code": null,
"e": 660,
"s": 606,
"text": "Property: This parameter contains the test condition."
},
{
"code": null,
"e": 794,
"s": 660,
"text": "Return value: The details of the element selected from the list are returned. Only the first element matched will be given as output."
},
{
"code": null,
"e": 1029,
"s": 794,
"text": "Difference between _.findWhere() and _.where() function: Both the functions takes an array name and the property to match but the _.where() function displays all the matches whereas, _.findWhere) function matches only the first match."
},
{
"code": null,
"e": 1373,
"s": 1029,
"text": "Searching a property in an array: The ._findWhere() function takes the array elements one by one and matches the given property is same or not. If the property matches it displays the rest of the details of that particular element. After the property is matched the first time the _.findWhere() function ends. It only displays the first match."
},
{
"code": null,
"e": 1383,
"s": 1373,
"text": "Example: "
},
{
"code": null,
"e": 1388,
"s": 1383,
"text": "HTML"
},
{
"code": "<html> <head> <title>_.findWhere() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> var users = [{id: 1, name: \"harry\"}, {id: 2, name: \"jerry\"}]; _.findWhere(users, {id:2}).name = 'tom'; console.log(users); </script> </body> </html>",
"e": 1858,
"s": 1388,
"text": null
},
{
"code": null,
"e": 1867,
"s": 1858,
"text": "Output: "
},
{
"code": null,
"e": 2218,
"s": 1867,
"text": "Passing a list of elements with a number of different properties to _.findWhere() function: Firstly, declare the array with all the elements and their specific properties. Then pass the array name along with the property which needs to match to the _.findWhere() function. All the rest properties will be displayed as output of that specific element."
},
{
"code": null,
"e": 2229,
"s": 2218,
"text": "Example: "
},
{
"code": null,
"e": 2234,
"s": 2229,
"text": "HTML"
},
{
"code": "<html> <head> <title>_.findWhere() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> var goal = [ { \"category\" : \"other\", \"title\" : \"harry University\", \"value\" : 50000, \"id\":\"1\" }, { \"category\" : \"traveling\", \"title\" : \"tommy University\", \"value\" : 50000, \"id\":\"2\" }, { \"category\" : \"education\", \"title\" : \"jerry University\", \"value\" : 50000, \"id\":\"3\" }, { \"category\" : \"business\", \"title\" : \"Charlie University\", \"value\" : 50000, \"id\":\"4\" } ] console.log(_.findWhere(goal, {category: \"education\"})); </script> </body> </html>",
"e": 3426,
"s": 2234,
"text": null
},
{
"code": null,
"e": 3435,
"s": 3426,
"text": "Output: "
},
{
"code": null,
"e": 3729,
"s": 3435,
"text": "Passing an array with ‘true/false’ as a property to the _.findWhere() function: First declare the array (here array is ‘people’). It is the property (here, ‘hasLong’) be defines as ‘true’ or ‘false’. Choose one condition to check like here ‘hasLongHairs’. Console.log display the final answer."
},
{
"code": null,
"e": 3740,
"s": 3729,
"text": "Example: "
},
{
"code": null,
"e": 3745,
"s": 3740,
"text": "HTML"
},
{
"code": "<html> <head> <title>_.findWhere() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> var people = [ {\"name\": \"sakshi\", \"hasLong\": \"false\"}, {\"name\": \"aishwarya\", \"hasLong\": \"true\"}, {\"name\": \"akansha\", \"hasLong\": \"true\"}, {\"name\": \"preeti\", \"hasLong\": \"true\"} ] console.log(_.findWhere(people, {hasLong: \"true\"})); </script> </body></html>",
"e": 4377,
"s": 3745,
"text": null
},
{
"code": null,
"e": 4385,
"s": 4377,
"text": "Output:"
},
{
"code": null,
"e": 4641,
"s": 4385,
"text": "Passing an array of numbers as property to _.findWhere() function together: It also follows the same procedure of firstly declaring the array with all the properties and the giving the array name and the property of matching to the _.findWhere() function."
},
{
"code": null,
"e": 4652,
"s": 4641,
"text": "Example: "
},
{
"code": null,
"e": 4657,
"s": 4652,
"text": "HTML"
},
{
"code": "<html> <head> <title>_.findWhere() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> var users = [{\"num\":\"1\"}, {\"num\":\"2\"}, {\"num\":\"3\"}, {\"num\":\"4\"}, {\"num\":\"5\"}]; console.log(_.findWhere(users, {num:\"2\"})); </script> </body> </html>",
"e": 5219,
"s": 4657,
"text": null
},
{
"code": null,
"e": 5227,
"s": 5219,
"text": "Output:"
},
{
"code": null,
"e": 5246,
"s": 5229,
"text": "arorakashish0911"
},
{
"code": null,
"e": 5273,
"s": 5246,
"text": "JavaScript - Underscore.js"
},
{
"code": null,
"e": 5284,
"s": 5273,
"text": "JavaScript"
},
{
"code": null,
"e": 5291,
"s": 5284,
"text": "JQuery"
},
{
"code": null,
"e": 5308,
"s": 5291,
"text": "Web Technologies"
}
] |
Remove all occurrences of a character from a string using STL
|
21 Dec, 2021
Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string.
Examples:
Input:vS = “GFG IS FUN”, C = ‘F’ Output:GG IS UN Explanation: Removing all occurrences of the character ‘F’ modifies S to “GG IS UN”. Therefore, the required output is GG IS UN
Input: S = “PLEASE REMOVE THE SPACES”, C = ‘ ‘ Output: PLEASEREMOVETHESPACES Explanation: Removing all occurrences of the character ‘ ‘ modifies S to “GG IS UN”.
Approach: The idea is to use erase() method and remove() function from C++ STL. Below is the syntax to remove all the occurrences of a character from a string.
S.erase(remove(S.begin(), S.end(), c), S.end())
Below is the implementation of the above approach:
C++
// C++ program of the above approach#include <algorithm>#include <iostream>using namespace std; // Function to remove all occurrences// of C from the string Sstring removeCharacters(string S, char c){ S.erase(remove( S.begin(), S.end(), c), S.end()); return S;} // Driver Codeint main(){ // Given String string S = "GFG is Fun"; char C = 'F'; cout << "String Before: " << S << endl; // Function call S = removeCharacters(S, C); cout << "String After: " << S << endl; return 0;}
String Before: GFG is Fun
String After: GG is un
Time Complexity: O(N2)Auxiliary Space: O(1)
chhabradhanvi
cpp-strings-library
STL
Strings
Strings
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string."
},
{
"code": null,
"e": 158,
"s": 148,
"text": "Examples:"
},
{
"code": null,
"e": 335,
"s": 158,
"text": "Input:vS = “GFG IS FUN”, C = ‘F’ Output:GG IS UN Explanation: Removing all occurrences of the character ‘F’ modifies S to “GG IS UN”. Therefore, the required output is GG IS UN"
},
{
"code": null,
"e": 499,
"s": 335,
"text": "Input: S = “PLEASE REMOVE THE SPACES”, C = ‘ ‘ Output: PLEASEREMOVETHESPACES Explanation: Removing all occurrences of the character ‘ ‘ modifies S to “GG IS UN”. "
},
{
"code": null,
"e": 659,
"s": 499,
"text": "Approach: The idea is to use erase() method and remove() function from C++ STL. Below is the syntax to remove all the occurrences of a character from a string."
},
{
"code": null,
"e": 707,
"s": 659,
"text": "S.erase(remove(S.begin(), S.end(), c), S.end())"
},
{
"code": null,
"e": 758,
"s": 707,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 762,
"s": 758,
"text": "C++"
},
{
"code": "// C++ program of the above approach#include <algorithm>#include <iostream>using namespace std; // Function to remove all occurrences// of C from the string Sstring removeCharacters(string S, char c){ S.erase(remove( S.begin(), S.end(), c), S.end()); return S;} // Driver Codeint main(){ // Given String string S = \"GFG is Fun\"; char C = 'F'; cout << \"String Before: \" << S << endl; // Function call S = removeCharacters(S, C); cout << \"String After: \" << S << endl; return 0;}",
"e": 1301,
"s": 762,
"text": null
},
{
"code": null,
"e": 1350,
"s": 1301,
"text": "String Before: GFG is Fun\nString After: GG is un"
},
{
"code": null,
"e": 1396,
"s": 1352,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1410,
"s": 1396,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 1430,
"s": 1410,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 1434,
"s": 1430,
"text": "STL"
},
{
"code": null,
"e": 1442,
"s": 1434,
"text": "Strings"
},
{
"code": null,
"e": 1450,
"s": 1442,
"text": "Strings"
},
{
"code": null,
"e": 1454,
"s": 1450,
"text": "STL"
}
] |
How to create Stacked bar chart in Python-Plotly?
|
29 Oct, 2020
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A stacked bar chart or graph is a chart that uses bars to demonstrate comparisons between categories of data, but with ability to impart and compare parts of a whole. Each bar in the chart represents a whole and segments which represent different parts or categories of that whole.
Example 1: Using iris dataset
Python3
import plotly.express as px df = px.data.iris() fig = px.bar(df, x="sepal_width", y="sepal_length", color="species", hover_data=['petal_width'], barmode = 'stack') fig.show()
Output:
Example 2: Using tips dataset
Python3
import plotly.express as px df = px.data.tips() fig = px.bar(df, x="total_bill", y="day", color="sex", barmode = 'stack') fig.show()
Output:
Example 3: Using graph_objects class
Python3
import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) x = ['A', 'B', 'C', 'D'] plot = px.Figure(data=[go.Bar( name = 'Data 1', x = x, y = [100, 200, 500, 673] ), go.Bar( name = 'Data 2', x = x, y = [56, 123, 982, 213] )]) plot.update_layout(barmode='stack') plot.show()
Output:
barissenyerli
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 330,
"s": 28,
"text": "Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 613,
"s": 330,
"text": "A stacked bar chart or graph is a chart that uses bars to demonstrate comparisons between categories of data, but with ability to impart and compare parts of a whole. Each bar in the chart represents a whole and segments which represent different parts or categories of that whole."
},
{
"code": null,
"e": 643,
"s": 613,
"text": "Example 1: Using iris dataset"
},
{
"code": null,
"e": 651,
"s": 643,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.bar(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", hover_data=['petal_width'], barmode = 'stack') fig.show()",
"e": 837,
"s": 651,
"text": null
},
{
"code": null,
"e": 848,
"s": 840,
"text": "Output:"
},
{
"code": null,
"e": 882,
"s": 852,
"text": "Example 2: Using tips dataset"
},
{
"code": null,
"e": 892,
"s": 884,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.bar(df, x=\"total_bill\", y=\"day\", color=\"sex\", barmode = 'stack') fig.show()",
"e": 1037,
"s": 892,
"text": null
},
{
"code": null,
"e": 1048,
"s": 1040,
"text": "Output:"
},
{
"code": null,
"e": 1089,
"s": 1052,
"text": "Example 3: Using graph_objects class"
},
{
"code": null,
"e": 1099,
"s": 1091,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) x = ['A', 'B', 'C', 'D'] plot = px.Figure(data=[go.Bar( name = 'Data 1', x = x, y = [100, 200, 500, 673] ), go.Bar( name = 'Data 2', x = x, y = [56, 123, 982, 213] )]) plot.update_layout(barmode='stack') plot.show()",
"e": 1591,
"s": 1099,
"text": null
},
{
"code": null,
"e": 1602,
"s": 1594,
"text": "Output:"
},
{
"code": null,
"e": 1620,
"s": 1606,
"text": "barissenyerli"
},
{
"code": null,
"e": 1634,
"s": 1620,
"text": "Python-Plotly"
},
{
"code": null,
"e": 1641,
"s": 1634,
"text": "Python"
}
] |
jQuery | load() with Examples
|
13 Feb, 2019
jQuery load() method is simple but very powerful AJAX method. The Load() method in jQuery helps to load data from server and returned into selected element without loading the whole page.
Syntax:
$(selector).load(URL, data, callback);
Parameters: This method accepts three parameter as mentioned above and described below:
URL: It is used to specify the URL which need to load.
data: It is used to specify a set of query key/value pairs to send along with the request.
callback: It is the optional parameter which is the name of a function to be executed after the load() method is call.
Return Value: This method returns the requested data from server with the specified URL.
Example:
The geeks.txt file stored on server and it will load after clicking the click button. The content of geeks.txt are:Hello GeeksforGeeks!
Program 1:
<!DOCTYPE html><html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div_content").load("gfg.txt"); }); }); </script> <style> body { text-align: center; } .gfg { font-size:40px; font-weight: bold; color: green; } .geeks { font-size:17px; color: black; } #div_content { font-size: 40px; font-weight: bold; color: green; } </style> </head> <body> <div id="div_content"> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> </div> <button>Change Content</button> </body></html>
Output :
There is also an additional callback function in the parameter which will run when the load() method is completed. This callback function has three different parameters:
parameter 1: It contains the result of the content if the method call succeeds.
parameter 2: It contains the status of the call function.
parameter 3: It contains the XMLHttpRequest object.
Program 2:
<html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div_content").load("gfg.txt", function(response, status, http){ if(status == "success") alert("Content loaded successfully!"); if(status == "error") alert("Error: " + http.status + ": " + http.statusText); }); }); }); </script> <style> body { text-align: center; } .gfg { font-size:40px; font-weight: bold; color: green; } .geeks { font-size:17px; color: black; } #div_content { font-size: 40px; font-weight: bold; color: green; } </style> </head> <body> <div id="div_content"> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> </div> <button>Change Content</button> </body></html>
Output:Output of the given code followed an alert box that will appear after click on the button and if the content loaded successfully then it will give a message “Content loaded successfully!”. Otherwise it will show an error message.
jQuery-Events
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "jQuery load() method is simple but very powerful AJAX method. The Load() method in jQuery helps to load data from server and returned into selected element without loading the whole page."
},
{
"code": null,
"e": 224,
"s": 216,
"text": "Syntax:"
},
{
"code": null,
"e": 263,
"s": 224,
"text": "$(selector).load(URL, data, callback);"
},
{
"code": null,
"e": 351,
"s": 263,
"text": "Parameters: This method accepts three parameter as mentioned above and described below:"
},
{
"code": null,
"e": 406,
"s": 351,
"text": "URL: It is used to specify the URL which need to load."
},
{
"code": null,
"e": 497,
"s": 406,
"text": "data: It is used to specify a set of query key/value pairs to send along with the request."
},
{
"code": null,
"e": 616,
"s": 497,
"text": "callback: It is the optional parameter which is the name of a function to be executed after the load() method is call."
},
{
"code": null,
"e": 705,
"s": 616,
"text": "Return Value: This method returns the requested data from server with the specified URL."
},
{
"code": null,
"e": 714,
"s": 705,
"text": "Example:"
},
{
"code": null,
"e": 850,
"s": 714,
"text": "The geeks.txt file stored on server and it will load after clicking the click button. The content of geeks.txt are:Hello GeeksforGeeks!"
},
{
"code": null,
"e": 861,
"s": 850,
"text": "Program 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function(){ $(\"button\").click(function(){ $(\"#div_content\").load(\"gfg.txt\"); }); }); </script> <style> body { text-align: center; } .gfg { font-size:40px; font-weight: bold; color: green; } .geeks { font-size:17px; color: black; } #div_content { font-size: 40px; font-weight: bold; color: green; } </style> </head> <body> <div id=\"div_content\"> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> </div> <button>Change Content</button> </body></html>",
"e": 1907,
"s": 861,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1907,
"text": "Output :"
},
{
"code": null,
"e": 2086,
"s": 1916,
"text": "There is also an additional callback function in the parameter which will run when the load() method is completed. This callback function has three different parameters:"
},
{
"code": null,
"e": 2166,
"s": 2086,
"text": "parameter 1: It contains the result of the content if the method call succeeds."
},
{
"code": null,
"e": 2224,
"s": 2166,
"text": "parameter 2: It contains the status of the call function."
},
{
"code": null,
"e": 2276,
"s": 2224,
"text": "parameter 3: It contains the XMLHttpRequest object."
},
{
"code": null,
"e": 2287,
"s": 2276,
"text": "Program 2:"
},
{
"code": "<html> <head> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function(){ $(\"button\").click(function(){ $(\"#div_content\").load(\"gfg.txt\", function(response, status, http){ if(status == \"success\") alert(\"Content loaded successfully!\"); if(status == \"error\") alert(\"Error: \" + http.status + \": \" + http.statusText); }); }); }); </script> <style> body { text-align: center; } .gfg { font-size:40px; font-weight: bold; color: green; } .geeks { font-size:17px; color: black; } #div_content { font-size: 40px; font-weight: bold; color: green; } </style> </head> <body> <div id=\"div_content\"> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> </div> <button>Change Content</button> </body></html>",
"e": 3691,
"s": 2287,
"text": null
},
{
"code": null,
"e": 3928,
"s": 3691,
"text": "Output:Output of the given code followed an alert box that will appear after click on the button and if the content loaded successfully then it will give a message “Content loaded successfully!”. Otherwise it will show an error message."
},
{
"code": null,
"e": 3942,
"s": 3928,
"text": "jQuery-Events"
},
{
"code": null,
"e": 3946,
"s": 3942,
"text": "CSS"
},
{
"code": null,
"e": 3951,
"s": 3946,
"text": "HTML"
},
{
"code": null,
"e": 3958,
"s": 3951,
"text": "JQuery"
},
{
"code": null,
"e": 3975,
"s": 3958,
"text": "Web Technologies"
},
{
"code": null,
"e": 3980,
"s": 3975,
"text": "HTML"
}
] |
Python - HTTP Requests
|
The http or Hyper Text Transfer Protocol works on client server model. Usually the web browser is the client and the computer hosting the website is the
server. IN python we use the requests module for creating the http requests. It is a very powerful module which can handle many aspects of http communication beyond the
simple request and response data. It can handle authentication, compression/decompression, chunked requests etc.
An HTTP client sends an HTTP request to a server in the form of a request message which includes following format:
A Request-line
Zero or more header (General|Request|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF)
indicating the end of the header fields
Optionally a message-body
The following sections explain each of the entities used in an HTTP request message.
The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by space SP characters.
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
Let's discuss each of the parts mentioned in the Request-Line.
The request method indicates the method to be performed on the resource identified by the given Request-URI. The method is case-sensitive and should always be mentioned in uppercase. The following table lists all the supported methods in HTTP/1.1.
The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.
Same as GET, but it transfers the status line and the header section only.
A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms.
Replaces all the current representations of the target resource with the uploaded content.
Removes all the current representations of the target resource given by URI.
Establishes a tunnel to the server identified by a given URI.
Describe the communication options for the target resource.
Performs a message loop back test along with the path to the target resource.
The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply the request. Following are the most commonly used forms to specify an URI:
Request-URI = "*" | absoluteURI | abs_path | authority
OPTIONS * HTTP/1.1
GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.w3.org
Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as "/" (the server root).
We will use the module requests for learning about http request.
pip install requests
In the below example we see a case of simple GET request annd print out the result of the response. We choose to print only the first 300 characters.
# How to make http request
import requests as req
r = req.get('http://www.tutorialspoint.com/python/')
print(r.text)[0:300]
When we run the above program, we get the following output −
<!DOCTYPE html>
<!--[if IE 8]><html class="ie ie8"> <![endif]-->
<!--[if IE 9]><html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!--> <html> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset="utf-8">
<title>Python Tutorial</title>
<meta name="description" content="Python Tutorial
|
[
{
"code": null,
"e": 2898,
"s": 2460,
"text": "The http or Hyper Text Transfer Protocol works on client server model. Usually the web browser is the client and the computer hosting the website is the \nserver. IN python we use the requests module for creating the http requests. It is a very powerful module which can handle many aspects of http communication beyond the \nsimple request and response data. It can handle authentication, compression/decompression, chunked requests etc. "
},
{
"code": null,
"e": 3013,
"s": 2898,
"text": "An HTTP client sends an HTTP request to a server in the form of a request message which includes following format:"
},
{
"code": null,
"e": 3028,
"s": 3013,
"text": "A Request-line"
},
{
"code": null,
"e": 3097,
"s": 3028,
"text": "Zero or more header (General|Request|Entity) fields followed by CRLF"
},
{
"code": null,
"e": 3199,
"s": 3097,
"text": "An empty line (i.e., a line with nothing preceding the CRLF) \nindicating the end of the header fields"
},
{
"code": null,
"e": 3225,
"s": 3199,
"text": "Optionally a message-body"
},
{
"code": null,
"e": 3310,
"s": 3225,
"text": "The following sections explain each of the entities used in an HTTP request message."
},
{
"code": null,
"e": 3482,
"s": 3310,
"text": "The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by space SP characters."
},
{
"code": null,
"e": 3541,
"s": 3482,
"text": "Request-Line = Method SP Request-URI SP HTTP-Version CRLF\n"
},
{
"code": null,
"e": 3604,
"s": 3541,
"text": "Let's discuss each of the parts mentioned in the Request-Line."
},
{
"code": null,
"e": 3852,
"s": 3604,
"text": "The request method indicates the method to be performed on the resource identified by the given Request-URI. The method is case-sensitive and should always be mentioned in uppercase. The following table lists all the supported methods in HTTP/1.1."
},
{
"code": null,
"e": 4032,
"s": 3852,
"text": "The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data."
},
{
"code": null,
"e": 4107,
"s": 4032,
"text": "Same as GET, but it transfers the status line and the header section only."
},
{
"code": null,
"e": 4229,
"s": 4107,
"text": "A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms."
},
{
"code": null,
"e": 4320,
"s": 4229,
"text": "Replaces all the current representations of the target resource with the uploaded content."
},
{
"code": null,
"e": 4397,
"s": 4320,
"text": "Removes all the current representations of the target resource given by URI."
},
{
"code": null,
"e": 4459,
"s": 4397,
"text": "Establishes a tunnel to the server identified by a given URI."
},
{
"code": null,
"e": 4519,
"s": 4459,
"text": "Describe the communication options for the target resource."
},
{
"code": null,
"e": 4597,
"s": 4519,
"text": "Performs a message loop back test along with the path to the target resource."
},
{
"code": null,
"e": 4769,
"s": 4597,
"text": "The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply the request. Following are the most commonly used forms to specify an URI:"
},
{
"code": null,
"e": 4825,
"s": 4769,
"text": "Request-URI = \"*\" | absoluteURI | abs_path | authority\n"
},
{
"code": null,
"e": 4844,
"s": 4825,
"text": "OPTIONS * HTTP/1.1"
},
{
"code": null,
"e": 4899,
"s": 4844,
"text": "GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1"
},
{
"code": null,
"e": 4937,
"s": 4899,
"text": "GET /pub/WWW/TheProject.html HTTP/1.1"
},
{
"code": null,
"e": 4954,
"s": 4937,
"text": "Host: www.w3.org"
},
{
"code": null,
"e": 5082,
"s": 4954,
"text": "Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as \"/\" (the server root)."
},
{
"code": null,
"e": 5147,
"s": 5082,
"text": "We will use the module requests for learning about http request."
},
{
"code": null,
"e": 5169,
"s": 5147,
"text": "pip install requests "
},
{
"code": null,
"e": 5319,
"s": 5169,
"text": "In the below example we see a case of simple GET request annd print out the result of the response. We choose to print only the first 300 characters."
},
{
"code": null,
"e": 5443,
"s": 5319,
"text": "# How to make http request\nimport requests as req\nr = req.get('http://www.tutorialspoint.com/python/')\nprint(r.text)[0:300]"
},
{
"code": null,
"e": 5504,
"s": 5443,
"text": "When we run the above program, we get the following output −"
}
] |
Maximum profit by buying and selling a share at most twice
|
In a trading, one buyer buys and sells the shares, at morning and the evening respectively. If at most two transactions are allowed in a day. The second transaction can only start after the first one is completed. If stock prices are given, then find the maximum profit that the buyer can make.
Input:
A list of stock prices. {2, 30, 15, 10, 8, 25, 80}
Output:
Here the total profit is 100. As buying at price 2 and selling at price 30.
so profit 28. Then buy at price 8 and sell it again at price 80.
So profit 72. So the total profit 28 + 72 = 100
findMaxProfit(pricelist, n)
Input − List of all prices, number of items in the list.
Output − Maximum Profit.
Begin
define profit array of size n and fill with 0
maxPrice := pricelist[n-1] //last item is chosen
for i := n-2 down to 0, do
if pricelist[i] > maxPrice, then
maxPrice := pricelist[i]
profit[i] := maximum of profit[i+1] and maxProfit – pricelist[i]
done
minProce := pricelist[0] //first item is chosen
for i := 1 to n-1, do
if pricelist[i] < minPrice, then
minPrice := pricelist[i]
profit[i] := maximum of profit[i-1] and (profit[i]+(pricelist[i] - minPrice))
done
return profit[n-1]
End
#include<iostream>
using namespace std;
int max(int a, int b) {
return (a>b)?a:b;
}
int findMaxProfit(int priceList[], int n) {
int *profit = new int[n];
for (int i=0; i<n; i++) //initialize profit list with 0
profit[i] = 0;
int maxPrice = priceList[n-1]; //initialize with last element of price list
for (int i=n-2;i>=0;i--) {
if (priceList[i] > maxPrice)
maxPrice = priceList[i];
profit[i] = max(profit[i+1], maxPrice - priceList[i]); //find the profit for selling in maxPrice
}
int minPrice = priceList[0]; //first item of priceList as minimum
for (int i=1; i<n; i++) {
if (priceList[i] < minPrice)
minPrice = priceList[i];
profit[i] = max(profit[i-1], profit[i] + (priceList[i]- minPrice) );
}
int result = profit[n-1];
return result;
}
int main() {
int priceList[] = {2, 30, 15, 10, 8, 25, 80};
int n = 7;
cout << "Maximum Profit = " << findMaxProfit(priceList, n);
}
Maximum Profit = 100
|
[
{
"code": null,
"e": 1357,
"s": 1062,
"text": "In a trading, one buyer buys and sells the shares, at morning and the evening respectively. If at most two transactions are allowed in a day. The second transaction can only start after the first one is completed. If stock prices are given, then find the maximum profit that the buyer can make."
},
{
"code": null,
"e": 1612,
"s": 1357,
"text": "Input:\nA list of stock prices. {2, 30, 15, 10, 8, 25, 80}\nOutput:\nHere the total profit is 100. As buying at price 2 and selling at price 30.\nso profit 28. Then buy at price 8 and sell it again at price 80.\nSo profit 72. So the total profit 28 + 72 = 100"
},
{
"code": null,
"e": 1640,
"s": 1612,
"text": "findMaxProfit(pricelist, n)"
},
{
"code": null,
"e": 1697,
"s": 1640,
"text": "Input − List of all prices, number of items in the list."
},
{
"code": null,
"e": 1722,
"s": 1697,
"text": "Output − Maximum Profit."
},
{
"code": null,
"e": 2302,
"s": 1722,
"text": "Begin\n define profit array of size n and fill with 0\n maxPrice := pricelist[n-1] //last item is chosen\n\n for i := n-2 down to 0, do\n if pricelist[i] > maxPrice, then\n maxPrice := pricelist[i]\n profit[i] := maximum of profit[i+1] and maxProfit – pricelist[i]\n done\n\n minProce := pricelist[0] //first item is chosen\n for i := 1 to n-1, do\n if pricelist[i] < minPrice, then\n minPrice := pricelist[i]\n profit[i] := maximum of profit[i-1] and (profit[i]+(pricelist[i] - minPrice))\n done\n\n return profit[n-1]\nEnd\n\n"
},
{
"code": null,
"e": 3308,
"s": 2302,
"text": "#include<iostream>\nusing namespace std;\n\nint max(int a, int b) {\n return (a>b)?a:b;\n}\n\nint findMaxProfit(int priceList[], int n) {\n int *profit = new int[n];\n for (int i=0; i<n; i++) //initialize profit list with 0\n profit[i] = 0;\n\n int maxPrice = priceList[n-1]; //initialize with last element of price list\n\n for (int i=n-2;i>=0;i--) {\n if (priceList[i] > maxPrice)\n maxPrice = priceList[i];\n\n profit[i] = max(profit[i+1], maxPrice - priceList[i]); //find the profit for selling in maxPrice\n }\n\n int minPrice = priceList[0]; //first item of priceList as minimum\n\n for (int i=1; i<n; i++) {\n if (priceList[i] < minPrice)\n minPrice = priceList[i];\n\n profit[i] = max(profit[i-1], profit[i] + (priceList[i]- minPrice) );\n }\n\n int result = profit[n-1];\n return result;\n}\n\nint main() {\n int priceList[] = {2, 30, 15, 10, 8, 25, 80};\n int n = 7;\n cout << \"Maximum Profit = \" << findMaxProfit(priceList, n);\n}"
},
{
"code": null,
"e": 3329,
"s": 3308,
"text": "Maximum Profit = 100"
}
] |
Queries to check if string B exists as substring in string A - GeeksforGeeks
|
15 Nov, 2021
Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) – 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A).
Examples:
Input: A = “abababa”, B = “aba”, q[] = {0, 1, 2, 3} Output: Yes No Yes No a[0-2] = “aba” = b (both are equal) a[1-3] = “bab” != b a[2-4] = “aba” = b a[3-5] = “bab” !=b
Input: A = “GeeksForGeeks”, B = “Geeks”, q[] = {0, 5, 8} Output: Yes No Yes
A simple approach will be to compare the strings character by character for every query which will take O(length(B)) time to answer each query.
Efficient approach: We will optimize the query processing using rolling hash algorithm. First, we will find hash value of string B. Then, using rolling hash technique, we will do the pre-processing of string A. Let’s suppose we created an array hash_A. Then ith element of this array will store.
((a[0] – 97) + (a[1] – 97) * d + (a[2] – 97) * d2 + ..... + (a[i] – 97) * di) % mod where d is the multiplier in rolling-hash.
We will use this to find hash of the sub-string of A.
Hash of sub-string of A starting from i can be found as (hash_a[i + len_b – 1] – hash_a[i – 1]) / di or more specifically
((hash_a[i + len_b – 1] – hash_a[i – 1] + 2 * mod) * mi(di)) % mod
Thus, using this we can answer each query in O(1).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>#define mod 3803#define d 26using namespace std; int hash_b;int* hash_a;int* mul; // Function to return the modular inverse// using Fermat's little theoremint mi(int x){ int p = mod - 2; int s = 1; while (p != 1) { if (p % 2 == 1) s = (s * x) % mod; x = (x * x) % mod; p /= 2; } return (s * x) % mod;} // Function to generate hashvoid genHash(string& a, string& b){ // To store prefix-sum // of rolling hash hash_a = new int[a.size()]; // Multiplier for different values of i mul = new int[a.size()]; // Generating hash value for string b for (int i = b.size() - 1; i >= 0; i--) hash_b = (hash_b * d + (b[i] - 97)) % mod; // Generating prefix-sum of hash of a mul[0] = 1; hash_a[0] = (a[0] - 97) % mod; for (int i = 1; i < a.size(); i++) { mul[i] = (mul[i - 1] * d) % mod; hash_a[i] = (hash_a[i - 1] + mul[i] * (a[i] - 97)) % mod; }} // Function that returns true if the// required sub-string in a is equal to bbool checkEqual(int i, int len_a, int len_b){ // To store hash of required // sub-string of A int x; // If i = 0 then // requires hash value if (i == 0) x = hash_a[len_b - 1]; // Required hash if i != 0 else { x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod; x = (x * mi(mul[i])) % mod; } // Comparing hash with hash of B if (x == hash_b) return true; return false;} // Driver codeint main(){ string a = "abababababa"; string b = "aba"; // Generating hash genHash(a, b); // Queries int queries[] = { 0, 1, 2, 3 }; int q = sizeof(queries) / sizeof(queries[0]); // Perform queries for (int i = 0; i < q; i++) { if (checkEqual(queries[i], a.size(), b.size())) cout << "Yes\n"; else cout << "No\n"; } return 0;}
// Java implementation of the approachimport java.util.*; class GFG { static int mod = 3803; static int d = 26; static int hash_b; static int[] hash_a; static int[] mul; // Function to return the modular inverse // using Fermat's little theorem static int mi(int x) { int p = mod - 2; int s = 1; while (p != 1) { if (p % 2 == 1) { s = (s * x) % mod; } x = (x * x) % mod; p /= 2; } return (s * x) % mod; } // Function to generate hash static void genHash(char[] a, char[] b) { // To store prefix-sum // of rolling hash hash_a = new int[a.length]; // Multiplier for different values of i mul = new int[a.length]; // Generating hash value for string b for (int i = b.length - 1; i >= 0; i--) { hash_b = (hash_b * d + (b[i] - 97)) % mod; } // Generating prefix-sum of hash of a mul[0] = 1; hash_a[0] = (a[0] - 97) % mod; for (int i = 1; i < a.length; i++) { mul[i] = (mul[i - 1] * d) % mod; hash_a[i] = (hash_a[i - 1] + mul[i] * (a[i] - 97)) % mod; } } // Function that returns true if the // required sub-string in a is equal to b static boolean checkEqual(int i, int len_a, int len_b) { // To store hash of required // sub-string of A int x; // If i = 0 then // requires hash value if (i == 0) { x = hash_a[len_b - 1]; } // Required hash if i != 0 else { x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod; x = (x * mi(mul[i])) % mod; } // Comparing hash with hash of B if (x == hash_b) { return true; } return false; } // Driver code public static void main(String[] args) { String a = "abababababa"; String b = "aba"; // Generating hash genHash(a.toCharArray(), b.toCharArray()); // Queries int queries[] = { 0, 1, 2, 3 }; int q = queries.length; // Perform queries for (int i = 0; i < q; i++) { if (checkEqual(queries[i], a.length(), b.length())) { System.out.println("Yes"); } else { System.out.println("No"); } } }} /* This code is contributed by PrinciRaj1992 */
# Python3 implementation of the approachmod = 3803d = 26 hash_b = 0hash_a = []mul = [] # Function to return the modular inverse# using Fermat's little theorem def mi(x): global mod p = mod - 2 s = 1 while p != 1: if p % 2 == 1: s = (s * x) % mod x = (x * x) % mod p //= 2 return (s * x) % mod # Function to generate hash def genHash(a, b): global hash_b, hash_a, mul, d, mod # To store prefix-sum # of rolling hash hash_a = [0] * len(a) # Multiplier for different values of i mul = [0] * len(a) # Generating hash value for string b for i in range(len(b) - 1, -1, -1): hash_b = (hash_b * d + (ord(b[i]) - 97)) % mod # Generating prefix-sum of hash of a mul[0] = 1 hash_a[0] = (ord(a[0]) - 97) % mod for i in range(1, len(a)): mul[i] = (mul[i - 1] * d) % mod hash_a[i] = (hash_a[i - 1] + mul[i] * (ord(a[i]) - 97)) % mod # Function that returns true if the# required sub-string in a is equal to b def checkEqual(i, len_a, len_b): global hash_b, hash_a, mul, d, mod # To store hash of required # sub-string of A x = -1 # If i = 0 then # requires hash value if i == 0: x = hash_a[len_b - 1] # Required hash if i != 0 else: x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod x = (x * mi(mul[i])) % mod # Comparing hash with hash of B if x == hash_b: return True return False # Driver Codeif __name__ == "__main__": a = "abababababa" b = "aba" # Generating hash genHash(a, b) # Queries queries = [0, 1, 2, 3] q = len(queries) # Perform queries for i in range(q): if checkEqual(queries[i], len(a), len(b)): print("Yes") else: print("No") # This code is contributed by# sanjeev2552
// C# implementation of the approachusing System; class GFG { static int mod = 3803; static int d = 26; static int hash_b; static int[] hash_a; static int[] mul; // Function to return the modular inverse // using Fermat's little theorem static int mi(int x) { int p = mod - 2; int s = 1; while (p != 1) { if (p % 2 == 1) { s = (s * x) % mod; } x = (x * x) % mod; p /= 2; } return (s * x) % mod; } // Function to generate hash static void genHash(char[] a, char[] b) { // To store prefix-sum // of rolling hash hash_a = new int[a.Length]; // Multiplier for different values of i mul = new int[a.Length]; // Generating hash value for string b for (int i = b.Length - 1; i >= 0; i--) { hash_b = (hash_b * d + (b[i] - 97)) % mod; } // Generating prefix-sum of hash of a mul[0] = 1; hash_a[0] = (a[0] - 97) % mod; for (int i = 1; i < a.Length; i++) { mul[i] = (mul[i - 1] * d) % mod; hash_a[i] = (hash_a[i - 1] + mul[i] * (a[i] - 97)) % mod; } } // Function that returns true if the // required sub-string in a is equal to b static Boolean checkEqual(int i, int len_a, int len_b) { // To store hash of required // sub-string of A int x; // If i = 0 then // requires hash value if (i == 0) { x = hash_a[len_b - 1]; } // Required hash if i != 0 else { x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod; x = (x * mi(mul[i])) % mod; } // Comparing hash with hash of B if (x == hash_b) { return true; } return false; } // Driver code public static void Main(String[] args) { String a = "abababababa"; String b = "aba"; // Generating hash genHash(a.ToCharArray(), b.ToCharArray()); // Queries int[] queries = { 0, 1, 2, 3 }; int q = queries.Length; // Perform queries for (int i = 0; i < q; i++) { if (checkEqual(queries[i], a.Length, b.Length)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } }} /* This code contributed by PrinciRaj1992 */
<script> // Javascript implementation of the approachvar mod = 3803;var d = 26; var hash_b = 0;var hash_a = [];var mul = []; // Function to return the modular inverse// using Fermat's little theoremfunction mi(x){ var p = mod - 2; var s = 1; while (p != 1) { if (p % 2 == 1) s = (s * x) % mod; x = (x * x) % mod; p = parseInt(p/2); } return (s * x) % mod;} // Function to generate hashfunction genHash(a, b){ // To store prefix-sum // of rolling hash hash_a = Array(a.length).fill(0); // Multiplier for different values of i mul = Array(a.length).fill(0); // Generating hash value for string b for (var i = b.length - 1; i >= 0; i--) hash_b = (hash_b * d + (b[i].charCodeAt(0) - 97)) % mod; // Generating prefix-sum of hash of a mul[0] = 1; hash_a[0] = (a[0].charCodeAt(0) - 97) % mod; for (var i = 1; i < a.length; i++) { mul[i] = (mul[i - 1] * d) % mod; hash_a[i] = (hash_a[i - 1] + mul[i] * (a[i].charCodeAt(0) - 97)) % mod; }} // Function that returns true if the// required sub-string in a is equal to bfunction checkEqual(i, len_a, len_b){ // To store hash of required // sub-string of A var x; // If i = 0 then // requires hash value if (i == 0) x = hash_a[len_b - 1]; // Required hash if i != 0 else { x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod; x = (x * mi(mul[i])) % mod; } // Comparing hash with hash of B if (x == hash_b) return true; return false;} // Driver codevar a = "abababababa";var b = "aba"; // Generating hashgenHash(a.split(''), b.split('')); // Queriesvar queries = [0, 1, 2, 3];var q = queries.length // Perform queriesfor (var i = 0; i < q; i++) { if (checkEqual(queries[i], a.length, b.length)) document.write("Yes<br>"); else document.write("No<br>");} // This code is contributed by rrrtnx.</script>
Yes
No
Yes
No
Note: For simplicity, we have used only one hash function. Use double/triple hash to eliminate any chance of collision and more accurate result.
The above question can be solved by using DP also, below is the java code.
Java
C#
Javascript
import java.io.*;import java.util.*;import java.lang.*;import java.io.*; public class GFG{ private static void substringCheck(String stra, String strb, int[] query) { // Dp Array int[][] matrix = new int[strb.length()][stra.length()]; // String to character array char[] charCrr = stra.toCharArray(); char[] charRrr = strb.toCharArray(); // initialize matrix with 1 for (int c = 0; c < stra.length(); c++) { if (charRrr[0] == charCrr) { matrix[0] = 1; } } // for r from 1 to string length for (int r = 1; r < charRrr.length; r++) { char ch = charRrr[r]; // for c from 1 b string length for (int c = 1; c < charCrr.length; c++) { if (ch == charCrr && matrix[r - 1] == 1) { matrix[r] = 1; } } } // For every query for (int q : query) { int matLoc = (q + (strb.length() - 1)); if (matLoc >= stra.length()) { System.out.println(false); } else { // print true if (matrix[strb.length() - 1][matLoc] == 1) { System.out.println(true); } else { // print false System.out.println(false); } } } } // Driver Code public static void main(String[] args) { String stra = "GeeksForGeeks"; String strb = "Geeks"; int[] query = { 0,5,8 }; substringCheck(stra, strb, query); } } // class// Code contributed by Swapnil Gupta
using System; public class GFG { private static void substringCheck(string stra, string strb, int[] query) { // Dp Array int[, ] matrix = new int[strb.Length, stra.Length]; // String to character array char[] charCrr = stra.ToCharArray(); char[] charRrr = strb.ToCharArray(); // initialize matrix with 1 for (int c = 0; c < stra.Length; c++) { if (charRrr[0] == charCrr) { matrix[0, c] = 1; } } // for r from 1 to string length for (int r = 1; r < charRrr.Length; r++) { char ch = charRrr[r]; // for c from 1 b string length for (int c = 1; c < charCrr.Length; c++) { if (ch == charCrr && matrix[r - 1, c - 1] == 1) { matrix[r, c] = 1; } } } // For every query foreach(int q in query) { int matLoc = (q + (strb.Length - 1)); if (matLoc >= stra.Length) { Console.WriteLine(false); } else { // print true if (matrix[strb.Length - 1, matLoc] == 1) { Console.WriteLine(true); } else { // print false Console.WriteLine(false); } } } } // Driver Code public static void Main(string[] args) { string stra = "GeeksForGeeks"; string strb = "Geeks"; int[] query = { 0, 5, 8 }; substringCheck(stra, strb, query); }} // This code is contributed by ukasp.
<script> function substringCheck(stra, strb, query){ // Dp Array var matrix = Array.from(Array(strb.length), ()=>Array(stra.length)); // String to character array var charCrr = stra.split(''); var charRrr = strb.split(''); // initialize matrix with 1 for (var c = 0; c < stra.length; c++) { if (charRrr[0] == charCrr) { matrix[0] = 1; } } // for r from 1 to string length for (var r = 1; r < charRrr.length; r++) { var ch = charRrr[r]; // for c from 1 b string length for (var c = 1; c < charCrr.length; c++) { if (ch == charCrr && matrix[r - 1] == 1) { matrix[r] = 1; } } } // For every query for (var q of query) { var matLoc = (q + (strb.length - 1)); if (matLoc >= stra.length) { document.write(false + "<br>"); } else { // print true if (matrix[strb.length - 1][matLoc] == 1) { document.write(true+ "<br>"); } else { // print false document.write(false+ "<br>"); } } }} // Driver Codevar stra = "GeeksForGeeks";var strb = "Geeks";var query = [0,5,8];substringCheck(stra, strb, query); // This code is contributed by rutvik_56.</script>
true
false
true
Time Complexity: O(M*N)
princiraj1992
sanjeev2552
gswapnil246
kk773572498
ukasp
rrrtnx
rutvik_56
Hash
substring
Dynamic Programming
Strings
Hash
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Matrix Chain Multiplication | DP-8
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 25202,
"s": 25174,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 25498,
"s": 25202,
"text": "Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) – 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A)."
},
{
"code": null,
"e": 25509,
"s": 25498,
"text": "Examples: "
},
{
"code": null,
"e": 25677,
"s": 25509,
"text": "Input: A = “abababa”, B = “aba”, q[] = {0, 1, 2, 3} Output: Yes No Yes No a[0-2] = “aba” = b (both are equal) a[1-3] = “bab” != b a[2-4] = “aba” = b a[3-5] = “bab” !=b"
},
{
"code": null,
"e": 25755,
"s": 25677,
"text": "Input: A = “GeeksForGeeks”, B = “Geeks”, q[] = {0, 5, 8} Output: Yes No Yes "
},
{
"code": null,
"e": 25899,
"s": 25755,
"text": "A simple approach will be to compare the strings character by character for every query which will take O(length(B)) time to answer each query."
},
{
"code": null,
"e": 26196,
"s": 25899,
"text": "Efficient approach: We will optimize the query processing using rolling hash algorithm. First, we will find hash value of string B. Then, using rolling hash technique, we will do the pre-processing of string A. Let’s suppose we created an array hash_A. Then ith element of this array will store. "
},
{
"code": null,
"e": 26324,
"s": 26196,
"text": "((a[0] – 97) + (a[1] – 97) * d + (a[2] – 97) * d2 + ..... + (a[i] – 97) * di) % mod where d is the multiplier in rolling-hash. "
},
{
"code": null,
"e": 26379,
"s": 26324,
"text": "We will use this to find hash of the sub-string of A. "
},
{
"code": null,
"e": 26502,
"s": 26379,
"text": "Hash of sub-string of A starting from i can be found as (hash_a[i + len_b – 1] – hash_a[i – 1]) / di or more specifically "
},
{
"code": null,
"e": 26570,
"s": 26502,
"text": "((hash_a[i + len_b – 1] – hash_a[i – 1] + 2 * mod) * mi(di)) % mod "
},
{
"code": null,
"e": 26621,
"s": 26570,
"text": "Thus, using this we can answer each query in O(1)."
},
{
"code": null,
"e": 26673,
"s": 26621,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26677,
"s": 26673,
"text": "C++"
},
{
"code": null,
"e": 26682,
"s": 26677,
"text": "Java"
},
{
"code": null,
"e": 26690,
"s": 26682,
"text": "Python3"
},
{
"code": null,
"e": 26693,
"s": 26690,
"text": "C#"
},
{
"code": null,
"e": 26704,
"s": 26693,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>#define mod 3803#define d 26using namespace std; int hash_b;int* hash_a;int* mul; // Function to return the modular inverse// using Fermat's little theoremint mi(int x){ int p = mod - 2; int s = 1; while (p != 1) { if (p % 2 == 1) s = (s * x) % mod; x = (x * x) % mod; p /= 2; } return (s * x) % mod;} // Function to generate hashvoid genHash(string& a, string& b){ // To store prefix-sum // of rolling hash hash_a = new int[a.size()]; // Multiplier for different values of i mul = new int[a.size()]; // Generating hash value for string b for (int i = b.size() - 1; i >= 0; i--) hash_b = (hash_b * d + (b[i] - 97)) % mod; // Generating prefix-sum of hash of a mul[0] = 1; hash_a[0] = (a[0] - 97) % mod; for (int i = 1; i < a.size(); i++) { mul[i] = (mul[i - 1] * d) % mod; hash_a[i] = (hash_a[i - 1] + mul[i] * (a[i] - 97)) % mod; }} // Function that returns true if the// required sub-string in a is equal to bbool checkEqual(int i, int len_a, int len_b){ // To store hash of required // sub-string of A int x; // If i = 0 then // requires hash value if (i == 0) x = hash_a[len_b - 1]; // Required hash if i != 0 else { x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod; x = (x * mi(mul[i])) % mod; } // Comparing hash with hash of B if (x == hash_b) return true; return false;} // Driver codeint main(){ string a = \"abababababa\"; string b = \"aba\"; // Generating hash genHash(a, b); // Queries int queries[] = { 0, 1, 2, 3 }; int q = sizeof(queries) / sizeof(queries[0]); // Perform queries for (int i = 0; i < q; i++) { if (checkEqual(queries[i], a.size(), b.size())) cout << \"Yes\\n\"; else cout << \"No\\n\"; } return 0;}",
"e": 28679,
"s": 26704,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG { static int mod = 3803; static int d = 26; static int hash_b; static int[] hash_a; static int[] mul; // Function to return the modular inverse // using Fermat's little theorem static int mi(int x) { int p = mod - 2; int s = 1; while (p != 1) { if (p % 2 == 1) { s = (s * x) % mod; } x = (x * x) % mod; p /= 2; } return (s * x) % mod; } // Function to generate hash static void genHash(char[] a, char[] b) { // To store prefix-sum // of rolling hash hash_a = new int[a.length]; // Multiplier for different values of i mul = new int[a.length]; // Generating hash value for string b for (int i = b.length - 1; i >= 0; i--) { hash_b = (hash_b * d + (b[i] - 97)) % mod; } // Generating prefix-sum of hash of a mul[0] = 1; hash_a[0] = (a[0] - 97) % mod; for (int i = 1; i < a.length; i++) { mul[i] = (mul[i - 1] * d) % mod; hash_a[i] = (hash_a[i - 1] + mul[i] * (a[i] - 97)) % mod; } } // Function that returns true if the // required sub-string in a is equal to b static boolean checkEqual(int i, int len_a, int len_b) { // To store hash of required // sub-string of A int x; // If i = 0 then // requires hash value if (i == 0) { x = hash_a[len_b - 1]; } // Required hash if i != 0 else { x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod; x = (x * mi(mul[i])) % mod; } // Comparing hash with hash of B if (x == hash_b) { return true; } return false; } // Driver code public static void main(String[] args) { String a = \"abababababa\"; String b = \"aba\"; // Generating hash genHash(a.toCharArray(), b.toCharArray()); // Queries int queries[] = { 0, 1, 2, 3 }; int q = queries.length; // Perform queries for (int i = 0; i < q; i++) { if (checkEqual(queries[i], a.length(), b.length())) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } } }} /* This code is contributed by PrinciRaj1992 */",
"e": 31233,
"s": 28679,
"text": null
},
{
"code": "# Python3 implementation of the approachmod = 3803d = 26 hash_b = 0hash_a = []mul = [] # Function to return the modular inverse# using Fermat's little theorem def mi(x): global mod p = mod - 2 s = 1 while p != 1: if p % 2 == 1: s = (s * x) % mod x = (x * x) % mod p //= 2 return (s * x) % mod # Function to generate hash def genHash(a, b): global hash_b, hash_a, mul, d, mod # To store prefix-sum # of rolling hash hash_a = [0] * len(a) # Multiplier for different values of i mul = [0] * len(a) # Generating hash value for string b for i in range(len(b) - 1, -1, -1): hash_b = (hash_b * d + (ord(b[i]) - 97)) % mod # Generating prefix-sum of hash of a mul[0] = 1 hash_a[0] = (ord(a[0]) - 97) % mod for i in range(1, len(a)): mul[i] = (mul[i - 1] * d) % mod hash_a[i] = (hash_a[i - 1] + mul[i] * (ord(a[i]) - 97)) % mod # Function that returns true if the# required sub-string in a is equal to b def checkEqual(i, len_a, len_b): global hash_b, hash_a, mul, d, mod # To store hash of required # sub-string of A x = -1 # If i = 0 then # requires hash value if i == 0: x = hash_a[len_b - 1] # Required hash if i != 0 else: x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod x = (x * mi(mul[i])) % mod # Comparing hash with hash of B if x == hash_b: return True return False # Driver Codeif __name__ == \"__main__\": a = \"abababababa\" b = \"aba\" # Generating hash genHash(a, b) # Queries queries = [0, 1, 2, 3] q = len(queries) # Perform queries for i in range(q): if checkEqual(queries[i], len(a), len(b)): print(\"Yes\") else: print(\"No\") # This code is contributed by# sanjeev2552",
"e": 33114,
"s": 31233,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { static int mod = 3803; static int d = 26; static int hash_b; static int[] hash_a; static int[] mul; // Function to return the modular inverse // using Fermat's little theorem static int mi(int x) { int p = mod - 2; int s = 1; while (p != 1) { if (p % 2 == 1) { s = (s * x) % mod; } x = (x * x) % mod; p /= 2; } return (s * x) % mod; } // Function to generate hash static void genHash(char[] a, char[] b) { // To store prefix-sum // of rolling hash hash_a = new int[a.Length]; // Multiplier for different values of i mul = new int[a.Length]; // Generating hash value for string b for (int i = b.Length - 1; i >= 0; i--) { hash_b = (hash_b * d + (b[i] - 97)) % mod; } // Generating prefix-sum of hash of a mul[0] = 1; hash_a[0] = (a[0] - 97) % mod; for (int i = 1; i < a.Length; i++) { mul[i] = (mul[i - 1] * d) % mod; hash_a[i] = (hash_a[i - 1] + mul[i] * (a[i] - 97)) % mod; } } // Function that returns true if the // required sub-string in a is equal to b static Boolean checkEqual(int i, int len_a, int len_b) { // To store hash of required // sub-string of A int x; // If i = 0 then // requires hash value if (i == 0) { x = hash_a[len_b - 1]; } // Required hash if i != 0 else { x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod; x = (x * mi(mul[i])) % mod; } // Comparing hash with hash of B if (x == hash_b) { return true; } return false; } // Driver code public static void Main(String[] args) { String a = \"abababababa\"; String b = \"aba\"; // Generating hash genHash(a.ToCharArray(), b.ToCharArray()); // Queries int[] queries = { 0, 1, 2, 3 }; int q = queries.Length; // Perform queries for (int i = 0; i < q; i++) { if (checkEqual(queries[i], a.Length, b.Length)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } } }} /* This code contributed by PrinciRaj1992 */",
"e": 35651,
"s": 33114,
"text": null
},
{
"code": "<script> // Javascript implementation of the approachvar mod = 3803;var d = 26; var hash_b = 0;var hash_a = [];var mul = []; // Function to return the modular inverse// using Fermat's little theoremfunction mi(x){ var p = mod - 2; var s = 1; while (p != 1) { if (p % 2 == 1) s = (s * x) % mod; x = (x * x) % mod; p = parseInt(p/2); } return (s * x) % mod;} // Function to generate hashfunction genHash(a, b){ // To store prefix-sum // of rolling hash hash_a = Array(a.length).fill(0); // Multiplier for different values of i mul = Array(a.length).fill(0); // Generating hash value for string b for (var i = b.length - 1; i >= 0; i--) hash_b = (hash_b * d + (b[i].charCodeAt(0) - 97)) % mod; // Generating prefix-sum of hash of a mul[0] = 1; hash_a[0] = (a[0].charCodeAt(0) - 97) % mod; for (var i = 1; i < a.length; i++) { mul[i] = (mul[i - 1] * d) % mod; hash_a[i] = (hash_a[i - 1] + mul[i] * (a[i].charCodeAt(0) - 97)) % mod; }} // Function that returns true if the// required sub-string in a is equal to bfunction checkEqual(i, len_a, len_b){ // To store hash of required // sub-string of A var x; // If i = 0 then // requires hash value if (i == 0) x = hash_a[len_b - 1]; // Required hash if i != 0 else { x = (hash_a[i + len_b - 1] - hash_a[i - 1] + 2 * mod) % mod; x = (x * mi(mul[i])) % mod; } // Comparing hash with hash of B if (x == hash_b) return true; return false;} // Driver codevar a = \"abababababa\";var b = \"aba\"; // Generating hashgenHash(a.split(''), b.split('')); // Queriesvar queries = [0, 1, 2, 3];var q = queries.length // Perform queriesfor (var i = 0; i < q; i++) { if (checkEqual(queries[i], a.length, b.length)) document.write(\"Yes<br>\"); else document.write(\"No<br>\");} // This code is contributed by rrrtnx.</script>",
"e": 37623,
"s": 35651,
"text": null
},
{
"code": null,
"e": 37637,
"s": 37623,
"text": "Yes\nNo\nYes\nNo"
},
{
"code": null,
"e": 37782,
"s": 37637,
"text": "Note: For simplicity, we have used only one hash function. Use double/triple hash to eliminate any chance of collision and more accurate result."
},
{
"code": null,
"e": 37857,
"s": 37782,
"text": "The above question can be solved by using DP also, below is the java code."
},
{
"code": null,
"e": 37862,
"s": 37857,
"text": "Java"
},
{
"code": null,
"e": 37865,
"s": 37862,
"text": "C#"
},
{
"code": null,
"e": 37876,
"s": 37865,
"text": "Javascript"
},
{
"code": "import java.io.*;import java.util.*;import java.lang.*;import java.io.*; public class GFG{ private static void substringCheck(String stra, String strb, int[] query) { // Dp Array int[][] matrix = new int[strb.length()][stra.length()]; // String to character array char[] charCrr = stra.toCharArray(); char[] charRrr = strb.toCharArray(); // initialize matrix with 1 for (int c = 0; c < stra.length(); c++) { if (charRrr[0] == charCrr) { matrix[0] = 1; } } // for r from 1 to string length for (int r = 1; r < charRrr.length; r++) { char ch = charRrr[r]; // for c from 1 b string length for (int c = 1; c < charCrr.length; c++) { if (ch == charCrr && matrix[r - 1] == 1) { matrix[r] = 1; } } } // For every query for (int q : query) { int matLoc = (q + (strb.length() - 1)); if (matLoc >= stra.length()) { System.out.println(false); } else { // print true if (matrix[strb.length() - 1][matLoc] == 1) { System.out.println(true); } else { // print false System.out.println(false); } } } } // Driver Code public static void main(String[] args) { String stra = \"GeeksForGeeks\"; String strb = \"Geeks\"; int[] query = { 0,5,8 }; substringCheck(stra, strb, query); } } // class// Code contributed by Swapnil Gupta",
"e": 39727,
"s": 37876,
"text": null
},
{
"code": "using System; public class GFG { private static void substringCheck(string stra, string strb, int[] query) { // Dp Array int[, ] matrix = new int[strb.Length, stra.Length]; // String to character array char[] charCrr = stra.ToCharArray(); char[] charRrr = strb.ToCharArray(); // initialize matrix with 1 for (int c = 0; c < stra.Length; c++) { if (charRrr[0] == charCrr) { matrix[0, c] = 1; } } // for r from 1 to string length for (int r = 1; r < charRrr.Length; r++) { char ch = charRrr[r]; // for c from 1 b string length for (int c = 1; c < charCrr.Length; c++) { if (ch == charCrr && matrix[r - 1, c - 1] == 1) { matrix[r, c] = 1; } } } // For every query foreach(int q in query) { int matLoc = (q + (strb.Length - 1)); if (matLoc >= stra.Length) { Console.WriteLine(false); } else { // print true if (matrix[strb.Length - 1, matLoc] == 1) { Console.WriteLine(true); } else { // print false Console.WriteLine(false); } } } } // Driver Code public static void Main(string[] args) { string stra = \"GeeksForGeeks\"; string strb = \"Geeks\"; int[] query = { 0, 5, 8 }; substringCheck(stra, strb, query); }} // This code is contributed by ukasp.",
"e": 41385,
"s": 39727,
"text": null
},
{
"code": "<script> function substringCheck(stra, strb, query){ // Dp Array var matrix = Array.from(Array(strb.length), ()=>Array(stra.length)); // String to character array var charCrr = stra.split(''); var charRrr = strb.split(''); // initialize matrix with 1 for (var c = 0; c < stra.length; c++) { if (charRrr[0] == charCrr) { matrix[0] = 1; } } // for r from 1 to string length for (var r = 1; r < charRrr.length; r++) { var ch = charRrr[r]; // for c from 1 b string length for (var c = 1; c < charCrr.length; c++) { if (ch == charCrr && matrix[r - 1] == 1) { matrix[r] = 1; } } } // For every query for (var q of query) { var matLoc = (q + (strb.length - 1)); if (matLoc >= stra.length) { document.write(false + \"<br>\"); } else { // print true if (matrix[strb.length - 1][matLoc] == 1) { document.write(true+ \"<br>\"); } else { // print false document.write(false+ \"<br>\"); } } }} // Driver Codevar stra = \"GeeksForGeeks\";var strb = \"Geeks\";var query = [0,5,8];substringCheck(stra, strb, query); // This code is contributed by rutvik_56.</script>",
"e": 42800,
"s": 41385,
"text": null
},
{
"code": null,
"e": 42816,
"s": 42800,
"text": "true\nfalse\ntrue"
},
{
"code": null,
"e": 42840,
"s": 42816,
"text": "Time Complexity: O(M*N)"
},
{
"code": null,
"e": 42854,
"s": 42840,
"text": "princiraj1992"
},
{
"code": null,
"e": 42866,
"s": 42854,
"text": "sanjeev2552"
},
{
"code": null,
"e": 42878,
"s": 42866,
"text": "gswapnil246"
},
{
"code": null,
"e": 42890,
"s": 42878,
"text": "kk773572498"
},
{
"code": null,
"e": 42896,
"s": 42890,
"text": "ukasp"
},
{
"code": null,
"e": 42903,
"s": 42896,
"text": "rrrtnx"
},
{
"code": null,
"e": 42913,
"s": 42903,
"text": "rutvik_56"
},
{
"code": null,
"e": 42918,
"s": 42913,
"text": "Hash"
},
{
"code": null,
"e": 42928,
"s": 42918,
"text": "substring"
},
{
"code": null,
"e": 42948,
"s": 42928,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42956,
"s": 42948,
"text": "Strings"
},
{
"code": null,
"e": 42961,
"s": 42956,
"text": "Hash"
},
{
"code": null,
"e": 42969,
"s": 42961,
"text": "Strings"
},
{
"code": null,
"e": 42989,
"s": 42969,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 43087,
"s": 42989,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43096,
"s": 43087,
"text": "Comments"
},
{
"code": null,
"e": 43109,
"s": 43096,
"text": "Old Comments"
},
{
"code": null,
"e": 43140,
"s": 43109,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 43173,
"s": 43140,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 43211,
"s": 43173,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 43279,
"s": 43211,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 43314,
"s": 43279,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 43339,
"s": 43314,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 43385,
"s": 43339,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 43400,
"s": 43385,
"text": "C++ Data Types"
},
{
"code": null,
"e": 43460,
"s": 43400,
"text": "Write a program to print all permutations of a given string"
}
] |
C++ Program to Find Factorial of a Number using Dynamic Programming
|
The factorial of a positive integer n is equal to 1*2*3*...n. Factorial of a negative number does not exist. Here a C++ program is given to find out the factorial of a given input using dynamic programming.
Begin
fact(int n):
Read the number n
Initialize
i = 1, result[1000] = {0}
result[0] = 1
for i = 1 to n
result[i] = I * result[i-1]
Print result
End
#include <iostream>
using namespace std;
int result[1000] = {0};
int fact(int n) {
if (n >= 0) {
result[0] = 1;
for (int i = 1; i <= n; ++i) {
result[i] = i * result[i - 1];
}
return result[n];
}
}
int main() {
int n;
while (1) {
cout<<"Enter integer to compute factorial (enter 0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fact(n)<<endl;
}
return 0;
}
Enter integer to compute factorial (enter 0 to exit): 2
2
Enter integer to compute factorial (enter 0 to exit): 6
720
Enter integer to compute factorial (enter 0 to exit): 7
5040
Enter integer to compute factorial (enter 0 to exit): 10
3628800
Enter integer to compute factorial (enter 0 to exit): 0
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "The factorial of a positive integer n is equal to 1*2*3*...n. Factorial of a negative number does not exist. Here a C++ program is given to find out the factorial of a given input using dynamic programming."
},
{
"code": null,
"e": 1462,
"s": 1269,
"text": "Begin\n fact(int n):\n Read the number n\n Initialize\n i = 1, result[1000] = {0}\n result[0] = 1\n for i = 1 to n\n result[i] = I * result[i-1]\n Print result\nEnd"
},
{
"code": null,
"e": 1899,
"s": 1462,
"text": "#include <iostream>\nusing namespace std;\nint result[1000] = {0};\nint fact(int n) {\n if (n >= 0) {\n result[0] = 1;\n for (int i = 1; i <= n; ++i) {\n result[i] = i * result[i - 1];\n }\n return result[n];\n }\n}\nint main() {\n int n;\n while (1) {\n cout<<\"Enter integer to compute factorial (enter 0 to exit): \";\n cin>>n;\n if (n == 0)\n break;\n cout<<fact(n)<<endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 2199,
"s": 1899,
"text": "Enter integer to compute factorial (enter 0 to exit): 2\n2\nEnter integer to compute factorial (enter 0 to exit): 6\n720\nEnter integer to compute factorial (enter 0 to exit): 7\n5040\nEnter integer to compute factorial (enter 0 to exit): 10\n3628800\nEnter integer to compute factorial (enter 0 to exit): 0"
}
] |
ES6 - Objects
|
JavaScript supports extending data types. JavaScript objects are a great way to define custom data types.
An object is an instance which contains a set of key value pairs. Unlike primitive data types, objects can represent multiple or complex values and can change over their life time. The values can be scalar values or functions or even array of other objects.
The syntactic variations for defining an object is discussed further.
Like the primitive types, objects have a literal syntax: curly bracesv ({and}). Following is the syntax for defining an object.
var identifier = {
Key1:value, Key2: function () {
//functions
},
Key3: [“content1”,” content2”]
}
The contents of an object are called properties (or members), and properties consist of a name (or key) and value. Property names must be strings or symbols, and values can be any type (including other objects).
Like all JavaScript variables, both the object name (which could be a normal variable) and the property name are case sensitive. You access the properties of an object with a simple dot-notation.
Following is the syntax for accessing Object Properties.
objectName.propertyName
var person = {
firstname:"Tom",
lastname:"Hanks",
func:function(){return "Hello!!"},
};
//access the object values
console.log(person.firstname)
console.log(person.lastname)
console.log(person.func())
The above Example, defines an object person. The object has three properties. The third property refers to a function.
The following output is displayed on successful execution of the above code.
Tom
Hanks
Hello!!
In ES6, assigning a property value that matches a property name, you can omit the property value.
var foo = 'bar'
var baz = { foo }
console.log(baz.foo)
The above code snippet defines an object baz. The object has a property foo. The property value is omitted here as ES6 implicitly assigns the value of the variable foo to the object’s key foo.
Following is the ES5 equivalent of the above code.
var foo = 'bar'
var baz = { foo:foo }
console.log(baz.foo)
The following output is displayed on successful execution of the above code.
bar
With this shorthand syntax, the JS engine looks in the containing scope for a variable with the same name. If it is found, that variable’s value is assigned to the property. If it is not found, a Reference Error is thrown.
JavaScript provides a special constructor function called Object() to build the object. The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.
Following is the syntax for defining an object.
var obj_name = new Object();
obj_name.property = value;
OR
obj_name["key"] = value
Following is the syntax for accessing a property.
Object_name.property_key
OR
Object_name["property_key"]
var myCar = new Object();
myCar.make = "Ford"; //define an object
myCar.model = "Mustang";
myCar.year = 1987;
console.log(myCar["make"]) //access the object property
console.log(myCar["model"])
console.log(myCar["year"])
The following output is displayed on successful execution of the above code.
Ford
Mustang
1987
Unassigned properties of an object are undefined.
var myCar = new Object();
myCar.make = "Ford";
console.log(myCar["model"])
The following output is displayed on successful execution of the above code.
undefined
Note − An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.
Properties can also be accessed by using a string value that is stored in a variable. In other words, the object’s property key can be a dynamic value. For example: a variable. The said concept is illustrated in the following example.
var myCar = new Object()
var propertyName = "make";
myCar[propertyName] = "Ford";
console.log(myCar.make)
The following output is displayed on successful execution of the above code.
Ford
An object can be created using the following two steps −
Step 1 − Define the object type by writing a constructor function.
Following is the syntax for the same.
function function_name() {
this.property_name = value
}
The ‘this’ keyword refers to the current object in use and defines the object’s property.
Step 2 − Create an instance of the object with the new syntax.
var Object_name= new function_name()
//Access the property value
Object_name.property_name
The new keyword invokes the function constructor and initializes the function’s property keys.
Example − Using a Function Constructor
function Car() {
this.make = "Ford"
this.model = "F123"
}
var obj = new Car()
console.log(obj.make)
console.log(obj.model)
The above example uses a function constructor to define an object.
The following output is displayed on successful execution of the above code.
Ford
F123
A new property can always be added to a previously defined object. For example, consider the following code snippet −
function Car() {
this.make = "Ford"
}
var obj = new Car()
obj.model = "F123"
console.log(obj.make)
console.log(obj.model)
The following output is displayed on successful execution of the above code.
Ford
F123
Objects can also be created using the Object.create() method. It allows you to create the prototype for the object you want, without having to define a constructor function.
var roles = {
type: "Admin", // Default value of properties
displayType : function() {
// Method which will display type of role
console.log(this.type);
}
}
// Create new role type called super_role
var super_role = Object.create(roles);
super_role.displayType(); // Output:Admin
// Create new role type called Guest
var guest_role = Object.create(roles);
guest_role.type = "Guest";
guest_role.displayType(); // Output:Guest
The above example defines an object -roles and sets the default values for the properties. Two new instances are created that override the default properties value for the object.
The following output is displayed on successful execution of the above code.
Admin
Guest
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Following is the syntax for the same.
Object.assign(target, ...sources)
Example − Cloning an Object
"use strict"
var det = { name:"Tom", ID:"E1001" };
var copy = Object.assign({}, det);
console.log(copy);
for (let val in copy) {
console.log(copy[val])
}
The following output is displayed on successful execution of the above code.
Tom
E1001
Example − Merging Objects
var o1 = { a: 10 };
var o2 = { b: 20 };
var o3 = { c: 30 };
var obj = Object.assign(o1, o2, o3);
console.log(obj);
console.log(o1);
The following output is displayed on successful execution of the above code.
{ a: 10, b: 20, c: 30 }
{ a: 10, b: 20, c: 30 }
Note − Unlike copying objects, when objects are merged, the larger object doesn’t maintain a new copy of the properties. Rather it holds the reference to the properties contained in the original objects. The following example explains this concept.
var o1 = { a: 10 };
var obj = Object.assign(o1);
obj.a++
console.log("Value of 'a' in the Merged object after increment ")
console.log(obj.a);
console.log("value of 'a' in the Original Object after increment ")
console.log(o1.a);
The following output is displayed on successful execution of the above code.
Value of 'a' in the Merged object after increment
11
value of 'a' in the Original Object after increment
11
You can remove a property by using the delete operator. The following code shows how to remove a property.
// Creates a new object, myobj, with two properties, a and b.
var myobj = new Object;
myobj.a = 5;
myobj.b = 12;
// Removes the ‘a’ property
delete myobj.a;
console.log ("a" in myobj) // yields "false"
The following output is displayed on successful execution of the above code.
false
The code snippet deletes the property from the object. The example prints false as the in operator doesn’t find the property in the object.
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. This is because, they point to a completely different memory address. Only those objects that share a common reference yields true on comparison.
Example 1 − Different Object References
var val1 = {name: "Tom"};
var val2 = {name: "Tom"};
console.log(val1 == val2) // return false
console.log(val1 === val2) // return false
In the above example, val1 and val2 are two distinct objects that refer to two different memory addresses. Hence on comparison for equality, the operator will return false.
Example 2 − Single Object Reference
var val1 = {name: "Tom"};
var val2 = val1
console.log(val1 == val2) // return true
console.log(val1 === val2) // return true
In the above example, the contents in val1 are assigned to val2, i.e. the reference of the properties in val1 are shared with val2. Since, the objects now share the reference to the property, the equality operator will return true for two distinct objects that refer to two different memory addresses. Hence on comparison for equality, the operator will return false.
The term destructuring refers to breaking up the structure of an entity. The destructuring assignment syntax in JavaScript makes it possible to extract data from arrays or objects into distinct variables. The same is illustrated in the following example.
When destructuring an object the variable names and the object property names must match.
<script>
let student = {
rollno:20,
name:'Prijin',
cgpa:7.2
}
//destructuring to same property name
let {name,cgpa} = student
console.log(name)
console.log(cgpa)
//destructuring to different name
let {name:student_name,cgpa:student_cgpa}=student
console.log(student_cgpa)
console.log("student_name",student_name)
</script>
The output of the above code will be as seen below −
Prijin
7.2
7.2
student_name Prijin
If the variable and assignment are in two different steps, then the destructuring object syntax will be surrounded by () as shown in the example ({rollno} = student) −
<script>
let student = {
rollno:20,
name:'Prijin',
cgpa:7.2
}
// destructuring to already declared variable
let rollno;
({rollno} = student)
console.log(rollno)
// assign default values to variables
let product ={ id:1001,price:2000} //discount is not product property
let {id,price,discount=.10} = product
console.log(id)
console.log(price)
console.log(discount)
</script>
The output of the above code will be as mentioned below −
20
1001
2000
0.1
The below example shows destructuring using the rest operator and how to destruct nested objects.
<script>
// rest operator with object destructuring
let customers= {
c1:101,
c2:102,
c3:103
}
let {c1,...others} = customers
console.log(c1)
console.log(others)
//nested objects
let emp = {
id:101,
address:{
city:'Mumbai',
pin:1234
}
}
let {address} = emp;
console.log(address)
let {address:{city,pin}} = emp
console.log(city)
</script>
The output of the above code will be as mentioned below −
101
{c2: 102, c3: 103}
{city: "Mumbai", pin: 1234}
Mumbai
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2383,
"s": 2277,
"text": "JavaScript supports extending data types. JavaScript objects are a great way to define custom data types."
},
{
"code": null,
"e": 2641,
"s": 2383,
"text": "An object is an instance which contains a set of key value pairs. Unlike primitive data types, objects can represent multiple or complex values and can change over their life time. The values can be scalar values or functions or even array of other objects."
},
{
"code": null,
"e": 2711,
"s": 2641,
"text": "The syntactic variations for defining an object is discussed further."
},
{
"code": null,
"e": 2839,
"s": 2711,
"text": "Like the primitive types, objects have a literal syntax: curly bracesv ({and}). Following is the syntax for defining an object."
},
{
"code": null,
"e": 2959,
"s": 2839,
"text": "var identifier = {\n Key1:value, Key2: function () { \n //functions \n }, \n Key3: [“content1”,” content2”] \n} \n"
},
{
"code": null,
"e": 3171,
"s": 2959,
"text": "The contents of an object are called properties (or members), and properties consist of a name (or key) and value. Property names must be strings or symbols, and values can be any type (including other objects)."
},
{
"code": null,
"e": 3367,
"s": 3171,
"text": "Like all JavaScript variables, both the object name (which could be a normal variable) and the property name are case sensitive. You access the properties of an object with a simple dot-notation."
},
{
"code": null,
"e": 3424,
"s": 3367,
"text": "Following is the syntax for accessing Object Properties."
},
{
"code": null,
"e": 3450,
"s": 3424,
"text": "objectName.propertyName \n"
},
{
"code": null,
"e": 3673,
"s": 3450,
"text": "var person = { \n firstname:\"Tom\", \n lastname:\"Hanks\", \n func:function(){return \"Hello!!\"}, \n}; \n//access the object values \nconsole.log(person.firstname) \nconsole.log(person.lastname) \nconsole.log(person.func())"
},
{
"code": null,
"e": 3792,
"s": 3673,
"text": "The above Example, defines an object person. The object has three properties. The third property refers to a function."
},
{
"code": null,
"e": 3869,
"s": 3792,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 3890,
"s": 3869,
"text": "Tom \nHanks \nHello!!\n"
},
{
"code": null,
"e": 3988,
"s": 3890,
"text": "In ES6, assigning a property value that matches a property name, you can omit the property value."
},
{
"code": null,
"e": 4045,
"s": 3988,
"text": "var foo = 'bar' \nvar baz = { foo } \nconsole.log(baz.foo)"
},
{
"code": null,
"e": 4238,
"s": 4045,
"text": "The above code snippet defines an object baz. The object has a property foo. The property value is omitted here as ES6 implicitly assigns the value of the variable foo to the object’s key foo."
},
{
"code": null,
"e": 4289,
"s": 4238,
"text": "Following is the ES5 equivalent of the above code."
},
{
"code": null,
"e": 4350,
"s": 4289,
"text": "var foo = 'bar' \nvar baz = { foo:foo } \nconsole.log(baz.foo)"
},
{
"code": null,
"e": 4427,
"s": 4350,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 4432,
"s": 4427,
"text": "bar\n"
},
{
"code": null,
"e": 4655,
"s": 4432,
"text": "With this shorthand syntax, the JS engine looks in the containing scope for a variable with the same name. If it is found, that variable’s value is assigned to the property. If it is not found, a Reference Error is thrown."
},
{
"code": null,
"e": 4881,
"s": 4655,
"text": "JavaScript provides a special constructor function called Object() to build the object. The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method."
},
{
"code": null,
"e": 4929,
"s": 4881,
"text": "Following is the syntax for defining an object."
},
{
"code": null,
"e": 5032,
"s": 4929,
"text": "var obj_name = new Object(); \nobj_name.property = value; \nOR \nobj_name[\"key\"] = value \n"
},
{
"code": null,
"e": 5082,
"s": 5032,
"text": "Following is the syntax for accessing a property."
},
{
"code": null,
"e": 5173,
"s": 5082,
"text": "Object_name.property_key \nOR \nObject_name[\"property_key\"]\n"
},
{
"code": null,
"e": 5402,
"s": 5173,
"text": "var myCar = new Object(); \nmyCar.make = \"Ford\"; //define an object \nmyCar.model = \"Mustang\"; \nmyCar.year = 1987; \n\nconsole.log(myCar[\"make\"]) //access the object property \nconsole.log(myCar[\"model\"]) \nconsole.log(myCar[\"year\"])"
},
{
"code": null,
"e": 5479,
"s": 5402,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 5500,
"s": 5479,
"text": "Ford \nMustang \n1987\n"
},
{
"code": null,
"e": 5550,
"s": 5500,
"text": "Unassigned properties of an object are undefined."
},
{
"code": null,
"e": 5627,
"s": 5550,
"text": "var myCar = new Object(); \nmyCar.make = \"Ford\"; \nconsole.log(myCar[\"model\"])"
},
{
"code": null,
"e": 5704,
"s": 5627,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 5715,
"s": 5704,
"text": "undefined\n"
},
{
"code": null,
"e": 6072,
"s": 5715,
"text": "Note − An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation."
},
{
"code": null,
"e": 6307,
"s": 6072,
"text": "Properties can also be accessed by using a string value that is stored in a variable. In other words, the object’s property key can be a dynamic value. For example: a variable. The said concept is illustrated in the following example."
},
{
"code": null,
"e": 6417,
"s": 6307,
"text": "var myCar = new Object() \nvar propertyName = \"make\"; \nmyCar[propertyName] = \"Ford\"; \nconsole.log(myCar.make)"
},
{
"code": null,
"e": 6494,
"s": 6417,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 6500,
"s": 6494,
"text": "Ford\n"
},
{
"code": null,
"e": 6557,
"s": 6500,
"text": "An object can be created using the following two steps −"
},
{
"code": null,
"e": 6624,
"s": 6557,
"text": "Step 1 − Define the object type by writing a constructor function."
},
{
"code": null,
"e": 6662,
"s": 6624,
"text": "Following is the syntax for the same."
},
{
"code": null,
"e": 6724,
"s": 6662,
"text": "function function_name() { \n this.property_name = value \n}\n"
},
{
"code": null,
"e": 6814,
"s": 6724,
"text": "The ‘this’ keyword refers to the current object in use and defines the object’s property."
},
{
"code": null,
"e": 6877,
"s": 6814,
"text": "Step 2 − Create an instance of the object with the new syntax."
},
{
"code": null,
"e": 6973,
"s": 6877,
"text": "var Object_name= new function_name() \n//Access the property value \n\nObject_name.property_name\n"
},
{
"code": null,
"e": 7068,
"s": 6973,
"text": "The new keyword invokes the function constructor and initializes the function’s property keys."
},
{
"code": null,
"e": 7107,
"s": 7068,
"text": "Example − Using a Function Constructor"
},
{
"code": null,
"e": 7243,
"s": 7107,
"text": "function Car() { \n this.make = \"Ford\" \n this.model = \"F123\" \n} \nvar obj = new Car() \nconsole.log(obj.make) \nconsole.log(obj.model)"
},
{
"code": null,
"e": 7310,
"s": 7243,
"text": "The above example uses a function constructor to define an object."
},
{
"code": null,
"e": 7387,
"s": 7310,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 7400,
"s": 7387,
"text": "Ford \nF123 \n"
},
{
"code": null,
"e": 7518,
"s": 7400,
"text": "A new property can always be added to a previously defined object. For example, consider the following code snippet −"
},
{
"code": null,
"e": 7649,
"s": 7518,
"text": "function Car() { \n this.make = \"Ford\" \n} \nvar obj = new Car() \nobj.model = \"F123\" \nconsole.log(obj.make) \nconsole.log(obj.model)"
},
{
"code": null,
"e": 7726,
"s": 7649,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 7738,
"s": 7726,
"text": "Ford \nF123\n"
},
{
"code": null,
"e": 7912,
"s": 7738,
"text": "Objects can also be created using the Object.create() method. It allows you to create the prototype for the object you want, without having to define a constructor function."
},
{
"code": null,
"e": 8375,
"s": 7912,
"text": "var roles = { \n type: \"Admin\", // Default value of properties \n displayType : function() { \n // Method which will display type of role \n console.log(this.type); \n } \n} \n// Create new role type called super_role \nvar super_role = Object.create(roles); \nsuper_role.displayType(); // Output:Admin \n\n// Create new role type called Guest \nvar guest_role = Object.create(roles); \nguest_role.type = \"Guest\"; \nguest_role.displayType(); // Output:Guest"
},
{
"code": null,
"e": 8555,
"s": 8375,
"text": "The above example defines an object -roles and sets the default values for the properties. Two new instances are created that override the default properties value for the object."
},
{
"code": null,
"e": 8632,
"s": 8555,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 8646,
"s": 8632,
"text": "Admin \nGuest\n"
},
{
"code": null,
"e": 8819,
"s": 8646,
"text": "The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object."
},
{
"code": null,
"e": 8857,
"s": 8819,
"text": "Following is the syntax for the same."
},
{
"code": null,
"e": 8896,
"s": 8857,
"text": "Object.assign(target, ...sources) \n"
},
{
"code": null,
"e": 8924,
"s": 8896,
"text": "Example − Cloning an Object"
},
{
"code": null,
"e": 9088,
"s": 8924,
"text": "\"use strict\" \nvar det = { name:\"Tom\", ID:\"E1001\" }; \nvar copy = Object.assign({}, det); \nconsole.log(copy); \nfor (let val in copy) { \n console.log(copy[val]) \n}"
},
{
"code": null,
"e": 9165,
"s": 9088,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 9177,
"s": 9165,
"text": "Tom \nE1001\n"
},
{
"code": null,
"e": 9203,
"s": 9177,
"text": "Example − Merging Objects"
},
{
"code": null,
"e": 9342,
"s": 9203,
"text": "var o1 = { a: 10 }; \nvar o2 = { b: 20 }; \nvar o3 = { c: 30 }; \nvar obj = Object.assign(o1, o2, o3); \nconsole.log(obj); \nconsole.log(o1);\n"
},
{
"code": null,
"e": 9419,
"s": 9342,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 9469,
"s": 9419,
"text": "{ a: 10, b: 20, c: 30 } \n{ a: 10, b: 20, c: 30 }\n"
},
{
"code": null,
"e": 9718,
"s": 9469,
"text": "Note − Unlike copying objects, when objects are merged, the larger object doesn’t maintain a new copy of the properties. Rather it holds the reference to the properties contained in the original objects. The following example explains this concept."
},
{
"code": null,
"e": 9956,
"s": 9718,
"text": "var o1 = { a: 10 }; \nvar obj = Object.assign(o1); \nobj.a++ \nconsole.log(\"Value of 'a' in the Merged object after increment \") \nconsole.log(obj.a); \nconsole.log(\"value of 'a' in the Original Object after increment \") \nconsole.log(o1.a);"
},
{
"code": null,
"e": 10033,
"s": 9956,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 10147,
"s": 10033,
"text": "Value of 'a' in the Merged object after increment \n11 \nvalue of 'a' in the Original Object after increment \n11 \n"
},
{
"code": null,
"e": 10254,
"s": 10147,
"text": "You can remove a property by using the delete operator. The following code shows how to remove a property."
},
{
"code": null,
"e": 10463,
"s": 10254,
"text": "// Creates a new object, myobj, with two properties, a and b. \nvar myobj = new Object; \nmyobj.a = 5; \nmyobj.b = 12; \n\n// Removes the ‘a’ property \ndelete myobj.a; \nconsole.log (\"a\" in myobj) // yields \"false\""
},
{
"code": null,
"e": 10540,
"s": 10463,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 10547,
"s": 10540,
"text": "false\n"
},
{
"code": null,
"e": 10687,
"s": 10547,
"text": "The code snippet deletes the property from the object. The example prints false as the in operator doesn’t find the property in the object."
},
{
"code": null,
"e": 10955,
"s": 10687,
"text": "In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. This is because, they point to a completely different memory address. Only those objects that share a common reference yields true on comparison."
},
{
"code": null,
"e": 10995,
"s": 10955,
"text": "Example 1 − Different Object References"
},
{
"code": null,
"e": 11137,
"s": 10995,
"text": "var val1 = {name: \"Tom\"}; \nvar val2 = {name: \"Tom\"}; \nconsole.log(val1 == val2) // return false \nconsole.log(val1 === val2) // return false"
},
{
"code": null,
"e": 11310,
"s": 11137,
"text": "In the above example, val1 and val2 are two distinct objects that refer to two different memory addresses. Hence on comparison for equality, the operator will return false."
},
{
"code": null,
"e": 11346,
"s": 11310,
"text": "Example 2 − Single Object Reference"
},
{
"code": null,
"e": 11476,
"s": 11346,
"text": "var val1 = {name: \"Tom\"}; \nvar val2 = val1 \n\nconsole.log(val1 == val2) // return true \nconsole.log(val1 === val2) // return true"
},
{
"code": null,
"e": 11844,
"s": 11476,
"text": "In the above example, the contents in val1 are assigned to val2, i.e. the reference of the properties in val1 are shared with val2. Since, the objects now share the reference to the property, the equality operator will return true for two distinct objects that refer to two different memory addresses. Hence on comparison for equality, the operator will return false."
},
{
"code": null,
"e": 12099,
"s": 11844,
"text": "The term destructuring refers to breaking up the structure of an entity. The destructuring assignment syntax in JavaScript makes it possible to extract data from arrays or objects into distinct variables. The same is illustrated in the following example."
},
{
"code": null,
"e": 12189,
"s": 12099,
"text": "When destructuring an object the variable names and the object property names must match."
},
{
"code": null,
"e": 12541,
"s": 12189,
"text": "<script>\nlet student = {\n rollno:20,\n name:'Prijin',\n cgpa:7.2\n}\n\n//destructuring to same property name\n let {name,cgpa} = student\n console.log(name)\n console.log(cgpa)\n\n//destructuring to different name\n let {name:student_name,cgpa:student_cgpa}=student\n console.log(student_cgpa)\n console.log(\"student_name\",student_name)\n</script>"
},
{
"code": null,
"e": 12594,
"s": 12541,
"text": "The output of the above code will be as seen below −"
},
{
"code": null,
"e": 12630,
"s": 12594,
"text": "Prijin\n7.2\n7.2\nstudent_name Prijin\n"
},
{
"code": null,
"e": 12798,
"s": 12630,
"text": "If the variable and assignment are in two different steps, then the destructuring object syntax will be surrounded by () as shown in the example ({rollno} = student) −"
},
{
"code": null,
"e": 13229,
"s": 12798,
"text": "<script>\n let student = {\n rollno:20,\n name:'Prijin',\n cgpa:7.2\n }\n\n // destructuring to already declared variable\n let rollno;\n ({rollno} = student)\n console.log(rollno)\n\n // assign default values to variables\n\n let product ={ id:1001,price:2000} //discount is not product property\n let {id,price,discount=.10} = product\n console.log(id)\n console.log(price)\n console.log(discount)\n</script>"
},
{
"code": null,
"e": 13287,
"s": 13229,
"text": "The output of the above code will be as mentioned below −"
},
{
"code": null,
"e": 13305,
"s": 13287,
"text": "20\n1001\n2000\n0.1\n"
},
{
"code": null,
"e": 13403,
"s": 13305,
"text": "The below example shows destructuring using the rest operator and how to destruct nested objects."
},
{
"code": null,
"e": 13836,
"s": 13403,
"text": "<script>\n // rest operator with object destructuring\n let customers= {\n c1:101,\n c2:102,\n c3:103\n }\n\n let {c1,...others} = customers\n console.log(c1)\n console.log(others)\n\n //nested objects\n let emp = {\n id:101,\n address:{\n city:'Mumbai',\n pin:1234\n }\n }\n let {address} = emp;\n\n console.log(address)\n let {address:{city,pin}} = emp\n console.log(city)\n</script>"
},
{
"code": null,
"e": 13894,
"s": 13836,
"text": "The output of the above code will be as mentioned below −"
},
{
"code": null,
"e": 13953,
"s": 13894,
"text": "101\n{c2: 102, c3: 103}\n{city: \"Mumbai\", pin: 1234}\nMumbai\n"
},
{
"code": null,
"e": 13988,
"s": 13953,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 14002,
"s": 13988,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 14035,
"s": 14002,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 14053,
"s": 14035,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 14086,
"s": 14053,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 14100,
"s": 14086,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 14135,
"s": 14100,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 14152,
"s": 14135,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 14185,
"s": 14152,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 14201,
"s": 14185,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 14236,
"s": 14201,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14244,
"s": 14236,
"text": " Shweta"
},
{
"code": null,
"e": 14251,
"s": 14244,
"text": " Print"
},
{
"code": null,
"e": 14262,
"s": 14251,
"text": " Add Notes"
}
] |
Data Formats for Training in TensorFlow: Parquet, Petastorm, Feather, and More | by Chaim Rand | Towards Data Science
|
Machine learning is all about the data. To successfully train a sophisticated model you will need a high quality training dataset; a dataset that is sufficiently large, accurately labeled, and correctly represents the distribution of data samples in the real world. However, no less important is proper management of the data. By data management we are referring to how and where the data is stored, the ways in which it is accessed, and the transformations it undergoes during the development life-cycle. The focus of this post is on the file format used to store the training data and the implications it can have on the model training. Choosing the file format is one of the many important decisions you will need to make when defining your machine learning project.
This post is comprised of four sections. In the first section we will identify some of the properties that we would like our file format to have. In the second section we will review potential file formats and evaluate them against the desired properties we have found. Next we will survey different options for streaming these formats into a TensorFlow training session. In the last section we will describe a few experiments we ran to test some of these options.
Before we dive in, let’s set the stage. We will assume in this post that the size of our training dataset necessitates storing it in a distributed storage system, e.g. hundreds of terabytes. In the examples below we will use Amazon S3 for data storage, but the principals applies equally to any other distributed storage system. The data will likely be accessed by several consumers during the development cycle and for various purposes including data creation, data analysis, model training, and more. Our focus will be on training in TensorFlow, although much of what we will say pertains to other training frameworks as well.
The underlying assumption of this post is that a file format for our data is required, i.e. that we require one or more files for: 1. grouping together all elements/columns/features of single data samples, as well as 2. grouping together multiple data samples. Of course, one could envision scenarios in which one might choose to maintain all elements of all samples in individual files and in their raw format. However, in many cases, especially if the file sizes are small (e.g. several KBs) this strategy is likely to severely degrade the runtime performance of the data access.
The intention of this post is to highlight some of the important considerations when choosing a file format and to discuss a few of the different options available today. We will mention a number of formats as well as a number of software development frameworks and tools. These mentions should not be interpreted as an endorsement. The appropriate choice for you is likely to be based on a wide range of considerations some of which may be beyond the scope of this discussion. The post will include a number of simple code snippets. These are presented for the purposes of demonstration only and should not be viewed as optimal implementations.
The landscape of machine learning tools is extremely dynamic. Some of the formats and tools we will mention continue to evolve and some of the comments we will make may become outdated by the time you read this. Take care to keep track of announcements of new versions and new tools and be sure to make your design decisions on the most up to date information available.
Please do not hesitate to reach out to me with any comments or corrections.
To facilitate this discussion let’s take a look at a common file format used for training in TensorFlow, the TFRecord format.
TFRecord is a format based on protocol buffers specifically designed for use with TensorFlow. A TFRecord file is comprised of sequences of serialized binary samples. Each sample represents a tf.train.Example which, in turn, represents a dictionary of string to value mappings. The sequential nature of the TFRecord format facilitates high data streaming throughput. In particular, one does not need to download and open a full file in order to start traversing its contents. Moreover, the TensorFlow tf.data module includes the highly optimized TFRecordDataset class for building input pipelines based on data stored in TFRecord files. However, the TFRecord format is not without its faults. Here we name a few:
Single purpose: The TFRecord format is unlikely to satisfy the needs of any of the other data consumers on the development pipeline. It is common for development teams to maintain their data in a different format and create a derivative of the data in TFRecord format specifically for the purpose of training. Storing multiple copies of your data is not ideal, especially when your data set is large. Aside from the added cost of data storage, the implication is that every time there is a change to the core data set a new TFRecord copy needs to be generated. We may wish update the core data records based on findings from the training session, in which case we will also need to maintain a mapping between the generated TFRecord records and their corresponding entries in the core data format.
Extracting partial record data: Another problem with the TFRecord format arises when our training model requires only a subset of the TFRecord elements. For example, suppose that we have a multi-headed model that performs different types of pixel level segmentation on an input image. Each record in the data set contains multiple ground truth images corresponding to the multiple heads of the model. Now we decide to train a version of the model with just a single head. The trivial solution would be to feed in the complete TFRecord and simply ignore the unnecessary fields. However, the need to pull and parse extraneous data can severely impact the throughput of our input pipeline and thus the speed of our training. To reduce the risk of bottlenecks in the pipeline, we would need to create an additional copy of the data containing only the content relevant for the specific training at hand. This further exacerbates the data duplication issue we discussed above.
Record filtering: Sometimes we are interested in traversing records that have specific entry values. The trivial way to do this is to iterate over all of the data and simply drop any record that does not match our filter (e.g. using tf.filter). As before, this can introduce considerable overhead to the data input pipeline and result in significant starvation of the training loop. In previous posts (here and here) we demonstrated a need to filter input images based on whether they contained pink cars. The solution we proposed there was to store different data classes in separate files. Whenever the need to filter arose, we could traverse only the files associated with the filter. However, this solution requires us to be able to anticipate the filters we will need to apply which is not always possible. If we encounter a need to apply a filter that we did not anticipate we could either recreate the data with an additional partition or fall back to the trivial method of dropping non-matching samples. Neither option is optimal.
Data transformation: A typical input data pipeline might include multiple operations on the input data including data warping, augmentations, batching, and more. TensorFlow offers a set of built-in data processing operations that can be added to the input data pipeline computation graph via the tf.data.Dataset.map function. However, you might find that the data processing you require cannot be implemented efficiently using TensorFlow. One option would be to apply a block of native python code using tf.py_function, but this may limit your data throughput performance due to the Python Global Interpreter Lock (GIL). Many use cases call for using a format that enables applying operations in native python before being entered into the TensorFlow computation graph.
Based on the discussion above let us compile a list of some of the properties we are looking for in our file format. Given the added cost and complexities of storing multiple copies of our data, we will restrict ourselves from now on to a single copy of the data, i.e. we must choose a format that satisfies the needs of all data consumers. This list is not intended to be all inclusive. Additional requirements based on the particular use-case should be considered.
Distributed Storage: The file format and supporting libraries must support the option of storing large datasets in distributed storage settings such as Amazon S3, HDFS, and more.
Software Ecosystem: We require a strong ecosystem of libraries providing a range of tools for analyzing and manipulating the data.
Columnar Support: The file format and supporting libraries must support efficient extraction of a subset of features per data sample.
Row Filtering: The file format and supporting libraries should support efficient filtering on the values of sample features.
TensorFlow Integration: The format must facilitate efficient data streaming from storage into TensorFlow training sessions.
One requirement for training that we have left out of our discussion is data shuffling. It is common practice to shuffle the training data before each traversal (epoch). Were we able to randomly access any sample in the dataset, data shuffling would be easy. However, such random access to individual samples comes at the expense of performance, certainly in a distributed storage setting. Instead, one must resort to other mechanisms for shuffling including combinations of: shuffling samples during data creation, shuffling on the list of files that comprise the full dataset, interleaving between multiple datasets, and using an appropriately large shuffle buffer during training (e.g. see tf.data.Dataset.shuffle). We have chosen not to state shuffling as a requirement of the file format as, in our view, in the training scenario we have presented this challenge will exist with any choice of file format.
In the next section we will evaluate the compatibility of several file formats for training. In the following section we will discuss options for streaming them into TensorFlow.
A full survey of data formats for deep learning is beyond the scope of this post. We will limit our discussion to just a few strong candidates. More extensive surveys abound. Here is one example:
towardsdatascience.com
You can also check out a recent post of mine that covers the relatively new webdataset format, an intriguing solution specially geared towards developers who wish to maintain their data in the most raw form possible.
We will measure each format according to the metrics we chose above as in the below diagram in which we summarize our evaluation of the TFRecord format. We use green to indicate full support, yellow to indicate partial support, and red to indicate no support.
One of the more compelling file format options is Apache Parquet. Apache Parquet has an extensive software ecosystem with multiple frameworks and tools supporting a wide variety of data processing operations. It is especially popular among data analysts. The possibility of basing our training on the same format is quite attractive.
One of the main attributes of the Parquet format to which it owes much of its success is the fact that is a columnar storage format. Contrary to other formats such as CSV or TFRecord, in which each row of data is stored sequentially, in a columnar data format columns of data are stored together. Each file in the dataset is divided into row blocks each of which contains multiple samples. Within a row block the sample data is stored according to columns, i.e. the values of the first field of all of the samples appear first and are followed by the values of the second field of all of the samples, and so on. The columnar nature of the format facilitates efficient data analytics since queries can be made on subsets of columns without needing to load entire data records. Furthermore, grouping together columns can lead to more efficient compression of data and thus to reduced storage costs. Check out this post for more on the advantages of columnar data storage.
The following diagram summarizes our evaluation of the Parquet format:
Being a columnar format, Parquet enables efficient extraction of subsets of data columns. In addition, we can also take advantage of the columnar nature of the format to facilitate row filtering by: 1. first extracting the column on which we are filtering and then 2. extracting the rest of columns only for rows that match the filter. However, being that efficient data extraction might rely on extracting the columnar data of full blocks of rows, it is unclear that this method would perform well. Therefore we have marked this capability in yellow. A more performant filtering approach might require separating samples into different Parquet files according to class during the dataset creation, as described above. In pyspark this can be done using the partitionBy functionality.
Parquet Dataset Creation: In the code block below we demonstrate creation of a Parquet dataset from the popular Cifar10 dataset using the pyspark library. Parquet creation is supported by additional libraries as well including pandas and pyarrow.
from tensorflow.keras import datasetsfrom pyspark.sql import SparkSession, Rowfrom pyspark.sql.types import StructType, \ StructField, IntegerType, BinaryTypedef cifar_to_parquet(): schema = StructType( [StructField("image", BinaryType(), True), StructField("label", IntegerType(), True)]) (data, labels), _ = datasets.cifar10.load_data() labels = labels.flatten().tolist() num_procs = 4 # set the number of parallel processes spark = SparkSession.builder\ .master('local[{num_procs}]'.format(num_procs=num_procs))\ .getOrCreate() sc = spark.sparkContext num_samples = len(labels) output_url = 'file:///tmp/parquet' def row_generator(i): return { 'image': bytearray(data[i].tobytes()), 'label': labels[i], } # optionally configure the size of row blocks # blockSize = 1024 * 1024 * 16 # 16 MB # sc._jsc.hadoopConfiguration()\ # .setInt("parquet.block.size", blockSize) rows_rdd = sc.parallelize(range(num_samples))\ .map(row_generator)\ .map(lambda x: Row(**x)) spark.createDataFrame(rows_rdd, schema)\ .write.mode('overwrite')\ .parquet(output_url)
While the number of files that comprise the dataset, the sizes of each file, and the size of each row block can have a meaningful impact on the performance of data loading, controlling these parameters can sometimes be a little tricky. In pyspark the row block size can be set using sc._jsc.hadoopConfiguration as in the comment in the code block above (the default value is 128 MB) and the sizes and number of files by the number of parallel processes and by the coalesce function.
Through appropriate configuration, the script can be modified to write directly to Amazon S3 (see e.g. here and here).
The petastorm library was created with the specific goal of unifying the dataset used by all data consumers on the development pipeline (see here). Although petastorm abstracts the underlying storage format, the default format used is Apache Parquet. More accurately, petastorm extends Apache Parquet by providing additional schema information in the Unischema structure, supporting multi-dimensional data, and supporting data compressing codecs. Henceforth we will assume the use of the extended Parquet as the underlying format and abuse the use of the term petastorm by using it to refer both to the library itself as well as to the file format created by the library. To distinguish between the two we will use capitalization when referring to the Petastorm format. The use of Parquet as the underlying format means that Petastorm enjoys all of the benefits associated with the use of the columnar format that we discussed above. However, use of the Parquet extensions introduced by petastorm does come with a caveat: The dataset needs to be created by the petastorm library and all data consumers on the development pipeline will require the petastorm library in order to properly read and parse the data. This requirement is somewhat limiting as one of the most appealing attributes of the Parquet format was its wide software ecosystem for accessing and manipulating data. It is for this reason that we have marked Software Ecosystem in yellow in the evaluation diagram below:
Petastorm includes a number of additional compelling features including support for row group indexing and n-grams. You can learn more about petastorm here and here.
Petastorm Dataset Creation: Dataset creation in petastorm is quite similar to Parquet creation in pyspark. The main differences are in the use of the Unischema and in the materialize_dataset context that wraps the dataset creation.
from petastorm.codecs import CompressedImageCodec, \ NdarrayCodec, ScalarCodecfrom petastorm.etl.dataset_metadata import materialize_datasetfrom petastorm.unischema import Unischema,\ UnischemaField, dict_to_spark_rowfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import IntegerTypedef cifar_to_peta(): MySchema = Unischema('MySchema', [ UnischemaField('image', np.uint8, (32,32,3), NdarrayCodec(), False), UnischemaField('label', np.uint8, (), ScalarCodec(IntegerType()), False), ]) (data, labels), _ = datasets.cifar10.load_data() labels = labels.flatten().tolist() num_procs = 4 # set the number of parallel processes spark = SparkSession.builder.\ master('local[{num_procs}]'.format(num_procs=num_procs))\ .getOrCreate() sc = spark.sparkContext num_samples = 100#len(labels) output_url = 'file:///tmp/petastorm' rowgroup_size_mb = 128 def row_generator(i): return { 'image': data[i], 'label': np.uint8(labels[i]), } # Wrap dataset materialization portion. # Will take care of setting up spark environment variables as # well as save petastorm specific metadata with materialize_dataset(spark, output_url, MySchema, rowgroup_size_mb): rows_rdd = sc.parallelize(range(num_samples)) \ .map(row_generator) \ .map(lambda x: dict_to_spark_row(MySchema, x)) spark.createDataFrame(rows_rdd, MySchema.as_spark_schema()) \ .write \ .mode('overwrite') \ .parquet(output_url)
The row block size is determined in petastorm by the rowgroup_size_mb parameter. In this example we did not take advantage of the codec support included in petastorm. When using large data elements using the codec support could result in significant data compression and savings in storage costs.
The Feather file format is another columnar format which we consider due to its inclusion in TensorFlow I/O (more on this below). While there are many similarities between Feather and Parquet there are also a number of subtle differences resulting from their distinct underlying implementations. A good comparison between the two, including scenarios in which Feather might be the better option, can be found here. It is important to distinguish between version 1 and version 2 of the Feather format. Version 2 supports more data types as well as different types of data compression. Whenever you encounter a review of Feather, bear in mind that it may be based on version 1 of the format.
The primary difference between Feather and Parquet is in the extent of the software ecosystem. Although it is supported by libraries such as pyarrow and pandas, at the time of this writing the Feather format is far less popular than Parquet and the number of supporting frameworks is much more limited. We summarize our Feather file format evaluation in the diagram below:
Being a columnar format the same considerations as above exist for how we chose to rate the columnar support and row filtering properties.
Feather Dataset Creation: In the code block below we demonstrate creation of a Feather file using pyarrow. Feather creation support is built into the pandas library as well. Contrary to the previous dataset creations in which process parallelization was an integral part of the data creation code, here we demonstrate creation of a single file. A full solution would require spawning multiple processes responsible for creating disjoint subsets of the files comprising the full dataset.
from tensorflow.keras import datasetsimport pyarrow as pafrom pyarrow.feather import write_featherdef cifar_to_feather(): (data, labels), _ = datasets.cifar10.load_data() data = [data[i].flatten() for i in range(data.shape[0])] labels = labels.flatten() table = pa.Table.from_arrays([data,labels], ['data','labels']) write_feather(table, '/tmp/df.feather', chunksize=10000)write_feather(table, '/tmp/df.feather', chunksize=10000)
In the example above the size of the row block is determined by the chunksize parameter. Note that, contrary to the previous format creations, we determine the size by the number of records per block rather than the amount of memory per block.
We now turn our attention to the final requirement we listed above, compatibility of the file format with TensorFlow training. No matter how appealing your file format of choice may otherwise be, if you are not able to integrate its use into your training session, or if the speed of the input stream does not meet your needs, then you are back to square one. In this section we will explore some of the tools at our disposal for training in TensorFlow with the file formats we encountered above. In the following section we will measure the speed of the input stream in a number of experiments. Our discussion is based on versions 2.4.1 of TensorFlow, 0.17.1 of TensorFlow I/O, and 0.11.0 of petastorm.
In a typical TensorFlow application we define a tf.data.Dataset, which represents a sequence of data samples, and feed it into the training loop. Setting up a tf.data.Dataset includes defining the source of the data and applying transformations on the data. The source can be data stored in memory or in files. See here for more on how to create a dataset in TensorFlow. Since we have chosen the TFRecord format as our point of reference, let’s start by reviewing how we feed TFRecord files into a TensorFlow training session.
TFRecordDataset: A TFRecordDataset takes a list of TFRecord files as input and produces a sequence of serialized TFRecord data samples. It is typically followed by a tf.data.Dataset.map call in which each individual sample is parsed. The code block below demonstrates the creation of a TFRecordDataset from the Cifar10 data stored in TFRecord format:
import tensorflow as tfdef get_dataset(): autotune = tf.data.experimental.AUTOTUNE def parse(example_proto): feature_description = { 'image': tf.io.FixedLenFeature([], tf.string), 'label': tf.io.FixedLenFeature([], tf.int64)} features = tf.io.parse_single_example(example_proto, feature_description) image = tf.io.decode_raw(features['image'], tf.uint8) image = tf.reshape(image, [32, 32, 3]) return image, label records = tf.data.Dataset.list_files(<path_to_files>+'/*') ds = tf.data.TFRecordDataset(records, num_parallel_reads=autotune) ds = ds.map(parse, num_parallel_calls=autotune) return ds
Our experience with TFRecordDataset has been overall positive; the underlying mechanics for pulling and parsing files seems to be pretty solid and we rarely find ourselves bottlenecked on this part of the pipeline. We have also found the API to be robust, performing well across a wide variety of training environments.
TensorFlow has several other tf.data.Dataset classes for loading data directly from files including FixedLengthRecordDataset and TextLineDataset. Building a TensorFlow dataset from a file format that doesn’t match any of the existing classes requires a bit more creativity. Here we will mention three options in ascending order of complexity.
Create the Dataset from memory source: The first option is to download and parse the files in Python (outside of TensorFlow) and load the data samples into TensorFlow from memory source. One way to do this is using tf.data.Dataset.from_generator as in the pseudo-code block below.
import tensorflow as tfdef get_custom_ds(file_names): def my_generator(): for f in file_names: # download f samples = ... # parse samples from f for sample in samples: yield sample return tf.data.Dataset.from_generator( my_generator, output_types=[tf.uint8,tf.uint8], output_shapes=[[32,32,3],[]])
Parse files in TensorFlow: A second option is to rely on TensorFlow’s tf.io module for downloading and parsing the files. In contrast with the previous solution, here the file management is part of the TensorFlow execution graph. Here is one way to do this using the tf.data.Dataset.list_files and tf.data.Dataset.interleave APIs:
import tensorflow as tfdef get_custom_ds(): autotune = tf.data.experimental.AUTOTUNE filenames = tf.data.Dataset.list_files(<path_to_files>+'/*', shuffle=True) def make_ds(path): bytestring = tf.io.read_file(path) samples = ... # parse bytestring using tf functions return tf.data.Dataset.from_tensor_slices(samples) ds = filenames.interleave(make_ds, num_parallel_calls=autotune, deterministic=False) return ds
Create a custom Dataset class: The last option we mention is to create a new tf.data.Dataset class specially designed to handle your data format. This option requires the most technical prowess. It also offers the highest potential reward as measured by the speed of the data input stream. One way to implement this is to modify the TensorFlow C++ code and rebuild TensorFlow from source. For example, one could clone the TFRecordDataset implementation and overwrite only the portions of the code specifically relevant to parsing the format. In this way one would hope to be able to enjoy the same performance benefits as the TFRecordDataset. The disadvantage to this approach is that it will require maintaining a specialized version of TensorFlow. In particular, every time you upgrade to a new version of TensorFlow you will need to rebuild your custom solution. Note that custom Dataset class creation can also be implemented within TensorFlow I/O, rather than TensorFlow, as describe in this post.
While any of the above solutions can be appropriately tuned to maximize performance, it is not always that easy. To make matters worse, you may find that the ideal configurations (e.g. number of underling system processes) may vary greatly based on the training environment. In this sense using a dedicated Dataset class such as TFRecordDataset has a meaningful advantage over the customized solutions we have described. The next two solutions we will see will use Dataset classes specifically designed for our file format of choice.
TensorFlow I/O (tfio) is an extension package for TensorFlow that adds support for a number of file systems and file formats that are not included in TensorFlow. In particular, tfio defines the tfio.arrow.ArrowFeatherDataset class for creating datasets based on the Feather format and the tfio.v0.IODataset.from_parquet function for creating datasets based on the Parquet format.
TensorFlow I/O Feather Dataset: The tfio.arrow.ArrowFeatherDataset class is just one of a collection of APIs designed to support the Apache Arrow format. For a full overview of the tfio Apache Arrow offering, be sure to check out this blog. In the code block below we demonstrate the use of a tfio.arrow.ArrowFeatherDataset based on the Cifar10 data stored in Feather format that we created above.
import tensorflow as tfimport tensorflow_io.arrow as arrow_iodef get_dataset(): filenames = <list of feather files> ds = arrow_io.ArrowFeatherDataset(filenames, columns=(0, 1), output_types=(tf.uint8, tf.uint8), output_shapes=([32*32*3,], []), batch_mode='auto') ds = ds.unbatch() return ds
By setting the batch_mode argument to ‘auto’ we are choosing to have the dataset return Parquet row blocks. Therefore the first call we apply is to unbatch the records so as to return individual samples. This strategy should result in better performance than reading samples individually.
We have found the throughput performance to improve if we combine the use of tfio.arrow.ArrowFeatherDataset with tf.data.Dataset.interleave:
import tensorflow as tfimport tensorflow_io as tfiodef get_dataset(): autotune = tf.data.experimental.AUTOTUNE filenames = tf.data.Dataset.list_files(<path_to_files>+'/*', shuffle=True) def make_ds(file): ds = arrow_io.ArrowFeatherDataset( [file], [0,1], output_types=(tf.uint8, tf.uint8), output_shapes=([32*32*3,], []), batch_mode='auto') return ds ds = filenames.interleave(make_ds, num_parallel_calls=autotune, deterministic=False) ds = ds.unbatch() return ds
TensorFlow I/O Parquet Dataset: In contrast with the Feather Dataset class, the from_parquet function receives a single Parquet file. However, we can overcome this limitation by using the tf.data.Dataset.interleave as shown below on the Cifar10 dataset stored in Parquet format:
import tensorflow as tfimport tensorflow_io as tfiodef get_dataset(): autotune = tf.data.experimental.AUTOTUNE filenames = tf.data.Dataset.list_files(<path_to_files>+'/*', shuffle=True) def parquet_ds(file): ds = tfio.IODataset.from_parquet(file, {'image': tf.string, 'label': tf.int32}) return ds ds = filenames.interleave(parquet_ds, num_parallel_calls=autotune, deterministic=False) def parse(example): image = tf.io.decode_raw(example['image'], tf.uint8) image = tf.reshape(image, [32, 32, 3]) label = example['label'] return image, label ds = ds.map(parse,num_parallel_calls=autotune) return ds
The petastorm library TensorFlow API defines the make_petastorm_dataset function for creating a TensorFlow tf.data.Dataset from a petastorm reader (petastorm.reader.Reader). The source of this dataset can be in either Petastorm format or raw Parquet format. To read from a dataset in Petastorm format we create the reader using the make_reader API. To read from a dataset in Parquet format we create the reader using the make_batch_reader API. There are a few delicate differences between the two readers described in the table here. Note that a TensorFlow tf.data.Dataset created from Petastorm format returns sequences of single data samples whereas a TensorFlow tf.data.Dataset created from raw Parquet format returns batches of data samples the size of which is determined by the Parquet row group size.
In the code block below we demonstrate the use of the make_petastorm_dataset API for creating a TensorFlow tf.data.Dataset from the Cifar10 data stored in Petastorm format.
from petastorm import make_readerfrom petastorm.tf_utils import make_petastorm_datasetdef get_dataset(): with make_reader('<path to data>') as reader: ds = make_petastorm_dataset(reader) return ds
In the code block below we demonstrate the use of the make_petastorm_dataset API for creating a TensorFlow tf.data.Dataset from the Cifar10 data stored in Parquet format.
from petastorm import make_batch_readerfrom petastorm.tf_utils import make_petastorm_datasetdef get_dataset(): autotune = tf.data.experimental.AUTOTUNE with make_batch_reader('<path to data>') as reader: ds = make_petastorm_dataset(reader) ds = ds.unbatch() def parse(example): image, label = example image = tf.io.decode_raw(image, tf.uint8) image = tf.reshape(image, [32, 32, 3]) return image, label ds = ds.map(parse,num_parallel_calls=autotune) return ds
Note how we use the unbatch routine so as to return individual samples.
In this section we share the results of several experiments. All experiments were run on a c5.2xlarge Amazon EC2 instance type (which has 8 vCPUs) with TensorFlow version 2.4.1, TensorFlow I/O version 0.17.1, and petastorm version 0.11.0. The experiments were divided into two parts. First we experimented with different methods of feeding the Cifar10 data stored in the file formats we have discussed into a TensorFlow session. We created multiple copies of the data in order to artificially inflate the dataset. For these experiments we chose to set the training batch size to 1024.
In order to assess how the size of the sample records impacted the relative performance, we ran a second set of tests in which we added a random byte array, 2 MB in size, to each Cifar10 data sample. For these experiments we chose to set the training batch size to 16.
For all experiments the datasets were divided into underlying files of size 100–200 MB.
Since we were interested in measuring only the training data throughput, we chose to forgo building a training model and instead iterated directly on the TensorFlow dataset as in the following code block.
import timeds = get_dataset().batch(batch_size)round = 0start_time = time.time()for x in ds: round = round + 1 if round % 100 == 0: print("round {}: epoch time: {}". format(round, time.time() - start_time)) start_time = time.time() if round == 2000: break
Note that in the case of petastorm the dataset traversal must be moved to within the petastorm reader context.
Our intention in sharing these results is to give you an idea of what your starting point might be and the amount of optimization effort that might be required. We strongly advise against drawing any conclusions from these results regarding your own use case for several reasons:
The performance of the solutions is likely to vary greatly based on the model, the dataset, and the training environment.For a given use case, the performance of each solution will vary based on the specifics of how both the format and the TensorFlow dataset are configured, including: the size of each file, the size of the row groups, the use of compression schemes, the number of worker processes, the size of each sample batch, and more.The experiments measure the maximum throughput of the solutions by iterating directly over the TensorFlow datasets. In practice, the throughput needs to be high enough to keep the training session busy. In other words, as long as we are not bottlenecked on IO, we might be perfectly content with a throughput that is lower than the maximum.By the time you read this post the versions of the libraries I have used might be outdated. Newer versions of the libraries might include changes that impact their performance.Last but not least is the likelihood of bugs in my experiments. When you find them please drop me a line.
The performance of the solutions is likely to vary greatly based on the model, the dataset, and the training environment.
For a given use case, the performance of each solution will vary based on the specifics of how both the format and the TensorFlow dataset are configured, including: the size of each file, the size of the row groups, the use of compression schemes, the number of worker processes, the size of each sample batch, and more.
The experiments measure the maximum throughput of the solutions by iterating directly over the TensorFlow datasets. In practice, the throughput needs to be high enough to keep the training session busy. In other words, as long as we are not bottlenecked on IO, we might be perfectly content with a throughput that is lower than the maximum.
By the time you read this post the versions of the libraries I have used might be outdated. Newer versions of the libraries might include changes that impact their performance.
Last but not least is the likelihood of bugs in my experiments. When you find them please drop me a line.
The results demonstrate the strength of the TFRecord format and TFRecordDataset. In particular, we can see their stability despite variations in the environment settings. At the same time, some of the other experiments resulted in training throughputs that do not pale in comparison. While we find the results to be encouraging, it is important to note the instability of the alternative solutions across the two cases we tested. Solutions that perform well (compared to the TFRecord format) in one scenario appear to break down in the other. It would seem that, in contrast with the use of the TFRecord format, adapting the other formats for use in varying training settings might require some extra effort. Given the advantages of the alternative formats that we have discussed in this post, this effort may be well worth its while.
An additional metric of interest is the CPU utilization associated with each of the options. In a recent blog post we discussed the possibility of bottlenecks in the training pipeline that are caused by reaching maximum utilization of one or more of the CPUs. In cases where this possibility is a concern, it would be wise to assess how different decisions related to the data storage affect the CPU utilization of loading and parsing the data. These include the choice of file format, data compression (and decompression), TensorFlow dataset creation method, and more. In the chart below we list the average CPU utilization for the three most performant solutions of the Cifar10 experiments. The CPU utilization was captured from the Amazon EC2 Instance Metrics in Amazon CloudWatch. Since the instance we used has 8 vCPUs, the maximum utilization is 800%.
Despite the clear favoritism of TensorFlow towards the TFRecord format, some of its properties leave it wanting. While the TFRecord format is great for training, it is unlikely to be suitable to any of the other consumers of the data on the development pipeline. In this post we have discussed several formats that better address the overall project needs and evaluated their compatibility to TensorFlow training. Although some effort may be required to support different training scenarios, our conclusion is that there are legitimate alternatives to the TFRecord format.
|
[
{
"code": null,
"e": 942,
"s": 172,
"text": "Machine learning is all about the data. To successfully train a sophisticated model you will need a high quality training dataset; a dataset that is sufficiently large, accurately labeled, and correctly represents the distribution of data samples in the real world. However, no less important is proper management of the data. By data management we are referring to how and where the data is stored, the ways in which it is accessed, and the transformations it undergoes during the development life-cycle. The focus of this post is on the file format used to store the training data and the implications it can have on the model training. Choosing the file format is one of the many important decisions you will need to make when defining your machine learning project."
},
{
"code": null,
"e": 1407,
"s": 942,
"text": "This post is comprised of four sections. In the first section we will identify some of the properties that we would like our file format to have. In the second section we will review potential file formats and evaluate them against the desired properties we have found. Next we will survey different options for streaming these formats into a TensorFlow training session. In the last section we will describe a few experiments we ran to test some of these options."
},
{
"code": null,
"e": 2036,
"s": 1407,
"text": "Before we dive in, let’s set the stage. We will assume in this post that the size of our training dataset necessitates storing it in a distributed storage system, e.g. hundreds of terabytes. In the examples below we will use Amazon S3 for data storage, but the principals applies equally to any other distributed storage system. The data will likely be accessed by several consumers during the development cycle and for various purposes including data creation, data analysis, model training, and more. Our focus will be on training in TensorFlow, although much of what we will say pertains to other training frameworks as well."
},
{
"code": null,
"e": 2618,
"s": 2036,
"text": "The underlying assumption of this post is that a file format for our data is required, i.e. that we require one or more files for: 1. grouping together all elements/columns/features of single data samples, as well as 2. grouping together multiple data samples. Of course, one could envision scenarios in which one might choose to maintain all elements of all samples in individual files and in their raw format. However, in many cases, especially if the file sizes are small (e.g. several KBs) this strategy is likely to severely degrade the runtime performance of the data access."
},
{
"code": null,
"e": 3264,
"s": 2618,
"text": "The intention of this post is to highlight some of the important considerations when choosing a file format and to discuss a few of the different options available today. We will mention a number of formats as well as a number of software development frameworks and tools. These mentions should not be interpreted as an endorsement. The appropriate choice for you is likely to be based on a wide range of considerations some of which may be beyond the scope of this discussion. The post will include a number of simple code snippets. These are presented for the purposes of demonstration only and should not be viewed as optimal implementations."
},
{
"code": null,
"e": 3635,
"s": 3264,
"text": "The landscape of machine learning tools is extremely dynamic. Some of the formats and tools we will mention continue to evolve and some of the comments we will make may become outdated by the time you read this. Take care to keep track of announcements of new versions and new tools and be sure to make your design decisions on the most up to date information available."
},
{
"code": null,
"e": 3711,
"s": 3635,
"text": "Please do not hesitate to reach out to me with any comments or corrections."
},
{
"code": null,
"e": 3837,
"s": 3711,
"text": "To facilitate this discussion let’s take a look at a common file format used for training in TensorFlow, the TFRecord format."
},
{
"code": null,
"e": 4549,
"s": 3837,
"text": "TFRecord is a format based on protocol buffers specifically designed for use with TensorFlow. A TFRecord file is comprised of sequences of serialized binary samples. Each sample represents a tf.train.Example which, in turn, represents a dictionary of string to value mappings. The sequential nature of the TFRecord format facilitates high data streaming throughput. In particular, one does not need to download and open a full file in order to start traversing its contents. Moreover, the TensorFlow tf.data module includes the highly optimized TFRecordDataset class for building input pipelines based on data stored in TFRecord files. However, the TFRecord format is not without its faults. Here we name a few:"
},
{
"code": null,
"e": 5346,
"s": 4549,
"text": "Single purpose: The TFRecord format is unlikely to satisfy the needs of any of the other data consumers on the development pipeline. It is common for development teams to maintain their data in a different format and create a derivative of the data in TFRecord format specifically for the purpose of training. Storing multiple copies of your data is not ideal, especially when your data set is large. Aside from the added cost of data storage, the implication is that every time there is a change to the core data set a new TFRecord copy needs to be generated. We may wish update the core data records based on findings from the training session, in which case we will also need to maintain a mapping between the generated TFRecord records and their corresponding entries in the core data format."
},
{
"code": null,
"e": 6318,
"s": 5346,
"text": "Extracting partial record data: Another problem with the TFRecord format arises when our training model requires only a subset of the TFRecord elements. For example, suppose that we have a multi-headed model that performs different types of pixel level segmentation on an input image. Each record in the data set contains multiple ground truth images corresponding to the multiple heads of the model. Now we decide to train a version of the model with just a single head. The trivial solution would be to feed in the complete TFRecord and simply ignore the unnecessary fields. However, the need to pull and parse extraneous data can severely impact the throughput of our input pipeline and thus the speed of our training. To reduce the risk of bottlenecks in the pipeline, we would need to create an additional copy of the data containing only the content relevant for the specific training at hand. This further exacerbates the data duplication issue we discussed above."
},
{
"code": null,
"e": 7357,
"s": 6318,
"text": "Record filtering: Sometimes we are interested in traversing records that have specific entry values. The trivial way to do this is to iterate over all of the data and simply drop any record that does not match our filter (e.g. using tf.filter). As before, this can introduce considerable overhead to the data input pipeline and result in significant starvation of the training loop. In previous posts (here and here) we demonstrated a need to filter input images based on whether they contained pink cars. The solution we proposed there was to store different data classes in separate files. Whenever the need to filter arose, we could traverse only the files associated with the filter. However, this solution requires us to be able to anticipate the filters we will need to apply which is not always possible. If we encounter a need to apply a filter that we did not anticipate we could either recreate the data with an additional partition or fall back to the trivial method of dropping non-matching samples. Neither option is optimal."
},
{
"code": null,
"e": 8127,
"s": 7357,
"text": "Data transformation: A typical input data pipeline might include multiple operations on the input data including data warping, augmentations, batching, and more. TensorFlow offers a set of built-in data processing operations that can be added to the input data pipeline computation graph via the tf.data.Dataset.map function. However, you might find that the data processing you require cannot be implemented efficiently using TensorFlow. One option would be to apply a block of native python code using tf.py_function, but this may limit your data throughput performance due to the Python Global Interpreter Lock (GIL). Many use cases call for using a format that enables applying operations in native python before being entered into the TensorFlow computation graph."
},
{
"code": null,
"e": 8594,
"s": 8127,
"text": "Based on the discussion above let us compile a list of some of the properties we are looking for in our file format. Given the added cost and complexities of storing multiple copies of our data, we will restrict ourselves from now on to a single copy of the data, i.e. we must choose a format that satisfies the needs of all data consumers. This list is not intended to be all inclusive. Additional requirements based on the particular use-case should be considered."
},
{
"code": null,
"e": 8773,
"s": 8594,
"text": "Distributed Storage: The file format and supporting libraries must support the option of storing large datasets in distributed storage settings such as Amazon S3, HDFS, and more."
},
{
"code": null,
"e": 8904,
"s": 8773,
"text": "Software Ecosystem: We require a strong ecosystem of libraries providing a range of tools for analyzing and manipulating the data."
},
{
"code": null,
"e": 9038,
"s": 8904,
"text": "Columnar Support: The file format and supporting libraries must support efficient extraction of a subset of features per data sample."
},
{
"code": null,
"e": 9163,
"s": 9038,
"text": "Row Filtering: The file format and supporting libraries should support efficient filtering on the values of sample features."
},
{
"code": null,
"e": 9287,
"s": 9163,
"text": "TensorFlow Integration: The format must facilitate efficient data streaming from storage into TensorFlow training sessions."
},
{
"code": null,
"e": 10198,
"s": 9287,
"text": "One requirement for training that we have left out of our discussion is data shuffling. It is common practice to shuffle the training data before each traversal (epoch). Were we able to randomly access any sample in the dataset, data shuffling would be easy. However, such random access to individual samples comes at the expense of performance, certainly in a distributed storage setting. Instead, one must resort to other mechanisms for shuffling including combinations of: shuffling samples during data creation, shuffling on the list of files that comprise the full dataset, interleaving between multiple datasets, and using an appropriately large shuffle buffer during training (e.g. see tf.data.Dataset.shuffle). We have chosen not to state shuffling as a requirement of the file format as, in our view, in the training scenario we have presented this challenge will exist with any choice of file format."
},
{
"code": null,
"e": 10376,
"s": 10198,
"text": "In the next section we will evaluate the compatibility of several file formats for training. In the following section we will discuss options for streaming them into TensorFlow."
},
{
"code": null,
"e": 10572,
"s": 10376,
"text": "A full survey of data formats for deep learning is beyond the scope of this post. We will limit our discussion to just a few strong candidates. More extensive surveys abound. Here is one example:"
},
{
"code": null,
"e": 10595,
"s": 10572,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10812,
"s": 10595,
"text": "You can also check out a recent post of mine that covers the relatively new webdataset format, an intriguing solution specially geared towards developers who wish to maintain their data in the most raw form possible."
},
{
"code": null,
"e": 11072,
"s": 10812,
"text": "We will measure each format according to the metrics we chose above as in the below diagram in which we summarize our evaluation of the TFRecord format. We use green to indicate full support, yellow to indicate partial support, and red to indicate no support."
},
{
"code": null,
"e": 11406,
"s": 11072,
"text": "One of the more compelling file format options is Apache Parquet. Apache Parquet has an extensive software ecosystem with multiple frameworks and tools supporting a wide variety of data processing operations. It is especially popular among data analysts. The possibility of basing our training on the same format is quite attractive."
},
{
"code": null,
"e": 12376,
"s": 11406,
"text": "One of the main attributes of the Parquet format to which it owes much of its success is the fact that is a columnar storage format. Contrary to other formats such as CSV or TFRecord, in which each row of data is stored sequentially, in a columnar data format columns of data are stored together. Each file in the dataset is divided into row blocks each of which contains multiple samples. Within a row block the sample data is stored according to columns, i.e. the values of the first field of all of the samples appear first and are followed by the values of the second field of all of the samples, and so on. The columnar nature of the format facilitates efficient data analytics since queries can be made on subsets of columns without needing to load entire data records. Furthermore, grouping together columns can lead to more efficient compression of data and thus to reduced storage costs. Check out this post for more on the advantages of columnar data storage."
},
{
"code": null,
"e": 12447,
"s": 12376,
"text": "The following diagram summarizes our evaluation of the Parquet format:"
},
{
"code": null,
"e": 13231,
"s": 12447,
"text": "Being a columnar format, Parquet enables efficient extraction of subsets of data columns. In addition, we can also take advantage of the columnar nature of the format to facilitate row filtering by: 1. first extracting the column on which we are filtering and then 2. extracting the rest of columns only for rows that match the filter. However, being that efficient data extraction might rely on extracting the columnar data of full blocks of rows, it is unclear that this method would perform well. Therefore we have marked this capability in yellow. A more performant filtering approach might require separating samples into different Parquet files according to class during the dataset creation, as described above. In pyspark this can be done using the partitionBy functionality."
},
{
"code": null,
"e": 13478,
"s": 13231,
"text": "Parquet Dataset Creation: In the code block below we demonstrate creation of a Parquet dataset from the popular Cifar10 dataset using the pyspark library. Parquet creation is supported by additional libraries as well including pandas and pyarrow."
},
{
"code": null,
"e": 14693,
"s": 13478,
"text": "from tensorflow.keras import datasetsfrom pyspark.sql import SparkSession, Rowfrom pyspark.sql.types import StructType, \\ StructField, IntegerType, BinaryTypedef cifar_to_parquet(): schema = StructType( [StructField(\"image\", BinaryType(), True), StructField(\"label\", IntegerType(), True)]) (data, labels), _ = datasets.cifar10.load_data() labels = labels.flatten().tolist() num_procs = 4 # set the number of parallel processes spark = SparkSession.builder\\ .master('local[{num_procs}]'.format(num_procs=num_procs))\\ .getOrCreate() sc = spark.sparkContext num_samples = len(labels) output_url = 'file:///tmp/parquet' def row_generator(i): return { 'image': bytearray(data[i].tobytes()), 'label': labels[i], } # optionally configure the size of row blocks # blockSize = 1024 * 1024 * 16 # 16 MB # sc._jsc.hadoopConfiguration()\\ # .setInt(\"parquet.block.size\", blockSize) rows_rdd = sc.parallelize(range(num_samples))\\ .map(row_generator)\\ .map(lambda x: Row(**x)) spark.createDataFrame(rows_rdd, schema)\\ .write.mode('overwrite')\\ .parquet(output_url)"
},
{
"code": null,
"e": 15176,
"s": 14693,
"text": "While the number of files that comprise the dataset, the sizes of each file, and the size of each row block can have a meaningful impact on the performance of data loading, controlling these parameters can sometimes be a little tricky. In pyspark the row block size can be set using sc._jsc.hadoopConfiguration as in the comment in the code block above (the default value is 128 MB) and the sizes and number of files by the number of parallel processes and by the coalesce function."
},
{
"code": null,
"e": 15295,
"s": 15176,
"text": "Through appropriate configuration, the script can be modified to write directly to Amazon S3 (see e.g. here and here)."
},
{
"code": null,
"e": 16779,
"s": 15295,
"text": "The petastorm library was created with the specific goal of unifying the dataset used by all data consumers on the development pipeline (see here). Although petastorm abstracts the underlying storage format, the default format used is Apache Parquet. More accurately, petastorm extends Apache Parquet by providing additional schema information in the Unischema structure, supporting multi-dimensional data, and supporting data compressing codecs. Henceforth we will assume the use of the extended Parquet as the underlying format and abuse the use of the term petastorm by using it to refer both to the library itself as well as to the file format created by the library. To distinguish between the two we will use capitalization when referring to the Petastorm format. The use of Parquet as the underlying format means that Petastorm enjoys all of the benefits associated with the use of the columnar format that we discussed above. However, use of the Parquet extensions introduced by petastorm does come with a caveat: The dataset needs to be created by the petastorm library and all data consumers on the development pipeline will require the petastorm library in order to properly read and parse the data. This requirement is somewhat limiting as one of the most appealing attributes of the Parquet format was its wide software ecosystem for accessing and manipulating data. It is for this reason that we have marked Software Ecosystem in yellow in the evaluation diagram below:"
},
{
"code": null,
"e": 16945,
"s": 16779,
"text": "Petastorm includes a number of additional compelling features including support for row group indexing and n-grams. You can learn more about petastorm here and here."
},
{
"code": null,
"e": 17177,
"s": 16945,
"text": "Petastorm Dataset Creation: Dataset creation in petastorm is quite similar to Parquet creation in pyspark. The main differences are in the use of the Unischema and in the materialize_dataset context that wraps the dataset creation."
},
{
"code": null,
"e": 18851,
"s": 17177,
"text": "from petastorm.codecs import CompressedImageCodec, \\ NdarrayCodec, ScalarCodecfrom petastorm.etl.dataset_metadata import materialize_datasetfrom petastorm.unischema import Unischema,\\ UnischemaField, dict_to_spark_rowfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import IntegerTypedef cifar_to_peta(): MySchema = Unischema('MySchema', [ UnischemaField('image', np.uint8, (32,32,3), NdarrayCodec(), False), UnischemaField('label', np.uint8, (), ScalarCodec(IntegerType()), False), ]) (data, labels), _ = datasets.cifar10.load_data() labels = labels.flatten().tolist() num_procs = 4 # set the number of parallel processes spark = SparkSession.builder.\\ master('local[{num_procs}]'.format(num_procs=num_procs))\\ .getOrCreate() sc = spark.sparkContext num_samples = 100#len(labels) output_url = 'file:///tmp/petastorm' rowgroup_size_mb = 128 def row_generator(i): return { 'image': data[i], 'label': np.uint8(labels[i]), } # Wrap dataset materialization portion. # Will take care of setting up spark environment variables as # well as save petastorm specific metadata with materialize_dataset(spark, output_url, MySchema, rowgroup_size_mb): rows_rdd = sc.parallelize(range(num_samples)) \\ .map(row_generator) \\ .map(lambda x: dict_to_spark_row(MySchema, x)) spark.createDataFrame(rows_rdd, MySchema.as_spark_schema()) \\ .write \\ .mode('overwrite') \\ .parquet(output_url)"
},
{
"code": null,
"e": 19148,
"s": 18851,
"text": "The row block size is determined in petastorm by the rowgroup_size_mb parameter. In this example we did not take advantage of the codec support included in petastorm. When using large data elements using the codec support could result in significant data compression and savings in storage costs."
},
{
"code": null,
"e": 19838,
"s": 19148,
"text": "The Feather file format is another columnar format which we consider due to its inclusion in TensorFlow I/O (more on this below). While there are many similarities between Feather and Parquet there are also a number of subtle differences resulting from their distinct underlying implementations. A good comparison between the two, including scenarios in which Feather might be the better option, can be found here. It is important to distinguish between version 1 and version 2 of the Feather format. Version 2 supports more data types as well as different types of data compression. Whenever you encounter a review of Feather, bear in mind that it may be based on version 1 of the format."
},
{
"code": null,
"e": 20211,
"s": 19838,
"text": "The primary difference between Feather and Parquet is in the extent of the software ecosystem. Although it is supported by libraries such as pyarrow and pandas, at the time of this writing the Feather format is far less popular than Parquet and the number of supporting frameworks is much more limited. We summarize our Feather file format evaluation in the diagram below:"
},
{
"code": null,
"e": 20350,
"s": 20211,
"text": "Being a columnar format the same considerations as above exist for how we chose to rate the columnar support and row filtering properties."
},
{
"code": null,
"e": 20837,
"s": 20350,
"text": "Feather Dataset Creation: In the code block below we demonstrate creation of a Feather file using pyarrow. Feather creation support is built into the pandas library as well. Contrary to the previous dataset creations in which process parallelization was an integral part of the data creation code, here we demonstrate creation of a single file. A full solution would require spawning multiple processes responsible for creating disjoint subsets of the files comprising the full dataset."
},
{
"code": null,
"e": 21282,
"s": 20837,
"text": "from tensorflow.keras import datasetsimport pyarrow as pafrom pyarrow.feather import write_featherdef cifar_to_feather(): (data, labels), _ = datasets.cifar10.load_data() data = [data[i].flatten() for i in range(data.shape[0])] labels = labels.flatten() table = pa.Table.from_arrays([data,labels], ['data','labels']) write_feather(table, '/tmp/df.feather', chunksize=10000)write_feather(table, '/tmp/df.feather', chunksize=10000)"
},
{
"code": null,
"e": 21526,
"s": 21282,
"text": "In the example above the size of the row block is determined by the chunksize parameter. Note that, contrary to the previous format creations, we determine the size by the number of records per block rather than the amount of memory per block."
},
{
"code": null,
"e": 22230,
"s": 21526,
"text": "We now turn our attention to the final requirement we listed above, compatibility of the file format with TensorFlow training. No matter how appealing your file format of choice may otherwise be, if you are not able to integrate its use into your training session, or if the speed of the input stream does not meet your needs, then you are back to square one. In this section we will explore some of the tools at our disposal for training in TensorFlow with the file formats we encountered above. In the following section we will measure the speed of the input stream in a number of experiments. Our discussion is based on versions 2.4.1 of TensorFlow, 0.17.1 of TensorFlow I/O, and 0.11.0 of petastorm."
},
{
"code": null,
"e": 22757,
"s": 22230,
"text": "In a typical TensorFlow application we define a tf.data.Dataset, which represents a sequence of data samples, and feed it into the training loop. Setting up a tf.data.Dataset includes defining the source of the data and applying transformations on the data. The source can be data stored in memory or in files. See here for more on how to create a dataset in TensorFlow. Since we have chosen the TFRecord format as our point of reference, let’s start by reviewing how we feed TFRecord files into a TensorFlow training session."
},
{
"code": null,
"e": 23108,
"s": 22757,
"text": "TFRecordDataset: A TFRecordDataset takes a list of TFRecord files as input and produces a sequence of serialized TFRecord data samples. It is typically followed by a tf.data.Dataset.map call in which each individual sample is parsed. The code block below demonstrates the creation of a TFRecordDataset from the Cifar10 data stored in TFRecord format:"
},
{
"code": null,
"e": 23851,
"s": 23108,
"text": "import tensorflow as tfdef get_dataset(): autotune = tf.data.experimental.AUTOTUNE def parse(example_proto): feature_description = { 'image': tf.io.FixedLenFeature([], tf.string), 'label': tf.io.FixedLenFeature([], tf.int64)} features = tf.io.parse_single_example(example_proto, feature_description) image = tf.io.decode_raw(features['image'], tf.uint8) image = tf.reshape(image, [32, 32, 3]) return image, label records = tf.data.Dataset.list_files(<path_to_files>+'/*') ds = tf.data.TFRecordDataset(records, num_parallel_reads=autotune) ds = ds.map(parse, num_parallel_calls=autotune) return ds"
},
{
"code": null,
"e": 24171,
"s": 23851,
"text": "Our experience with TFRecordDataset has been overall positive; the underlying mechanics for pulling and parsing files seems to be pretty solid and we rarely find ourselves bottlenecked on this part of the pipeline. We have also found the API to be robust, performing well across a wide variety of training environments."
},
{
"code": null,
"e": 24514,
"s": 24171,
"text": "TensorFlow has several other tf.data.Dataset classes for loading data directly from files including FixedLengthRecordDataset and TextLineDataset. Building a TensorFlow dataset from a file format that doesn’t match any of the existing classes requires a bit more creativity. Here we will mention three options in ascending order of complexity."
},
{
"code": null,
"e": 24795,
"s": 24514,
"text": "Create the Dataset from memory source: The first option is to download and parse the files in Python (outside of TensorFlow) and load the data samples into TensorFlow from memory source. One way to do this is using tf.data.Dataset.from_generator as in the pseudo-code block below."
},
{
"code": null,
"e": 25205,
"s": 24795,
"text": "import tensorflow as tfdef get_custom_ds(file_names): def my_generator(): for f in file_names: # download f samples = ... # parse samples from f for sample in samples: yield sample return tf.data.Dataset.from_generator( my_generator, output_types=[tf.uint8,tf.uint8], output_shapes=[[32,32,3],[]])"
},
{
"code": null,
"e": 25536,
"s": 25205,
"text": "Parse files in TensorFlow: A second option is to rely on TensorFlow’s tf.io module for downloading and parsing the files. In contrast with the previous solution, here the file management is part of the TensorFlow execution graph. Here is one way to do this using the tf.data.Dataset.list_files and tf.data.Dataset.interleave APIs:"
},
{
"code": null,
"e": 26059,
"s": 25536,
"text": "import tensorflow as tfdef get_custom_ds(): autotune = tf.data.experimental.AUTOTUNE filenames = tf.data.Dataset.list_files(<path_to_files>+'/*', shuffle=True) def make_ds(path): bytestring = tf.io.read_file(path) samples = ... # parse bytestring using tf functions return tf.data.Dataset.from_tensor_slices(samples) ds = filenames.interleave(make_ds, num_parallel_calls=autotune, deterministic=False) return ds"
},
{
"code": null,
"e": 27062,
"s": 26059,
"text": "Create a custom Dataset class: The last option we mention is to create a new tf.data.Dataset class specially designed to handle your data format. This option requires the most technical prowess. It also offers the highest potential reward as measured by the speed of the data input stream. One way to implement this is to modify the TensorFlow C++ code and rebuild TensorFlow from source. For example, one could clone the TFRecordDataset implementation and overwrite only the portions of the code specifically relevant to parsing the format. In this way one would hope to be able to enjoy the same performance benefits as the TFRecordDataset. The disadvantage to this approach is that it will require maintaining a specialized version of TensorFlow. In particular, every time you upgrade to a new version of TensorFlow you will need to rebuild your custom solution. Note that custom Dataset class creation can also be implemented within TensorFlow I/O, rather than TensorFlow, as describe in this post."
},
{
"code": null,
"e": 27596,
"s": 27062,
"text": "While any of the above solutions can be appropriately tuned to maximize performance, it is not always that easy. To make matters worse, you may find that the ideal configurations (e.g. number of underling system processes) may vary greatly based on the training environment. In this sense using a dedicated Dataset class such as TFRecordDataset has a meaningful advantage over the customized solutions we have described. The next two solutions we will see will use Dataset classes specifically designed for our file format of choice."
},
{
"code": null,
"e": 27976,
"s": 27596,
"text": "TensorFlow I/O (tfio) is an extension package for TensorFlow that adds support for a number of file systems and file formats that are not included in TensorFlow. In particular, tfio defines the tfio.arrow.ArrowFeatherDataset class for creating datasets based on the Feather format and the tfio.v0.IODataset.from_parquet function for creating datasets based on the Parquet format."
},
{
"code": null,
"e": 28374,
"s": 27976,
"text": "TensorFlow I/O Feather Dataset: The tfio.arrow.ArrowFeatherDataset class is just one of a collection of APIs designed to support the Apache Arrow format. For a full overview of the tfio Apache Arrow offering, be sure to check out this blog. In the code block below we demonstrate the use of a tfio.arrow.ArrowFeatherDataset based on the Cifar10 data stored in Feather format that we created above."
},
{
"code": null,
"e": 28778,
"s": 28374,
"text": "import tensorflow as tfimport tensorflow_io.arrow as arrow_iodef get_dataset(): filenames = <list of feather files> ds = arrow_io.ArrowFeatherDataset(filenames, columns=(0, 1), output_types=(tf.uint8, tf.uint8), output_shapes=([32*32*3,], []), batch_mode='auto') ds = ds.unbatch() return ds"
},
{
"code": null,
"e": 29067,
"s": 28778,
"text": "By setting the batch_mode argument to ‘auto’ we are choosing to have the dataset return Parquet row blocks. Therefore the first call we apply is to unbatch the records so as to return individual samples. This strategy should result in better performance than reading samples individually."
},
{
"code": null,
"e": 29208,
"s": 29067,
"text": "We have found the throughput performance to improve if we combine the use of tfio.arrow.ArrowFeatherDataset with tf.data.Dataset.interleave:"
},
{
"code": null,
"e": 29879,
"s": 29208,
"text": "import tensorflow as tfimport tensorflow_io as tfiodef get_dataset(): autotune = tf.data.experimental.AUTOTUNE filenames = tf.data.Dataset.list_files(<path_to_files>+'/*', shuffle=True) def make_ds(file): ds = arrow_io.ArrowFeatherDataset( [file], [0,1], output_types=(tf.uint8, tf.uint8), output_shapes=([32*32*3,], []), batch_mode='auto') return ds ds = filenames.interleave(make_ds, num_parallel_calls=autotune, deterministic=False) ds = ds.unbatch() return ds"
},
{
"code": null,
"e": 30158,
"s": 29879,
"text": "TensorFlow I/O Parquet Dataset: In contrast with the Feather Dataset class, the from_parquet function receives a single Parquet file. However, we can overcome this limitation by using the tf.data.Dataset.interleave as shown below on the Cifar10 dataset stored in Parquet format:"
},
{
"code": null,
"e": 30947,
"s": 30158,
"text": "import tensorflow as tfimport tensorflow_io as tfiodef get_dataset(): autotune = tf.data.experimental.AUTOTUNE filenames = tf.data.Dataset.list_files(<path_to_files>+'/*', shuffle=True) def parquet_ds(file): ds = tfio.IODataset.from_parquet(file, {'image': tf.string, 'label': tf.int32}) return ds ds = filenames.interleave(parquet_ds, num_parallel_calls=autotune, deterministic=False) def parse(example): image = tf.io.decode_raw(example['image'], tf.uint8) image = tf.reshape(image, [32, 32, 3]) label = example['label'] return image, label ds = ds.map(parse,num_parallel_calls=autotune) return ds"
},
{
"code": null,
"e": 31755,
"s": 30947,
"text": "The petastorm library TensorFlow API defines the make_petastorm_dataset function for creating a TensorFlow tf.data.Dataset from a petastorm reader (petastorm.reader.Reader). The source of this dataset can be in either Petastorm format or raw Parquet format. To read from a dataset in Petastorm format we create the reader using the make_reader API. To read from a dataset in Parquet format we create the reader using the make_batch_reader API. There are a few delicate differences between the two readers described in the table here. Note that a TensorFlow tf.data.Dataset created from Petastorm format returns sequences of single data samples whereas a TensorFlow tf.data.Dataset created from raw Parquet format returns batches of data samples the size of which is determined by the Parquet row group size."
},
{
"code": null,
"e": 31928,
"s": 31755,
"text": "In the code block below we demonstrate the use of the make_petastorm_dataset API for creating a TensorFlow tf.data.Dataset from the Cifar10 data stored in Petastorm format."
},
{
"code": null,
"e": 32138,
"s": 31928,
"text": "from petastorm import make_readerfrom petastorm.tf_utils import make_petastorm_datasetdef get_dataset(): with make_reader('<path to data>') as reader: ds = make_petastorm_dataset(reader) return ds"
},
{
"code": null,
"e": 32309,
"s": 32138,
"text": "In the code block below we demonstrate the use of the make_petastorm_dataset API for creating a TensorFlow tf.data.Dataset from the Cifar10 data stored in Parquet format."
},
{
"code": null,
"e": 32821,
"s": 32309,
"text": "from petastorm import make_batch_readerfrom petastorm.tf_utils import make_petastorm_datasetdef get_dataset(): autotune = tf.data.experimental.AUTOTUNE with make_batch_reader('<path to data>') as reader: ds = make_petastorm_dataset(reader) ds = ds.unbatch() def parse(example): image, label = example image = tf.io.decode_raw(image, tf.uint8) image = tf.reshape(image, [32, 32, 3]) return image, label ds = ds.map(parse,num_parallel_calls=autotune) return ds"
},
{
"code": null,
"e": 32893,
"s": 32821,
"text": "Note how we use the unbatch routine so as to return individual samples."
},
{
"code": null,
"e": 33478,
"s": 32893,
"text": "In this section we share the results of several experiments. All experiments were run on a c5.2xlarge Amazon EC2 instance type (which has 8 vCPUs) with TensorFlow version 2.4.1, TensorFlow I/O version 0.17.1, and petastorm version 0.11.0. The experiments were divided into two parts. First we experimented with different methods of feeding the Cifar10 data stored in the file formats we have discussed into a TensorFlow session. We created multiple copies of the data in order to artificially inflate the dataset. For these experiments we chose to set the training batch size to 1024."
},
{
"code": null,
"e": 33747,
"s": 33478,
"text": "In order to assess how the size of the sample records impacted the relative performance, we ran a second set of tests in which we added a random byte array, 2 MB in size, to each Cifar10 data sample. For these experiments we chose to set the training batch size to 16."
},
{
"code": null,
"e": 33835,
"s": 33747,
"text": "For all experiments the datasets were divided into underlying files of size 100–200 MB."
},
{
"code": null,
"e": 34040,
"s": 33835,
"text": "Since we were interested in measuring only the training data throughput, we chose to forgo building a training model and instead iterated directly on the TensorFlow dataset as in the following code block."
},
{
"code": null,
"e": 34341,
"s": 34040,
"text": "import timeds = get_dataset().batch(batch_size)round = 0start_time = time.time()for x in ds: round = round + 1 if round % 100 == 0: print(\"round {}: epoch time: {}\". format(round, time.time() - start_time)) start_time = time.time() if round == 2000: break"
},
{
"code": null,
"e": 34452,
"s": 34341,
"text": "Note that in the case of petastorm the dataset traversal must be moved to within the petastorm reader context."
},
{
"code": null,
"e": 34732,
"s": 34452,
"text": "Our intention in sharing these results is to give you an idea of what your starting point might be and the amount of optimization effort that might be required. We strongly advise against drawing any conclusions from these results regarding your own use case for several reasons:"
},
{
"code": null,
"e": 35795,
"s": 34732,
"text": "The performance of the solutions is likely to vary greatly based on the model, the dataset, and the training environment.For a given use case, the performance of each solution will vary based on the specifics of how both the format and the TensorFlow dataset are configured, including: the size of each file, the size of the row groups, the use of compression schemes, the number of worker processes, the size of each sample batch, and more.The experiments measure the maximum throughput of the solutions by iterating directly over the TensorFlow datasets. In practice, the throughput needs to be high enough to keep the training session busy. In other words, as long as we are not bottlenecked on IO, we might be perfectly content with a throughput that is lower than the maximum.By the time you read this post the versions of the libraries I have used might be outdated. Newer versions of the libraries might include changes that impact their performance.Last but not least is the likelihood of bugs in my experiments. When you find them please drop me a line."
},
{
"code": null,
"e": 35917,
"s": 35795,
"text": "The performance of the solutions is likely to vary greatly based on the model, the dataset, and the training environment."
},
{
"code": null,
"e": 36238,
"s": 35917,
"text": "For a given use case, the performance of each solution will vary based on the specifics of how both the format and the TensorFlow dataset are configured, including: the size of each file, the size of the row groups, the use of compression schemes, the number of worker processes, the size of each sample batch, and more."
},
{
"code": null,
"e": 36579,
"s": 36238,
"text": "The experiments measure the maximum throughput of the solutions by iterating directly over the TensorFlow datasets. In practice, the throughput needs to be high enough to keep the training session busy. In other words, as long as we are not bottlenecked on IO, we might be perfectly content with a throughput that is lower than the maximum."
},
{
"code": null,
"e": 36756,
"s": 36579,
"text": "By the time you read this post the versions of the libraries I have used might be outdated. Newer versions of the libraries might include changes that impact their performance."
},
{
"code": null,
"e": 36862,
"s": 36756,
"text": "Last but not least is the likelihood of bugs in my experiments. When you find them please drop me a line."
},
{
"code": null,
"e": 37697,
"s": 36862,
"text": "The results demonstrate the strength of the TFRecord format and TFRecordDataset. In particular, we can see their stability despite variations in the environment settings. At the same time, some of the other experiments resulted in training throughputs that do not pale in comparison. While we find the results to be encouraging, it is important to note the instability of the alternative solutions across the two cases we tested. Solutions that perform well (compared to the TFRecord format) in one scenario appear to break down in the other. It would seem that, in contrast with the use of the TFRecord format, adapting the other formats for use in varying training settings might require some extra effort. Given the advantages of the alternative formats that we have discussed in this post, this effort may be well worth its while."
},
{
"code": null,
"e": 38555,
"s": 37697,
"text": "An additional metric of interest is the CPU utilization associated with each of the options. In a recent blog post we discussed the possibility of bottlenecks in the training pipeline that are caused by reaching maximum utilization of one or more of the CPUs. In cases where this possibility is a concern, it would be wise to assess how different decisions related to the data storage affect the CPU utilization of loading and parsing the data. These include the choice of file format, data compression (and decompression), TensorFlow dataset creation method, and more. In the chart below we list the average CPU utilization for the three most performant solutions of the Cifar10 experiments. The CPU utilization was captured from the Amazon EC2 Instance Metrics in Amazon CloudWatch. Since the instance we used has 8 vCPUs, the maximum utilization is 800%."
}
] |
How to Design Transparent Login Form in Android Studio Using Java? - GeeksforGeeks
|
09 Sep, 2021
We will be designing a simple application in which we make a transparent login screen in our MainActivity that takes the Username and Password from the user. A sample image is given below to get an idea about what we are going to do in this article.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Download any background image that you want to use in your application and add it to the drawable section which is a subpart of the resource folder.
fig = image file in drawable
Step 3: Make custom buttons that you need in the application by following steps. Right-click on project name file(transparent login form in this case) -> New -> Android Resource File.
circle.xml file:
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <corners android:radius="100dp" /> <stroke android:width="2dp" android:color="#ffffff" /> <size android:width="80dp" android:height="80dp" /> </shape>
custombutton.xml file:
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#3fff" /> <corners android:radius="50dp" /></shape>
custombutton2.xml file:
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#03A679" /> <corners android:radius="50dp" /></shape>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/wallpaper" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#3fff" android:gravity="center" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Moon light" android:background="@drawable/circle" android:gravity="center" android:textColor="#ffffff"/> <EditText android:layout_marginTop="15dp" android:gravity="center" android:layout_width="250dp" android:layout_height="40dp" android:hint="Username" android:textColorHint="#FFFBF6" android:background="@drawable/custombutton" /> <EditText android:layout_marginTop="15dp" android:gravity="center" android:layout_width="250dp" android:layout_height="40dp" android:hint="Password" android:textColorHint="#FFFBF6" android:background="@drawable/custombutton"/> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Keep me Signed in " android:textColor="#FFFBF6" android:hint="#FFFBF6" android:layout_marginTop="15dp" android:buttonTint="#FFFBF6" /> <Button android:layout_width="250dp" android:layout_height="40dp" android:text="Signin" android:textAllCaps="false" android:layout_marginTop="10dp" android:background="@drawable/custombutton2" android:textColor="#FFFBF6"/> <View android:layout_width="fill_parent" android:layout_height="2dp" android:background="#3fff" android:layout_marginTop="15dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Forget Password" android:textSize="18dp" android:layout_marginTop="15dp" android:textColor="#FFFBF6" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
Output:
FIG = Transparent login page
Project Link: Click Here
sagartomar9927
Android-Studio
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 25366,
"s": 25116,
"text": "We will be designing a simple application in which we make a transparent login screen in our MainActivity that takes the Username and Password from the user. A sample image is given below to get an idea about what we are going to do in this article."
},
{
"code": null,
"e": 25395,
"s": 25366,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25507,
"s": 25395,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. "
},
{
"code": null,
"e": 25664,
"s": 25507,
"text": "Step 2: Download any background image that you want to use in your application and add it to the drawable section which is a subpart of the resource folder."
},
{
"code": null,
"e": 25694,
"s": 25664,
"text": "fig = image file in drawable "
},
{
"code": null,
"e": 25878,
"s": 25694,
"text": "Step 3: Make custom buttons that you need in the application by following steps. Right-click on project name file(transparent login form in this case) -> New -> Android Resource File."
},
{
"code": null,
"e": 25896,
"s": 25878,
"text": "circle.xml file: "
},
{
"code": null,
"e": 25900,
"s": 25896,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"oval\"> <corners android:radius=\"100dp\" /> <stroke android:width=\"2dp\" android:color=\"#ffffff\" /> <size android:width=\"80dp\" android:height=\"80dp\" /> </shape>",
"e": 26218,
"s": 25900,
"text": null
},
{
"code": null,
"e": 26244,
"s": 26221,
"text": "custombutton.xml file:"
},
{
"code": null,
"e": 26250,
"s": 26246,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\"> <solid android:color=\"#3fff\" /> <corners android:radius=\"50dp\" /></shape>",
"e": 26435,
"s": 26250,
"text": null
},
{
"code": null,
"e": 26463,
"s": 26438,
"text": "custombutton2.xml file: "
},
{
"code": null,
"e": 26469,
"s": 26465,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\"> <solid android:color=\"#03A679\" /> <corners android:radius=\"50dp\" /></shape>",
"e": 26656,
"s": 26469,
"text": null
},
{
"code": null,
"e": 26707,
"s": 26659,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26852,
"s": 26709,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 26858,
"s": 26854,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@drawable/wallpaper\" tools:context=\".MainActivity\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:background=\"#3fff\" android:gravity=\"center\" android:padding=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Moon light\" android:background=\"@drawable/circle\" android:gravity=\"center\" android:textColor=\"#ffffff\"/> <EditText android:layout_marginTop=\"15dp\" android:gravity=\"center\" android:layout_width=\"250dp\" android:layout_height=\"40dp\" android:hint=\"Username\" android:textColorHint=\"#FFFBF6\" android:background=\"@drawable/custombutton\" /> <EditText android:layout_marginTop=\"15dp\" android:gravity=\"center\" android:layout_width=\"250dp\" android:layout_height=\"40dp\" android:hint=\"Password\" android:textColorHint=\"#FFFBF6\" android:background=\"@drawable/custombutton\"/> <CheckBox android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Keep me Signed in \" android:textColor=\"#FFFBF6\" android:hint=\"#FFFBF6\" android:layout_marginTop=\"15dp\" android:buttonTint=\"#FFFBF6\" /> <Button android:layout_width=\"250dp\" android:layout_height=\"40dp\" android:text=\"Signin\" android:textAllCaps=\"false\" android:layout_marginTop=\"10dp\" android:background=\"@drawable/custombutton2\" android:textColor=\"#FFFBF6\"/> <View android:layout_width=\"fill_parent\" android:layout_height=\"2dp\" android:background=\"#3fff\" android:layout_marginTop=\"15dp\"/> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Forget Password\" android:textSize=\"18dp\" android:layout_marginTop=\"15dp\" android:textColor=\"#FFFBF6\" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 29575,
"s": 26858,
"text": null
},
{
"code": null,
"e": 29586,
"s": 29578,
"text": "Output:"
},
{
"code": null,
"e": 29618,
"s": 29588,
"text": "FIG = Transparent login page "
},
{
"code": null,
"e": 29645,
"s": 29620,
"text": "Project Link: Click Here"
},
{
"code": null,
"e": 29662,
"s": 29647,
"text": "sagartomar9927"
},
{
"code": null,
"e": 29677,
"s": 29662,
"text": "Android-Studio"
},
{
"code": null,
"e": 29685,
"s": 29677,
"text": "Android"
},
{
"code": null,
"e": 29690,
"s": 29685,
"text": "Java"
},
{
"code": null,
"e": 29695,
"s": 29690,
"text": "Java"
},
{
"code": null,
"e": 29703,
"s": 29695,
"text": "Android"
},
{
"code": null,
"e": 29801,
"s": 29703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29840,
"s": 29801,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29890,
"s": 29840,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29932,
"s": 29890,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29970,
"s": 29932,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 30043,
"s": 29970,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 30058,
"s": 30043,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30102,
"s": 30058,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 30124,
"s": 30102,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 30160,
"s": 30124,
"text": "Arrays.sort() in Java with examples"
}
] |
How to swap two arrays without using temporary variable in C language?
|
Swap two arrays without using Temp variable. Here, we are going to use Arithmetic Operators and Bitwise Operators instead of third variable.
The logic to read the first array is as follows −
printf("enter first array ele:\n");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
}
The logic to read the second array is as follows −
printf("enter first array ele:\n");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
}
The logic to swap the two arrays without using a third variable is as follows −
for(i = 0; i < size; i++){
first[i] = first[i] + sec[i];
sec[i] = first[i] - sec[i];
first[i] = first[i] - sec[i];
}
Following is the C program to swap two arrays without using the Temp variable −
Live Demo
#include<stdio.h>
int main(){
int size, i, first[20], sec[20];
printf("enter the size of array:");
scanf("%d", &size);
printf("enter first array ele:\n");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
}
printf("enter second array ele:\n");
for(i = 0; i < size; i ++){
scanf("%d", &sec[i]);
}
//Swapping two Arrays
for(i = 0; i < size; i++){
first[i] = first[i] + sec[i];
sec[i] = first[i] - sec[i];
first[i] = first[i] - sec[i];
}
printf("\n first array after swapping %d elements\n", size);
for(i = 0; i < size; i ++){
printf(" %d \t ",first[i]);
}
printf("sec array after Swapping %d elements\n", size);
for(i = 0; i < size; i ++){
printf(" %d \t ",sec[i]);
}
return 0;
}
When the above program is executed, it produces the following result −
enter the size of array:5
enter first array ele:
11 12 13 14 15
enter second array ele:
90 80 70 60 50
first array after swapping 5 elements
90 80 70 60 50
sec array after Swapping 5 elements
11 12 13 14 15
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "Swap two arrays without using Temp variable. Here, we are going to use Arithmetic Operators and Bitwise Operators instead of third variable."
},
{
"code": null,
"e": 1253,
"s": 1203,
"text": "The logic to read the first array is as follows −"
},
{
"code": null,
"e": 1345,
"s": 1253,
"text": "printf(\"enter first array ele:\\n\");\nfor(i = 0; i < size; i++){\n scanf(\"%d\", &first[i]);\n}"
},
{
"code": null,
"e": 1396,
"s": 1345,
"text": "The logic to read the second array is as follows −"
},
{
"code": null,
"e": 1488,
"s": 1396,
"text": "printf(\"enter first array ele:\\n\");\nfor(i = 0; i < size; i++){\n scanf(\"%d\", &first[i]);\n}"
},
{
"code": null,
"e": 1568,
"s": 1488,
"text": "The logic to swap the two arrays without using a third variable is as follows −"
},
{
"code": null,
"e": 1694,
"s": 1568,
"text": "for(i = 0; i < size; i++){\n first[i] = first[i] + sec[i];\n sec[i] = first[i] - sec[i];\n first[i] = first[i] - sec[i];\n}"
},
{
"code": null,
"e": 1774,
"s": 1694,
"text": "Following is the C program to swap two arrays without using the Temp variable −"
},
{
"code": null,
"e": 1785,
"s": 1774,
"text": " Live Demo"
},
{
"code": null,
"e": 2563,
"s": 1785,
"text": "#include<stdio.h>\nint main(){\n int size, i, first[20], sec[20];\n printf(\"enter the size of array:\");\n scanf(\"%d\", &size);\n printf(\"enter first array ele:\\n\");\n for(i = 0; i < size; i++){\n scanf(\"%d\", &first[i]);\n }\n printf(\"enter second array ele:\\n\");\n for(i = 0; i < size; i ++){\n scanf(\"%d\", &sec[i]);\n }\n //Swapping two Arrays\n for(i = 0; i < size; i++){\n first[i] = first[i] + sec[i];\n sec[i] = first[i] - sec[i];\n first[i] = first[i] - sec[i];\n }\n printf(\"\\n first array after swapping %d elements\\n\", size);\n for(i = 0; i < size; i ++){\n printf(\" %d \\t \",first[i]);\n }\n printf(\"sec array after Swapping %d elements\\n\", size);\n for(i = 0; i < size; i ++){\n printf(\" %d \\t \",sec[i]);\n }\n return 0;\n}"
},
{
"code": null,
"e": 2634,
"s": 2563,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2841,
"s": 2634,
"text": "enter the size of array:5\nenter first array ele:\n11 12 13 14 15\nenter second array ele:\n90 80 70 60 50\nfirst array after swapping 5 elements\n90 80 70 60 50\nsec array after Swapping 5 elements\n11 12 13 14 15"
}
] |
Smallest divisible number | Practice | GeeksforGeeks
|
Given a number N, find an integer denoting the smallest number evenly divisible by each number from 1 to n.
Example 1:
Input:
N = 3
Output: 6
Explanation: 6 is the smallest number
divisible by 1,2,3.
Example 2:
Input:
N = 6
Output: 60
Explanation: 60 is the smallest number
divisible by 1,2,3,4,5,6.
Your Task:
You dont need to read input or print anything. Complete the function getSmallestDivNum() which takes N as input parameter and returns the smallest number evenly divisible by each number from 1 to n.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 25
0
Kartik Khanna8 months ago
Kartik Khanna
long long gcd(long long a,long long b){ return(b==0)?a:gcd(b,a%b); } long long getSmallestDivNum(long long n){ long long res=1; for(long long i=2;i<=n;i++){ res=(res*i)/gcd(res,i); } return res; }
0
sneha sinha8 months ago
sneha sinha
import mathclass Solution: def getSmallestDivNum(self, n): # code here a=1 for i in range(2,n+1): a=(a*i)//math.gcd(a,i) return a
0
Ashu10 months ago
Ashu
Easy c++ Solution|| C++
0
101_Sumit Patil10 months ago
101_Sumit Patil
CPP SolutionExecution Time : 0.01 seclong long gcd(long long int a, long long int b){ if (b == 0) return a; return gcd(b, a % b);} long long getSmallestDivNum(long long n) { long res=1; for(long i =2; i<=n; i++) { res = (res*i)/gcd(res,i); } return res; }
0
3lit3coder10 months ago
3lit3coder
0
Vishal Kumar Mahto11 months ago
Vishal Kumar Mahto
Simple solution in javaclass Solution{public static long getSmallestDivNum(int n){
long s=1;
for(long i =2;i<=n;i++) { s = lcm(s,i); }
return s ; }
public static long gcd(long a,long b){ if(b==0) return a ; else return gcd(b,a%b);}
public static long lcm(long a,long b){ return (a*b)/gcd(a,b);}}
-2
Akansha11 months ago
Akansha
If you observe carefully the ans must be the LCM of the numbers 1 to n. To find LCM of numbers from 1 to n
0
Amar Prakash1 year ago
Amar Prakash
long long gcdfun (long long A, long long B) { if( A < B) { swap(A, B); }
if( A % B == 0) { return B; } else { return gcdfun(B, A % B); } }
long long getSmallestDivNum(long long n){
long long x = 1; for(long long i=2; i<=n; i++) { x = (x*i) /gcdfun(x,i); }
return x; // code here }
0
Kumar Tejaswi1 year ago
Kumar Tejaswi
//define the gcd function first and than...
long long getSmallestDivNum(long long N){ // code here long long x=1; for (long long i=1;i<=N;i++) { x=(((i*x))/gcd(i,x)); }return x; }
0
Annanya Mathur1 year ago
Annanya Mathur
long long getSmallestDivNum(long long n){
long long int a=1,i; for( i=2;i<=n;i++) { a=(i*a)/__gcd(a,i);
} return a; }
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": 346,
"s": 238,
"text": "Given a number N, find an integer denoting the smallest number evenly divisible by each number from 1 to n."
},
{
"code": null,
"e": 358,
"s": 346,
"text": "\nExample 1:"
},
{
"code": null,
"e": 440,
"s": 358,
"text": "Input:\nN = 3\nOutput: 6\nExplanation: 6 is the smallest number \ndivisible by 1,2,3."
},
{
"code": null,
"e": 452,
"s": 440,
"text": "\nExample 2:"
},
{
"code": null,
"e": 542,
"s": 452,
"text": "Input:\nN = 6\nOutput: 60\nExplanation: 60 is the smallest number \ndivisible by 1,2,3,4,5,6."
},
{
"code": null,
"e": 755,
"s": 542,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function getSmallestDivNum() which takes N as input parameter and returns the smallest number evenly divisible by each number from 1 to n."
},
{
"code": null,
"e": 818,
"s": 755,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 843,
"s": 818,
"text": "\nConstraints:\n1 ≤ N ≤ 25"
},
{
"code": null,
"e": 845,
"s": 843,
"text": "0"
},
{
"code": null,
"e": 871,
"s": 845,
"text": "Kartik Khanna8 months ago"
},
{
"code": null,
"e": 885,
"s": 871,
"text": "Kartik Khanna"
},
{
"code": null,
"e": 1126,
"s": 885,
"text": "long long gcd(long long a,long long b){ return(b==0)?a:gcd(b,a%b); } long long getSmallestDivNum(long long n){ long long res=1; for(long long i=2;i<=n;i++){ res=(res*i)/gcd(res,i); } return res; }"
},
{
"code": null,
"e": 1128,
"s": 1126,
"text": "0"
},
{
"code": null,
"e": 1152,
"s": 1128,
"text": "sneha sinha8 months ago"
},
{
"code": null,
"e": 1164,
"s": 1152,
"text": "sneha sinha"
},
{
"code": null,
"e": 1338,
"s": 1164,
"text": "import mathclass Solution: def getSmallestDivNum(self, n): # code here a=1 for i in range(2,n+1): a=(a*i)//math.gcd(a,i) return a"
},
{
"code": null,
"e": 1340,
"s": 1338,
"text": "0"
},
{
"code": null,
"e": 1358,
"s": 1340,
"text": "Ashu10 months ago"
},
{
"code": null,
"e": 1363,
"s": 1358,
"text": "Ashu"
},
{
"code": null,
"e": 1387,
"s": 1363,
"text": "Easy c++ Solution|| C++"
},
{
"code": null,
"e": 1389,
"s": 1387,
"text": "0"
},
{
"code": null,
"e": 1418,
"s": 1389,
"text": "101_Sumit Patil10 months ago"
},
{
"code": null,
"e": 1434,
"s": 1418,
"text": "101_Sumit Patil"
},
{
"code": null,
"e": 1751,
"s": 1434,
"text": "CPP SolutionExecution Time : 0.01 seclong long gcd(long long int a, long long int b){ if (b == 0) return a; return gcd(b, a % b);} long long getSmallestDivNum(long long n) { long res=1; for(long i =2; i<=n; i++) { res = (res*i)/gcd(res,i); } return res; }"
},
{
"code": null,
"e": 1753,
"s": 1751,
"text": "0"
},
{
"code": null,
"e": 1777,
"s": 1753,
"text": "3lit3coder10 months ago"
},
{
"code": null,
"e": 1788,
"s": 1777,
"text": "3lit3coder"
},
{
"code": null,
"e": 1790,
"s": 1788,
"text": "0"
},
{
"code": null,
"e": 1822,
"s": 1790,
"text": "Vishal Kumar Mahto11 months ago"
},
{
"code": null,
"e": 1841,
"s": 1822,
"text": "Vishal Kumar Mahto"
},
{
"code": null,
"e": 1924,
"s": 1841,
"text": "Simple solution in javaclass Solution{public static long getSmallestDivNum(int n){"
},
{
"code": null,
"e": 1938,
"s": 1924,
"text": " long s=1;"
},
{
"code": null,
"e": 1997,
"s": 1938,
"text": " for(long i =2;i<=n;i++) { s = lcm(s,i); }"
},
{
"code": null,
"e": 2018,
"s": 1997,
"text": " return s ; }"
},
{
"code": null,
"e": 2114,
"s": 2018,
"text": "public static long gcd(long a,long b){ if(b==0) return a ; else return gcd(b,a%b);}"
},
{
"code": null,
"e": 2181,
"s": 2114,
"text": "public static long lcm(long a,long b){ return (a*b)/gcd(a,b);}}"
},
{
"code": null,
"e": 2184,
"s": 2181,
"text": "-2"
},
{
"code": null,
"e": 2205,
"s": 2184,
"text": "Akansha11 months ago"
},
{
"code": null,
"e": 2213,
"s": 2205,
"text": "Akansha"
},
{
"code": null,
"e": 2320,
"s": 2213,
"text": "If you observe carefully the ans must be the LCM of the numbers 1 to n. To find LCM of numbers from 1 to n"
},
{
"code": null,
"e": 2322,
"s": 2320,
"text": "0"
},
{
"code": null,
"e": 2345,
"s": 2322,
"text": "Amar Prakash1 year ago"
},
{
"code": null,
"e": 2358,
"s": 2345,
"text": "Amar Prakash"
},
{
"code": null,
"e": 2496,
"s": 2358,
"text": "long long gcdfun (long long A, long long B) { if( A < B) { swap(A, B); }"
},
{
"code": null,
"e": 2684,
"s": 2496,
"text": " if( A % B == 0) { return B; } else { return gcdfun(B, A % B); } }"
},
{
"code": null,
"e": 2730,
"s": 2684,
"text": " long long getSmallestDivNum(long long n){"
},
{
"code": null,
"e": 2845,
"s": 2730,
"text": " long long x = 1; for(long long i=2; i<=n; i++) { x = (x*i) /gcdfun(x,i); }"
},
{
"code": null,
"e": 2888,
"s": 2845,
"text": " return x; // code here }"
},
{
"code": null,
"e": 2890,
"s": 2888,
"text": "0"
},
{
"code": null,
"e": 2914,
"s": 2890,
"text": "Kumar Tejaswi1 year ago"
},
{
"code": null,
"e": 2928,
"s": 2914,
"text": "Kumar Tejaswi"
},
{
"code": null,
"e": 2972,
"s": 2928,
"text": "//define the gcd function first and than..."
},
{
"code": null,
"e": 3157,
"s": 2972,
"text": "long long getSmallestDivNum(long long N){ // code here long long x=1; for (long long i=1;i<=N;i++) { x=(((i*x))/gcd(i,x)); }return x; }"
},
{
"code": null,
"e": 3159,
"s": 3157,
"text": "0"
},
{
"code": null,
"e": 3184,
"s": 3159,
"text": "Annanya Mathur1 year ago"
},
{
"code": null,
"e": 3199,
"s": 3184,
"text": "Annanya Mathur"
},
{
"code": null,
"e": 3241,
"s": 3199,
"text": "long long getSmallestDivNum(long long n){"
},
{
"code": null,
"e": 3335,
"s": 3241,
"text": " long long int a=1,i; for( i=2;i<=n;i++) { a=(i*a)/__gcd(a,i);"
},
{
"code": null,
"e": 3369,
"s": 3335,
"text": " } return a; }"
},
{
"code": null,
"e": 3515,
"s": 3369,
"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": 3551,
"s": 3515,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3561,
"s": 3551,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3571,
"s": 3561,
"text": "\nContest\n"
},
{
"code": null,
"e": 3634,
"s": 3571,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3782,
"s": 3634,
"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": 3990,
"s": 3782,
"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": 4096,
"s": 3990,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Golang Program to Print the Sum of all the Positive Numbers and Negative Numbers in a List
|
Read a number of elements to be in a list.
Take the elements from the user using a for loop and append to a list.
Using a for loop, get the elements one by one from the list and check if it is positive or negative.
If it is positive, check if it is odd or even and find the individual sum.
Find the individual sum of negative numbers.
Print all the sums.
Live Demo
package main
import "fmt"
func main() {
fmt.Printf("Enter the number of elements to be in the list:")
var size int
fmt.Scanln(&size)
var arr = make([]int, size)
for i:=0; i<size; i++ {
fmt.Printf("Enter %d element: ", i)
fmt.Scanf("%d", &arr[i])
}
sum1:=0
sum2:=0
sum3:=0
for i:=0; i<size; i++{
fmt.Println(i)
if arr[i] > 0{
if arr[i]%2==0 {
sum1=sum1+arr[i]
}else{
sum2=sum2+arr[i]
}
} else {
sum3=sum3+arr[i]
}
}
fmt.Println("Sum of all positive even numbers:", sum1)
fmt.Println("Sum of all positive odd numbers:", sum2)
fmt.Println("Sum of all negative numbers:", sum3)
}
Enter the number of elements to be in the list:4
Enter 0th element: -12
Enter 1 element: 34
Enter 2 element: 35
Enter 3 element: 89
0
1
2
3
Sum of all positive even numbers: 34
Sum of all positive odd numbers: 124
Sum of all negative numbers: -12
|
[
{
"code": null,
"e": 1105,
"s": 1062,
"text": "Read a number of elements to be in a list."
},
{
"code": null,
"e": 1176,
"s": 1105,
"text": "Take the elements from the user using a for loop and append to a list."
},
{
"code": null,
"e": 1277,
"s": 1176,
"text": "Using a for loop, get the elements one by one from the list and check if it is positive or negative."
},
{
"code": null,
"e": 1352,
"s": 1277,
"text": "If it is positive, check if it is odd or even and find the individual sum."
},
{
"code": null,
"e": 1397,
"s": 1352,
"text": "Find the individual sum of negative numbers."
},
{
"code": null,
"e": 1417,
"s": 1397,
"text": "Print all the sums."
},
{
"code": null,
"e": 1428,
"s": 1417,
"text": " Live Demo"
},
{
"code": null,
"e": 2142,
"s": 1428,
"text": "package main\nimport \"fmt\"\nfunc main() {\n fmt.Printf(\"Enter the number of elements to be in the list:\")\n var size int\n fmt.Scanln(&size)\n var arr = make([]int, size)\n for i:=0; i<size; i++ {\n fmt.Printf(\"Enter %d element: \", i)\n fmt.Scanf(\"%d\", &arr[i])\n }\n sum1:=0\n sum2:=0\n sum3:=0\n for i:=0; i<size; i++{\n fmt.Println(i)\n if arr[i] > 0{\n if arr[i]%2==0 {\n sum1=sum1+arr[i]\n }else{\n sum2=sum2+arr[i]\n }\n } else {\n sum3=sum3+arr[i]\n }\n }\n fmt.Println(\"Sum of all positive even numbers:\", sum1)\n fmt.Println(\"Sum of all positive odd numbers:\", sum2)\n fmt.Println(\"Sum of all negative numbers:\", sum3)\n}"
},
{
"code": null,
"e": 2389,
"s": 2142,
"text": "Enter the number of elements to be in the list:4\nEnter 0th element: -12\nEnter 1 element: 34\nEnter 2 element: 35\nEnter 3 element: 89\n0\n1\n2\n3\nSum of all positive even numbers: 34\nSum of all positive odd numbers: 124\nSum of all negative numbers: -12"
}
] |
Post Order Traversal of Binary Tree in O(N) using O(1) space - GeeksforGeeks
|
25 Oct, 2021
Prerequisites:- Morris Inorder Traversal, Tree Traversals (Inorder, Preorder and Postorder)Given a Binary Tree, the task is to print the elements in post order using O(N) time complexity and constant space.
Input: 1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
Output: 8 9 4 5 2 6 7 3 1
Input: 5
/ \
7 3
/ \ / \
4 11 13 9
/ \
8 4
Output: 8 4 4 11 7 13 9 3 5
Method 1: Using Morris Inorder Traversal
Create a dummy node and make the root as it’s left child.Initialize current with dummy node.While current is not NULL If the current does not have a left child traverse the right child, current = current->rightOtherwise, Find the rightmost child in the left subtree.If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->leftOtherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right
Create a dummy node and make the root as it’s left child.
Initialize current with dummy node.
While current is not NULL If the current does not have a left child traverse the right child, current = current->rightOtherwise, Find the rightmost child in the left subtree.If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->leftOtherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right
If the current does not have a left child traverse the right child, current = current->right
Otherwise, Find the rightmost child in the left subtree.If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->leftOtherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right
Find the rightmost child in the left subtree.If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->leftOtherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right
Find the rightmost child in the left subtree.
If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->left
Make current as the right child of the rightmost node.
Traverse the left child, current = current->left
Otherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right
Set the rightmost child’s right pointer to NULL.
From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.
Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.
Traverse the right child, current = current->right
Below is the diagram showing the rightmost child in the left subtree, pointing to its inorder successor.
Below is the diagram which highlights the path 1->2->5->9 and the way the nodes are processed and printed as per the above algorithm.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// Post Order traversal// of Binary Tree in O(N)// time and O(1) space#include <bits/stdc++.h>using namespace std; class node{ public: int data; node *left, *right;}; // Helper function that allocates a// new node with the given data and// NULL left and right pointers.node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Postorder traversal without recursion// and without stackvoid postOrderConstSpace(node* root){ if (root == NULL) return; node* current = newNode(-1); node* pre = NULL; node* prev = NULL; node* succ = NULL; node* temp = NULL; current->left = root; while (current) { // If left child is null. // Move to right child. if (current->left == NULL) { current = current->right; } else { pre = current->left; // Inorder predecessor while (pre->right && pre->right != current) pre = pre->right; // The connection between current and // predecessor is made if (pre->right == NULL) { // Make current as the right // child of the right most node pre->right = current; // Traverse the left child current = current->left; } else { pre->right = NULL; succ = current; current = current->left; prev = NULL; // Traverse along the right // subtree to the // right-most child while (current != NULL) { temp = current->right; current->right = prev; prev = current; current = temp; } // Traverse back // to current's left child // node while (prev != NULL) { cout << prev->data << " "; temp = prev->right; prev->right = current; current = prev; prev = temp; } current = succ; current = current->right; } } }} // Driver codeint main(){ /* Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 */ node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->right->left = newNode(8); root->left->right->right = newNode(9); postOrderConstSpace(root); return 0;} // This code is contributed by Saurav Chaudhary
// Java program to implement// Post Order traversal// of Binary Tree in O(N)// time and O(1) space // Definition of the// binary treeclass TreeNode { public int data; public TreeNode left; public TreeNode right; public TreeNode(int data) { this.data = data; } public String toString() { return data + " "; }} public class PostOrder { TreeNode root; // Function to find Post Order // Traversal Using Constant space void postOrderConstantspace(TreeNode root) { if (root == null) return; TreeNode current = new TreeNode(-1), pre = null; TreeNode prev = null, succ = null, temp = null; current.left = root; while (current != null) { // Go to the right child // if current does not // have a left child if (current.left == null) { current = current.right; } else { // Traverse left child pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { // Make current as the right // child of the right most node pre.right = current; // Traverse the left child current = current.left; } else { pre.right = null; succ = current; current = current.left; prev = null; // Traverse along the right // subtree to the // right-most child while (current != null) { temp = current.right; current.right = prev; prev = current; current = temp; } // Traverse back from // right most child to // current's left child node while (prev != null) { System.out.print(prev); temp = prev.right; prev.right = current; current = prev; prev = temp; } current = succ; current = current.right; } } } } // Driver Code public static void main(String[] args) { /* Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 */ PostOrder tree = new PostOrder(); tree.root = new TreeNode(1); tree.root.left = new TreeNode(2); tree.root.right = new TreeNode(3); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(5); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(7); tree.root.left.right.left = new TreeNode(8); tree.root.left.right.right = new TreeNode(9); tree.postOrderConstantspace( tree.root); }}
# Python3 program to implement# Post Order traversal# of Binary Tree in O(N)# time and O(1) spaceclass node: def __init__(self, data): self.data = data self.left = None self.right = None # Helper function that allocates a# new node with the given data and# None left and right pointers.def newNode(data): temp = node(data) return temp # Postorder traversal without recursion# and without stackdef postOrderConstSpace(root): if (root == None): return current = newNode(-1) pre = None prev = None succ = None temp = None current.left = root while (current): # If left child is None. # Move to right child. if (current.left == None): current = current.right else: pre = current.left # Inorder predecessor while (pre.right and pre.right != current): pre = pre.right # The connection between current # and predecessor is made if (pre.right == None): # Make current as the right # child of the right most node pre.right = current # Traverse the left child current = current.left else: pre.right = None succ = current current = current.left prev = None # Traverse along the right # subtree to the # right-most child while (current != None): temp = current.right current.right = prev prev = current current = temp # Traverse back # to current's left child # node while (prev != None): print(prev.data, end = ' ') temp = prev.right prev.right = current current = prev prev = temp current = succ current = current.right # Driver codeif __name__=='__main__': ''' Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 ''' root = None root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.right.left = newNode(8) root.left.right.right = newNode(9) postOrderConstSpace(root) # This code is contributed by pratham76
// C# program to implement// Post Order traversal// of Binary Tree in O(N)// time and O(1) spaceusing System; // Definition of the// binary treepublic class TreeNode{ public int data; public TreeNode left, right; public TreeNode(int item) { data = item; left = right = null; }} class PostOrder{ public TreeNode root; // Function to find Post Order// Traversal Using Constant spacevoid postOrderConstantspace(TreeNode root){ if (root == null) return; TreeNode current = new TreeNode(-1), pre = null; TreeNode prev = null, succ = null, temp = null; current.left = root; while (current != null) { // Go to the right child // if current does not // have a left child if (current.left == null) { current = current.right; } else { // Traverse left child pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { // Make current as the right // child of the right most node pre.right = current; // Traverse the left child current = current.left; } else { pre.right = null; succ = current; current = current.left; prev = null; // Traverse along the right // subtree to the // right-most child while (current != null) { temp = current.right; current.right = prev; prev = current; current = temp; } // Traverse back from // right most child to // current's left child node while (prev != null) { Console.Write(prev.data + " "); temp = prev.right; prev.right = current; current = prev; prev = temp; } current = succ; current = current.right; } } }} // Driver codestatic public void Main (){ /* Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 */ PostOrder tree = new PostOrder(); tree.root = new TreeNode(1); tree.root.left = new TreeNode(2); tree.root.right = new TreeNode(3); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(5); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(7); tree.root.left.right.left = new TreeNode(8); tree.root.left.right.right = new TreeNode(9); tree.postOrderConstantspace(tree.root);}} // This code is contributed by offbeat
<script> // Javascript program to implement// Post Order traversal// of Binary Tree in O(N)// time and O(1) space // Definition of the// binary treeclass TreeNode{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root; // Function to find Post Order// Traversal Using Constant spacefunction postOrderConstantspace(root){ if (root == null) return; var current = new TreeNode(-1), pre = null; var prev = null, succ = null, temp = null; current.left = root; while (current != null) { // Go to the right child // if current does not // have a left child if (current.left == null) { current = current.right; } else { // Traverse left child pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { // Make current as the right // child of the right most node pre.right = current; // Traverse the left child current = current.left; } else { pre.right = null; succ = current; current = current.left; prev = null; // Traverse along the right // subtree to the // right-most child while (current != null) { temp = current.right; current.right = prev; prev = current; current = temp; } // Traverse back from // right most child to // current's left child node while (prev != null) { document.write(prev.data + " "); temp = prev.right; prev.right = current; current = prev; prev = temp; } current = succ; current = current.right; } } }} // Driver code/* Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 */var tree = new TreeNode();tree.root = new TreeNode(1);tree.root.left = new TreeNode(2);tree.root.right = new TreeNode(3);tree.root.left.left = new TreeNode(4);tree.root.left.right = new TreeNode(5);tree.root.right.left = new TreeNode(6);tree.root.right.right = new TreeNode(7);tree.root.left.right.left = new TreeNode(8);tree.root.left.right.right = new TreeNode(9);postOrderConstantspace(tree.root); </script>
4 8 9 5 2 6 7 3 1
Time Complexity: O(N) Auxiliary Space: O(1)
Method 2: In method 1, we traverse a path, reverse references, print nodes as we restore the references by reversing them again. In method 2, instead of reversing paths and restoring the structure, we traverse to the parent node from the current node using the current node’s left subtree. This could be faster depending on the tree structure, for example in a right-skewed tree.
The following algorithm and diagrams provide the details of the approach.
Below is the conceptual diagram showing how the left and right child references are used to traverse back and forth.
Below is the diagram which highlights the path 1->2->5->9 and the way the nodes are processed and printed as per the above algorithm.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement the above approach#include <bits/stdc++.h>using namespace std; struct TreeNode { TreeNode* left; TreeNode* right; int data; TreeNode(int data) { this->data = data; this->left = nullptr; this->right = nullptr; }}; TreeNode* root; // Function to Calculate Post// Order Traversal Using// Constant Spacestatic void postOrderConstantspace(TreeNode* root){ if (root == nullptr) return; TreeNode* current = nullptr; TreeNode* prevNode = nullptr; TreeNode* pre = nullptr; TreeNode* ptr = nullptr; TreeNode* netChild = nullptr; TreeNode* prevPtr = nullptr; current = root; while (current != nullptr) { if (current->left == nullptr) { current->left = prevNode; // Set prevNode to current prevNode = current; current = current->right; } else { pre = current->left; // Find the right most child // in the left subtree while (pre->right != nullptr && pre->right != current) pre = pre->right; if (pre->right == nullptr) { pre->right = current; current = current->left; } else { // Set the right most // child's right pointer // to NULL pre->right = nullptr; cout << pre->data << " "; ptr = pre; netChild = pre; prevPtr = pre; while (ptr != nullptr) { if (ptr->right == netChild) { cout << ptr->data << " "; netChild = ptr; prevPtr->left = nullptr; } if (ptr == current->left) break; // Break the loop // all the left subtree // nodes of current // processed prevPtr = ptr; ptr = ptr->left; } prevNode = current; current = current->right; } } } cout << prevNode->data << " "; // Last path traversal // that includes the root. ptr = prevNode; netChild = prevNode; prevPtr = prevNode; while (ptr != nullptr) { if (ptr->right == netChild) { cout << ptr->data << " "; netChild = ptr; prevPtr->left = nullptr; } if (ptr == root) break; prevPtr = ptr; ptr = ptr->left; }} int main(){ /* Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 */ root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); root->right->left = new TreeNode(6); root->right->right = new TreeNode(7); root->left->right->left = new TreeNode(8); root->left->right->right = new TreeNode(9); postOrderConstantspace(root); return 0;} // This code is contributed by mukesh07.
// Java Program to implement// the above approachclass TreeNode { public int data; public TreeNode left; public TreeNode right; public TreeNode(int data) { this.data = data; } public String toString() { return data + " "; }} public class PostOrder { TreeNode root; // Function to Calculate Post // Order Traversal // Using Constant Space void postOrderConstantspace(TreeNode root) { if (root == null) return; TreeNode current = null; TreeNode prevNode = null; TreeNode pre = null; TreeNode ptr = null; TreeNode netChild = null; TreeNode prevPtr = null; current = root; while (current != null) { if (current.left == null) { current.left = prevNode; // Set prevNode to current prevNode = current; current = current.right; } else { pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { pre.right = current; current = current.left; } else { // Set the right most // child's right pointer // to NULL pre.right = null; System.out.print(pre); ptr = pre; netChild = pre; prevPtr = pre; while (ptr != null) { if (ptr.right == netChild) { System.out.print(ptr); netChild = ptr; prevPtr.left = null; } if (ptr == current.left) break; // Break the loop // all the left subtree // nodes of current // processed prevPtr = ptr; ptr = ptr.left; } prevNode = current; current = current.right; } } } System.out.print(prevNode); // Last path traversal // that includes the root. ptr = prevNode; netChild = prevNode; prevPtr = prevNode; while (ptr != null) { if (ptr.right == netChild) { System.out.print(ptr); netChild = ptr; prevPtr.left = null; } if (ptr == root) break; prevPtr = ptr; ptr = ptr.left; } } // Main Function public static void main(String[] args) { /* Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 */ PostOrder tree = new PostOrder(); tree.root = new TreeNode(1); tree.root.left = new TreeNode(2); tree.root.right = new TreeNode(3); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(5); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(7); tree.root.left.right.left = new TreeNode(8); tree.root.left.right.right = new TreeNode(9); tree.postOrderConstantspace( tree.root); }}
# Python3 Program to implement the above approachclass TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None # Function to Calculate Post# Order Traversal Using# Constant Spacedef postOrderConstantspace(root): if root == None: return current = None prevNode = None pre = None ptr = None netChild = None prevPtr = None current = root while current != None: if current.left == None: current.left = prevNode # Set prevNode to current prevNode = current current = current.right else: pre = current.left # Find the right most child # in the left subtree while pre.right != None and pre.right != current: pre = pre.right if pre.right == None: pre.right = current current = current.left else: # Set the right most # child's right pointer # to NULL pre.right = None print(pre.data, end = " ") ptr = pre netChild = pre prevPtr = pre while ptr != None: if ptr.right == netChild: print(ptr.data, end = " ") netChild = ptr prevPtr.left = None if ptr == current.left: break # Break the loop # all the left subtree # nodes of current # processed prevPtr = ptr ptr = ptr.left prevNode = current current = current.right print(prevNode.data, end = " ") # Last path traversal # that includes the root. ptr = prevNode netChild = prevNode prevPtr = prevNode while ptr != None: if ptr.right == netChild: print(ptr.data, end = " ") netChild = ptr prevPtr.left = None if (ptr == root): break prevPtr = ptr ptr = ptr.left """ Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9"""root = TreeNode(1)root.left = TreeNode(2)root.right = TreeNode(3)root.left.left = TreeNode(4)root.left.right = TreeNode(5)root.right.left = TreeNode(6)root.right.right = TreeNode(7)root.left.right.left = TreeNode(8)root.left.right.right = TreeNode(9)postOrderConstantspace(root) # This code is contributed by divyeshrabadiya07.
// C# Program to implement// the above approachusing System;class TreeNode{ public int data;public TreeNode left;public TreeNode right; public TreeNode(int data){ this.data = data;} public string toString(){ return data + " ";}} class PostOrder{ TreeNode root; // Function to Calculate Post// Order Traversal Using// Constant Spacevoid postOrderConstantspace(TreeNode root){ if (root == null) return; TreeNode current = null; TreeNode prevNode = null; TreeNode pre = null; TreeNode ptr = null; TreeNode netChild = null; TreeNode prevPtr = null; current = root; while (current != null) { if (current.left == null) { current.left = prevNode; // Set prevNode to current prevNode = current; current = current.right; } else { pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { pre.right = current; current = current.left; } else { // Set the right most // child's right pointer // to NULL pre.right = null; Console.Write(pre.data + " "); ptr = pre; netChild = pre; prevPtr = pre; while (ptr != null) { if (ptr.right == netChild) { Console.Write(ptr.data + " "); netChild = ptr; prevPtr.left = null; } if (ptr == current.left) break; // Break the loop // all the left subtree // nodes of current // processed prevPtr = ptr; ptr = ptr.left; } prevNode = current; current = current.right; } } } Console.Write(prevNode.data + " "); // Last path traversal // that includes the root. ptr = prevNode; netChild = prevNode; prevPtr = prevNode; while (ptr != null) { if (ptr.right == netChild) { Console.Write(ptr.data + " "); netChild = ptr; prevPtr.left = null; } if (ptr == root) break; prevPtr = ptr; ptr = ptr.left; }} // Driver codepublic static void Main(string[] args){ /* Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 */ PostOrder tree = new PostOrder(); tree.root = new TreeNode(1); tree.root.left = new TreeNode(2); tree.root.right = new TreeNode(3); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(5); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(7); tree.root.left.right.left = new TreeNode(8); tree.root.left.right.right = new TreeNode(9); tree.postOrderConstantspace(tree.root);}} // This code is contributed by Rutvik_56
<script> // Javascript Program to implement the above approach class TreeNode { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; // Function to Calculate Post // Order Traversal Using // Constant Space function postOrderConstantspace(root) { if (root == null) return; let current = null; let prevNode = null; let pre = null; let ptr = null; let netChild = null; let prevPtr = null; current = root; while (current != null) { if (current.left == null) { current.left = prevNode; // Set prevNode to current prevNode = current; current = current.right; } else { pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { pre.right = current; current = current.left; } else { // Set the right most // child's right pointer // to NULL pre.right = null; document.write(pre.data + " "); ptr = pre; netChild = pre; prevPtr = pre; while (ptr != null) { if (ptr.right == netChild) { document.write(ptr.data + " "); netChild = ptr; prevPtr.left = null; } if (ptr == current.left) break; // Break the loop // all the left subtree // nodes of current // processed prevPtr = ptr; ptr = ptr.left; } prevNode = current; current = current.right; } } } document.write(prevNode.data + " "); // Last path traversal // that includes the root. ptr = prevNode; netChild = prevNode; prevPtr = prevNode; while (ptr != null) { if (ptr.right == netChild) { document.write(ptr.data + " "); netChild = ptr; prevPtr.left = null; } if (ptr == root) break; prevPtr = ptr; ptr = ptr.left; } } /* Constructed tree is as follows:- 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 */ root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); root.left.right.left = new TreeNode(8); root.left.right.right = new TreeNode(9); postOrderConstantspace(root); // This code is contributed by divyesh072019.</script>
4 8 9 5 2 6 7 3 1
Time Complexity: O(N) Auxiliary Space: O(1)
sauravchaudhary717
offbeat
rutvik_56
pratham76
ankurgupta1999
geekygaurab
famously
divyesh072019
divyeshrabadiya07
mukesh07
Inorder Traversal
interview-preparation
morris-traversal
PostOrder Traversal
Data Structures
Recursion
Tree
Data Structures
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Start Learning DSA?
Introduction to Tree Data Structure
Program to implement Singly Linked List in C++ using class
Hash Functions and list/types of Hash functions
Insertion in a B+ tree
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
|
[
{
"code": null,
"e": 26299,
"s": 26271,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 26506,
"s": 26299,
"text": "Prerequisites:- Morris Inorder Traversal, Tree Traversals (Inorder, Preorder and Postorder)Given a Binary Tree, the task is to print the elements in post order using O(N) time complexity and constant space."
},
{
"code": null,
"e": 26733,
"s": 26506,
"text": "Input: 1 \n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\\n 8 9\nOutput: 8 9 4 5 2 6 7 3 1\n\nInput: 5 \n / \\\n 7 3\n / \\ / \\\n 4 11 13 9\n / \\\n 8 4\nOutput: 8 4 4 11 7 13 9 3 5"
},
{
"code": null,
"e": 26774,
"s": 26733,
"text": "Method 1: Using Morris Inorder Traversal"
},
{
"code": null,
"e": 27525,
"s": 26774,
"text": "Create a dummy node and make the root as it’s left child.Initialize current with dummy node.While current is not NULL If the current does not have a left child traverse the right child, current = current->rightOtherwise, Find the rightmost child in the left subtree.If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->leftOtherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right"
},
{
"code": null,
"e": 27583,
"s": 27525,
"text": "Create a dummy node and make the root as it’s left child."
},
{
"code": null,
"e": 27619,
"s": 27583,
"text": "Initialize current with dummy node."
},
{
"code": null,
"e": 28278,
"s": 27619,
"text": "While current is not NULL If the current does not have a left child traverse the right child, current = current->rightOtherwise, Find the rightmost child in the left subtree.If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->leftOtherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right"
},
{
"code": null,
"e": 28371,
"s": 28278,
"text": "If the current does not have a left child traverse the right child, current = current->right"
},
{
"code": null,
"e": 28912,
"s": 28371,
"text": "Otherwise, Find the rightmost child in the left subtree.If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->leftOtherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right"
},
{
"code": null,
"e": 29442,
"s": 28912,
"text": "Find the rightmost child in the left subtree.If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->leftOtherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right"
},
{
"code": null,
"e": 29488,
"s": 29442,
"text": "Find the rightmost child in the left subtree."
},
{
"code": null,
"e": 29631,
"s": 29488,
"text": "If rightmost child’s right child is NULLMake current as the right child of the rightmost node.Traverse the left child, current = current->left"
},
{
"code": null,
"e": 29686,
"s": 29631,
"text": "Make current as the right child of the rightmost node."
},
{
"code": null,
"e": 29735,
"s": 29686,
"text": "Traverse the left child, current = current->left"
},
{
"code": null,
"e": 30078,
"s": 29735,
"text": "Otherwise, Set the rightmost child’s right pointer to NULL.From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers.Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements.Traverse the right child, current = current->right"
},
{
"code": null,
"e": 30127,
"s": 30078,
"text": "Set the rightmost child’s right pointer to NULL."
},
{
"code": null,
"e": 30245,
"s": 30127,
"text": "From current’s left child, traverse along with the right children until the rightmost child and reverse the pointers."
},
{
"code": null,
"e": 30362,
"s": 30245,
"text": "Traverse back from rightmost child to current’s left child node by reversing the pointers and printing the elements."
},
{
"code": null,
"e": 30413,
"s": 30362,
"text": "Traverse the right child, current = current->right"
},
{
"code": null,
"e": 30519,
"s": 30413,
"text": "Below is the diagram showing the rightmost child in the left subtree, pointing to its inorder successor. "
},
{
"code": null,
"e": 30655,
"s": 30519,
"text": "Below is the diagram which highlights the path 1->2->5->9 and the way the nodes are processed and printed as per the above algorithm. "
},
{
"code": null,
"e": 30706,
"s": 30655,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30710,
"s": 30706,
"text": "C++"
},
{
"code": null,
"e": 30715,
"s": 30710,
"text": "Java"
},
{
"code": null,
"e": 30723,
"s": 30715,
"text": "Python3"
},
{
"code": null,
"e": 30726,
"s": 30723,
"text": "C#"
},
{
"code": null,
"e": 30737,
"s": 30726,
"text": "Javascript"
},
{
"code": "// C++ program to implement// Post Order traversal// of Binary Tree in O(N)// time and O(1) space#include <bits/stdc++.h>using namespace std; class node{ public: int data; node *left, *right;}; // Helper function that allocates a// new node with the given data and// NULL left and right pointers.node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Postorder traversal without recursion// and without stackvoid postOrderConstSpace(node* root){ if (root == NULL) return; node* current = newNode(-1); node* pre = NULL; node* prev = NULL; node* succ = NULL; node* temp = NULL; current->left = root; while (current) { // If left child is null. // Move to right child. if (current->left == NULL) { current = current->right; } else { pre = current->left; // Inorder predecessor while (pre->right && pre->right != current) pre = pre->right; // The connection between current and // predecessor is made if (pre->right == NULL) { // Make current as the right // child of the right most node pre->right = current; // Traverse the left child current = current->left; } else { pre->right = NULL; succ = current; current = current->left; prev = NULL; // Traverse along the right // subtree to the // right-most child while (current != NULL) { temp = current->right; current->right = prev; prev = current; current = temp; } // Traverse back // to current's left child // node while (prev != NULL) { cout << prev->data << \" \"; temp = prev->right; prev->right = current; current = prev; prev = temp; } current = succ; current = current->right; } } }} // Driver codeint main(){ /* Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 */ node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->right->left = newNode(8); root->left->right->right = newNode(9); postOrderConstSpace(root); return 0;} // This code is contributed by Saurav Chaudhary",
"e": 33956,
"s": 30737,
"text": null
},
{
"code": "// Java program to implement// Post Order traversal// of Binary Tree in O(N)// time and O(1) space // Definition of the// binary treeclass TreeNode { public int data; public TreeNode left; public TreeNode right; public TreeNode(int data) { this.data = data; } public String toString() { return data + \" \"; }} public class PostOrder { TreeNode root; // Function to find Post Order // Traversal Using Constant space void postOrderConstantspace(TreeNode root) { if (root == null) return; TreeNode current = new TreeNode(-1), pre = null; TreeNode prev = null, succ = null, temp = null; current.left = root; while (current != null) { // Go to the right child // if current does not // have a left child if (current.left == null) { current = current.right; } else { // Traverse left child pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { // Make current as the right // child of the right most node pre.right = current; // Traverse the left child current = current.left; } else { pre.right = null; succ = current; current = current.left; prev = null; // Traverse along the right // subtree to the // right-most child while (current != null) { temp = current.right; current.right = prev; prev = current; current = temp; } // Traverse back from // right most child to // current's left child node while (prev != null) { System.out.print(prev); temp = prev.right; prev.right = current; current = prev; prev = temp; } current = succ; current = current.right; } } } } // Driver Code public static void main(String[] args) { /* Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 */ PostOrder tree = new PostOrder(); tree.root = new TreeNode(1); tree.root.left = new TreeNode(2); tree.root.right = new TreeNode(3); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(5); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(7); tree.root.left.right.left = new TreeNode(8); tree.root.left.right.right = new TreeNode(9); tree.postOrderConstantspace( tree.root); }}",
"e": 37489,
"s": 33956,
"text": null
},
{
"code": "# Python3 program to implement# Post Order traversal# of Binary Tree in O(N)# time and O(1) spaceclass node: def __init__(self, data): self.data = data self.left = None self.right = None # Helper function that allocates a# new node with the given data and# None left and right pointers.def newNode(data): temp = node(data) return temp # Postorder traversal without recursion# and without stackdef postOrderConstSpace(root): if (root == None): return current = newNode(-1) pre = None prev = None succ = None temp = None current.left = root while (current): # If left child is None. # Move to right child. if (current.left == None): current = current.right else: pre = current.left # Inorder predecessor while (pre.right and pre.right != current): pre = pre.right # The connection between current # and predecessor is made if (pre.right == None): # Make current as the right # child of the right most node pre.right = current # Traverse the left child current = current.left else: pre.right = None succ = current current = current.left prev = None # Traverse along the right # subtree to the # right-most child while (current != None): temp = current.right current.right = prev prev = current current = temp # Traverse back # to current's left child # node while (prev != None): print(prev.data, end = ' ') temp = prev.right prev.right = current current = prev prev = temp current = succ current = current.right # Driver codeif __name__=='__main__': ''' Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 ''' root = None root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.right.left = newNode(8) root.left.right.right = newNode(9) postOrderConstSpace(root) # This code is contributed by pratham76",
"e": 40369,
"s": 37489,
"text": null
},
{
"code": "// C# program to implement// Post Order traversal// of Binary Tree in O(N)// time and O(1) spaceusing System; // Definition of the// binary treepublic class TreeNode{ public int data; public TreeNode left, right; public TreeNode(int item) { data = item; left = right = null; }} class PostOrder{ public TreeNode root; // Function to find Post Order// Traversal Using Constant spacevoid postOrderConstantspace(TreeNode root){ if (root == null) return; TreeNode current = new TreeNode(-1), pre = null; TreeNode prev = null, succ = null, temp = null; current.left = root; while (current != null) { // Go to the right child // if current does not // have a left child if (current.left == null) { current = current.right; } else { // Traverse left child pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { // Make current as the right // child of the right most node pre.right = current; // Traverse the left child current = current.left; } else { pre.right = null; succ = current; current = current.left; prev = null; // Traverse along the right // subtree to the // right-most child while (current != null) { temp = current.right; current.right = prev; prev = current; current = temp; } // Traverse back from // right most child to // current's left child node while (prev != null) { Console.Write(prev.data + \" \"); temp = prev.right; prev.right = current; current = prev; prev = temp; } current = succ; current = current.right; } } }} // Driver codestatic public void Main (){ /* Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 */ PostOrder tree = new PostOrder(); tree.root = new TreeNode(1); tree.root.left = new TreeNode(2); tree.root.right = new TreeNode(3); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(5); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(7); tree.root.left.right.left = new TreeNode(8); tree.root.left.right.right = new TreeNode(9); tree.postOrderConstantspace(tree.root);}} // This code is contributed by offbeat",
"e": 43578,
"s": 40369,
"text": null
},
{
"code": "<script> // Javascript program to implement// Post Order traversal// of Binary Tree in O(N)// time and O(1) space // Definition of the// binary treeclass TreeNode{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root; // Function to find Post Order// Traversal Using Constant spacefunction postOrderConstantspace(root){ if (root == null) return; var current = new TreeNode(-1), pre = null; var prev = null, succ = null, temp = null; current.left = root; while (current != null) { // Go to the right child // if current does not // have a left child if (current.left == null) { current = current.right; } else { // Traverse left child pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { // Make current as the right // child of the right most node pre.right = current; // Traverse the left child current = current.left; } else { pre.right = null; succ = current; current = current.left; prev = null; // Traverse along the right // subtree to the // right-most child while (current != null) { temp = current.right; current.right = prev; prev = current; current = temp; } // Traverse back from // right most child to // current's left child node while (prev != null) { document.write(prev.data + \" \"); temp = prev.right; prev.right = current; current = prev; prev = temp; } current = succ; current = current.right; } } }} // Driver code/* Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 */var tree = new TreeNode();tree.root = new TreeNode(1);tree.root.left = new TreeNode(2);tree.root.right = new TreeNode(3);tree.root.left.left = new TreeNode(4);tree.root.left.right = new TreeNode(5);tree.root.right.left = new TreeNode(6);tree.root.right.right = new TreeNode(7);tree.root.left.right.left = new TreeNode(8);tree.root.left.right.right = new TreeNode(9);postOrderConstantspace(tree.root); </script>",
"e": 46547,
"s": 43578,
"text": null
},
{
"code": null,
"e": 46565,
"s": 46547,
"text": "4 8 9 5 2 6 7 3 1"
},
{
"code": null,
"e": 46609,
"s": 46565,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 46990,
"s": 46609,
"text": "Method 2: In method 1, we traverse a path, reverse references, print nodes as we restore the references by reversing them again. In method 2, instead of reversing paths and restoring the structure, we traverse to the parent node from the current node using the current node’s left subtree. This could be faster depending on the tree structure, for example in a right-skewed tree. "
},
{
"code": null,
"e": 47064,
"s": 46990,
"text": "The following algorithm and diagrams provide the details of the approach."
},
{
"code": null,
"e": 47182,
"s": 47064,
"text": "Below is the conceptual diagram showing how the left and right child references are used to traverse back and forth. "
},
{
"code": null,
"e": 47317,
"s": 47182,
"text": "Below is the diagram which highlights the path 1->2->5->9 and the way the nodes are processed and printed as per the above algorithm. "
},
{
"code": null,
"e": 47368,
"s": 47317,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 47372,
"s": 47368,
"text": "C++"
},
{
"code": null,
"e": 47377,
"s": 47372,
"text": "Java"
},
{
"code": null,
"e": 47385,
"s": 47377,
"text": "Python3"
},
{
"code": null,
"e": 47388,
"s": 47385,
"text": "C#"
},
{
"code": null,
"e": 47399,
"s": 47388,
"text": "Javascript"
},
{
"code": "// C++ Program to implement the above approach#include <bits/stdc++.h>using namespace std; struct TreeNode { TreeNode* left; TreeNode* right; int data; TreeNode(int data) { this->data = data; this->left = nullptr; this->right = nullptr; }}; TreeNode* root; // Function to Calculate Post// Order Traversal Using// Constant Spacestatic void postOrderConstantspace(TreeNode* root){ if (root == nullptr) return; TreeNode* current = nullptr; TreeNode* prevNode = nullptr; TreeNode* pre = nullptr; TreeNode* ptr = nullptr; TreeNode* netChild = nullptr; TreeNode* prevPtr = nullptr; current = root; while (current != nullptr) { if (current->left == nullptr) { current->left = prevNode; // Set prevNode to current prevNode = current; current = current->right; } else { pre = current->left; // Find the right most child // in the left subtree while (pre->right != nullptr && pre->right != current) pre = pre->right; if (pre->right == nullptr) { pre->right = current; current = current->left; } else { // Set the right most // child's right pointer // to NULL pre->right = nullptr; cout << pre->data << \" \"; ptr = pre; netChild = pre; prevPtr = pre; while (ptr != nullptr) { if (ptr->right == netChild) { cout << ptr->data << \" \"; netChild = ptr; prevPtr->left = nullptr; } if (ptr == current->left) break; // Break the loop // all the left subtree // nodes of current // processed prevPtr = ptr; ptr = ptr->left; } prevNode = current; current = current->right; } } } cout << prevNode->data << \" \"; // Last path traversal // that includes the root. ptr = prevNode; netChild = prevNode; prevPtr = prevNode; while (ptr != nullptr) { if (ptr->right == netChild) { cout << ptr->data << \" \"; netChild = ptr; prevPtr->left = nullptr; } if (ptr == root) break; prevPtr = ptr; ptr = ptr->left; }} int main(){ /* Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 */ root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); root->right->left = new TreeNode(6); root->right->right = new TreeNode(7); root->left->right->left = new TreeNode(8); root->left->right->right = new TreeNode(9); postOrderConstantspace(root); return 0;} // This code is contributed by mukesh07.",
"e": 50296,
"s": 47399,
"text": null
},
{
"code": "// Java Program to implement// the above approachclass TreeNode { public int data; public TreeNode left; public TreeNode right; public TreeNode(int data) { this.data = data; } public String toString() { return data + \" \"; }} public class PostOrder { TreeNode root; // Function to Calculate Post // Order Traversal // Using Constant Space void postOrderConstantspace(TreeNode root) { if (root == null) return; TreeNode current = null; TreeNode prevNode = null; TreeNode pre = null; TreeNode ptr = null; TreeNode netChild = null; TreeNode prevPtr = null; current = root; while (current != null) { if (current.left == null) { current.left = prevNode; // Set prevNode to current prevNode = current; current = current.right; } else { pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { pre.right = current; current = current.left; } else { // Set the right most // child's right pointer // to NULL pre.right = null; System.out.print(pre); ptr = pre; netChild = pre; prevPtr = pre; while (ptr != null) { if (ptr.right == netChild) { System.out.print(ptr); netChild = ptr; prevPtr.left = null; } if (ptr == current.left) break; // Break the loop // all the left subtree // nodes of current // processed prevPtr = ptr; ptr = ptr.left; } prevNode = current; current = current.right; } } } System.out.print(prevNode); // Last path traversal // that includes the root. ptr = prevNode; netChild = prevNode; prevPtr = prevNode; while (ptr != null) { if (ptr.right == netChild) { System.out.print(ptr); netChild = ptr; prevPtr.left = null; } if (ptr == root) break; prevPtr = ptr; ptr = ptr.left; } } // Main Function public static void main(String[] args) { /* Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 */ PostOrder tree = new PostOrder(); tree.root = new TreeNode(1); tree.root.left = new TreeNode(2); tree.root.right = new TreeNode(3); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(5); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(7); tree.root.left.right.left = new TreeNode(8); tree.root.left.right.right = new TreeNode(9); tree.postOrderConstantspace( tree.root); }}",
"e": 54047,
"s": 50296,
"text": null
},
{
"code": "# Python3 Program to implement the above approachclass TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None # Function to Calculate Post# Order Traversal Using# Constant Spacedef postOrderConstantspace(root): if root == None: return current = None prevNode = None pre = None ptr = None netChild = None prevPtr = None current = root while current != None: if current.left == None: current.left = prevNode # Set prevNode to current prevNode = current current = current.right else: pre = current.left # Find the right most child # in the left subtree while pre.right != None and pre.right != current: pre = pre.right if pre.right == None: pre.right = current current = current.left else: # Set the right most # child's right pointer # to NULL pre.right = None print(pre.data, end = \" \") ptr = pre netChild = pre prevPtr = pre while ptr != None: if ptr.right == netChild: print(ptr.data, end = \" \") netChild = ptr prevPtr.left = None if ptr == current.left: break # Break the loop # all the left subtree # nodes of current # processed prevPtr = ptr ptr = ptr.left prevNode = current current = current.right print(prevNode.data, end = \" \") # Last path traversal # that includes the root. ptr = prevNode netChild = prevNode prevPtr = prevNode while ptr != None: if ptr.right == netChild: print(ptr.data, end = \" \") netChild = ptr prevPtr.left = None if (ptr == root): break prevPtr = ptr ptr = ptr.left \"\"\" Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9\"\"\"root = TreeNode(1)root.left = TreeNode(2)root.right = TreeNode(3)root.left.left = TreeNode(4)root.left.right = TreeNode(5)root.right.left = TreeNode(6)root.right.right = TreeNode(7)root.left.right.left = TreeNode(8)root.left.right.right = TreeNode(9)postOrderConstantspace(root) # This code is contributed by divyeshrabadiya07.",
"e": 56368,
"s": 54047,
"text": null
},
{
"code": "// C# Program to implement// the above approachusing System;class TreeNode{ public int data;public TreeNode left;public TreeNode right; public TreeNode(int data){ this.data = data;} public string toString(){ return data + \" \";}} class PostOrder{ TreeNode root; // Function to Calculate Post// Order Traversal Using// Constant Spacevoid postOrderConstantspace(TreeNode root){ if (root == null) return; TreeNode current = null; TreeNode prevNode = null; TreeNode pre = null; TreeNode ptr = null; TreeNode netChild = null; TreeNode prevPtr = null; current = root; while (current != null) { if (current.left == null) { current.left = prevNode; // Set prevNode to current prevNode = current; current = current.right; } else { pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { pre.right = current; current = current.left; } else { // Set the right most // child's right pointer // to NULL pre.right = null; Console.Write(pre.data + \" \"); ptr = pre; netChild = pre; prevPtr = pre; while (ptr != null) { if (ptr.right == netChild) { Console.Write(ptr.data + \" \"); netChild = ptr; prevPtr.left = null; } if (ptr == current.left) break; // Break the loop // all the left subtree // nodes of current // processed prevPtr = ptr; ptr = ptr.left; } prevNode = current; current = current.right; } } } Console.Write(prevNode.data + \" \"); // Last path traversal // that includes the root. ptr = prevNode; netChild = prevNode; prevPtr = prevNode; while (ptr != null) { if (ptr.right == netChild) { Console.Write(ptr.data + \" \"); netChild = ptr; prevPtr.left = null; } if (ptr == root) break; prevPtr = ptr; ptr = ptr.left; }} // Driver codepublic static void Main(string[] args){ /* Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 */ PostOrder tree = new PostOrder(); tree.root = new TreeNode(1); tree.root.left = new TreeNode(2); tree.root.right = new TreeNode(3); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(5); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(7); tree.root.left.right.left = new TreeNode(8); tree.root.left.right.right = new TreeNode(9); tree.postOrderConstantspace(tree.root);}} // This code is contributed by Rutvik_56",
"e": 59314,
"s": 56368,
"text": null
},
{
"code": "<script> // Javascript Program to implement the above approach class TreeNode { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; // Function to Calculate Post // Order Traversal Using // Constant Space function postOrderConstantspace(root) { if (root == null) return; let current = null; let prevNode = null; let pre = null; let ptr = null; let netChild = null; let prevPtr = null; current = root; while (current != null) { if (current.left == null) { current.left = prevNode; // Set prevNode to current prevNode = current; current = current.right; } else { pre = current.left; // Find the right most child // in the left subtree while (pre.right != null && pre.right != current) pre = pre.right; if (pre.right == null) { pre.right = current; current = current.left; } else { // Set the right most // child's right pointer // to NULL pre.right = null; document.write(pre.data + \" \"); ptr = pre; netChild = pre; prevPtr = pre; while (ptr != null) { if (ptr.right == netChild) { document.write(ptr.data + \" \"); netChild = ptr; prevPtr.left = null; } if (ptr == current.left) break; // Break the loop // all the left subtree // nodes of current // processed prevPtr = ptr; ptr = ptr.left; } prevNode = current; current = current.right; } } } document.write(prevNode.data + \" \"); // Last path traversal // that includes the root. ptr = prevNode; netChild = prevNode; prevPtr = prevNode; while (ptr != null) { if (ptr.right == netChild) { document.write(ptr.data + \" \"); netChild = ptr; prevPtr.left = null; } if (ptr == root) break; prevPtr = ptr; ptr = ptr.left; } } /* Constructed tree is as follows:- 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ 8 9 */ root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); root.left.right.left = new TreeNode(8); root.left.right.right = new TreeNode(9); postOrderConstantspace(root); // This code is contributed by divyesh072019.</script>",
"e": 62412,
"s": 59314,
"text": null
},
{
"code": null,
"e": 62431,
"s": 62412,
"text": "4 8 9 5 2 6 7 3 1 "
},
{
"code": null,
"e": 62476,
"s": 62431,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 62495,
"s": 62476,
"text": "sauravchaudhary717"
},
{
"code": null,
"e": 62503,
"s": 62495,
"text": "offbeat"
},
{
"code": null,
"e": 62513,
"s": 62503,
"text": "rutvik_56"
},
{
"code": null,
"e": 62523,
"s": 62513,
"text": "pratham76"
},
{
"code": null,
"e": 62538,
"s": 62523,
"text": "ankurgupta1999"
},
{
"code": null,
"e": 62550,
"s": 62538,
"text": "geekygaurab"
},
{
"code": null,
"e": 62559,
"s": 62550,
"text": "famously"
},
{
"code": null,
"e": 62573,
"s": 62559,
"text": "divyesh072019"
},
{
"code": null,
"e": 62591,
"s": 62573,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 62600,
"s": 62591,
"text": "mukesh07"
},
{
"code": null,
"e": 62618,
"s": 62600,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 62640,
"s": 62618,
"text": "interview-preparation"
},
{
"code": null,
"e": 62657,
"s": 62640,
"text": "morris-traversal"
},
{
"code": null,
"e": 62677,
"s": 62657,
"text": "PostOrder Traversal"
},
{
"code": null,
"e": 62693,
"s": 62677,
"text": "Data Structures"
},
{
"code": null,
"e": 62703,
"s": 62693,
"text": "Recursion"
},
{
"code": null,
"e": 62708,
"s": 62703,
"text": "Tree"
},
{
"code": null,
"e": 62724,
"s": 62708,
"text": "Data Structures"
},
{
"code": null,
"e": 62734,
"s": 62724,
"text": "Recursion"
},
{
"code": null,
"e": 62739,
"s": 62734,
"text": "Tree"
},
{
"code": null,
"e": 62837,
"s": 62739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 62864,
"s": 62837,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 62900,
"s": 62864,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 62959,
"s": 62900,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 63007,
"s": 62959,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 63030,
"s": 63007,
"text": "Insertion in a B+ tree"
},
{
"code": null,
"e": 63090,
"s": 63030,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 63175,
"s": 63090,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 63185,
"s": 63175,
"text": "Recursion"
},
{
"code": null,
"e": 63212,
"s": 63185,
"text": "Program for Tower of Hanoi"
}
] |
SQL Query to Convert Datetime to String - GeeksforGeeks
|
25 Oct, 2021
In order to convert a DateTime to a string, we can use CONVERT() and CAST() function. These functions are used to converts a value(of any datatype) into a specified datatype.
Syntax:
CONVERT(VARCHAR, datetime [,style])
VARCHAR – It represent the string type.
datetime – It can be the expression that evaluates date or datetime value that you want to convert into string.
style – It specifies the format of the date. It’s value is predefined by the SQL Server. The style parameter is optional.
Syntax:
CAST(EXPRESSION AS DATATYPE(length))
EXPRESSION – It represent the value that need to be converted.
DATATYPE – It is the type of the data to which we want to convert our expression.
length – It represent the length of the resulting datatype(optional).
Without
Century (YY)
With
Century(YYYY)
Standard
Format
–
0 or 100
Default for datetime
and smalldatetime
mon dd yyyy
hh:miAM (or PM)
1
101
U.S.
1 = mm/dd/yy
101 = mm/dd/yyyy
2
102
ANSI
2 = yy.mm.dd
102 = yyyy.mm.dd
3
103
British/French
3 = dd/mm/yy
103 = dd/mm/yyyy
4
104
German
4 = dd.mm.yy
104 = dd.mm.yyyy
5
105
Italian
5 = dd-mm-yy
105 = dd-mm-yyyy
6
106
–
6 = dd mon yy
106 = dd mon yyyy
7
107
–
7 = Mon dd, yy
107 = Mon dd, yyyy
8
108
–
hh:mm:ss
In the below example, we will convert the DateTime into a string in different formats.
Step 1: Create a database
Query:
CREATE DATABASE Product_order;
Figure: Create DATABASE
Step 2: Create a table
Now, we need to create a table inside our database. For this, we will use CREATE statement.
Query:
CREATE TABLE orders (prod_id INT,
prod_name VARCHAR(255),
order_date DATE,
PRIMARY KEY(prod_id));
Figure: Create a table orders
Step 3: Insert data into a table
In this step, we will insert data inside our orders table. For inserting data we will use an INSERT statement.
Query:
INSERT INTO orders VALUES (101, 'iPhone', '2020-07-20'),
(102, 'iPad', '2018-01-01'),
(103, 'iWatch', '2019-03-15'),
(104, 'iMac', '2016-05-13');
Figure: Insert data into the order table
Step 4: In order to verify the contents of the table, we will be using the SELECT statement.
SELECT * FROM orders;
Figure: Select statement query
Output:
Figure: Order table
Step 5: Using CONVERT() function
Query :
/*Declaring DATETIME as dt*/
DECLARE @dt DATETIME = (SELECT order_date
FROM orders WHERE prod_id = 101);
/*SELECT statement is used to print the s1 message*/
SELECT
CONVERT(VARCHAR(20),@dt,0) s1;
Figure: CONVERT() function query
Output:
Figure: Output
Query :
In this, we are changing the style parameter to 1. Similarly, you can use different style parameter values from the above table.
/*Declaring DATETIME as dt*/
DECLARE @dt DATETIME = (SELECT order_date
FROM orders WHERE prod_id = 103);
/*SELECT statement is used to print the s1 message*/
SELECT
CONVERT(VARCHAR(20),@dt,1) s1;
Figure: CONVERT() function query
Output :
Figure: Output
Step 6: Using CAST() function
Query:
/*Declaring DATETIME as dt*/
DECLARE @dt DATETIME = (SELECT order_date
FROM orders WHERE prod_id = 102);
/*SELECT statement is used to print the s1 message*/
SELECT
CAST(@dt AS DATETIME) s1;
Figure: CAST() function query
Output:
Figure: Output
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Convert VARCHAR to INT
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25623,
"s": 25595,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 25798,
"s": 25623,
"text": "In order to convert a DateTime to a string, we can use CONVERT() and CAST() function. These functions are used to converts a value(of any datatype) into a specified datatype."
},
{
"code": null,
"e": 25806,
"s": 25798,
"text": "Syntax:"
},
{
"code": null,
"e": 25842,
"s": 25806,
"text": "CONVERT(VARCHAR, datetime [,style])"
},
{
"code": null,
"e": 25882,
"s": 25842,
"text": "VARCHAR – It represent the string type."
},
{
"code": null,
"e": 25994,
"s": 25882,
"text": "datetime – It can be the expression that evaluates date or datetime value that you want to convert into string."
},
{
"code": null,
"e": 26116,
"s": 25994,
"text": "style – It specifies the format of the date. It’s value is predefined by the SQL Server. The style parameter is optional."
},
{
"code": null,
"e": 26124,
"s": 26116,
"text": "Syntax:"
},
{
"code": null,
"e": 26161,
"s": 26124,
"text": "CAST(EXPRESSION AS DATATYPE(length))"
},
{
"code": null,
"e": 26224,
"s": 26161,
"text": "EXPRESSION – It represent the value that need to be converted."
},
{
"code": null,
"e": 26306,
"s": 26224,
"text": "DATATYPE – It is the type of the data to which we want to convert our expression."
},
{
"code": null,
"e": 26376,
"s": 26306,
"text": "length – It represent the length of the resulting datatype(optional)."
},
{
"code": null,
"e": 26385,
"s": 26376,
"text": "Without "
},
{
"code": null,
"e": 26398,
"s": 26385,
"text": "Century (YY)"
},
{
"code": null,
"e": 26403,
"s": 26398,
"text": "With"
},
{
"code": null,
"e": 26418,
"s": 26403,
"text": " Century(YYYY)"
},
{
"code": null,
"e": 26427,
"s": 26418,
"text": "Standard"
},
{
"code": null,
"e": 26434,
"s": 26427,
"text": "Format"
},
{
"code": null,
"e": 26436,
"s": 26434,
"text": "–"
},
{
"code": null,
"e": 26445,
"s": 26436,
"text": "0 or 100"
},
{
"code": null,
"e": 26467,
"s": 26445,
"text": "Default for datetime "
},
{
"code": null,
"e": 26485,
"s": 26467,
"text": "and smalldatetime"
},
{
"code": null,
"e": 26498,
"s": 26485,
"text": "mon dd yyyy "
},
{
"code": null,
"e": 26514,
"s": 26498,
"text": "hh:miAM (or PM)"
},
{
"code": null,
"e": 26516,
"s": 26514,
"text": "1"
},
{
"code": null,
"e": 26520,
"s": 26516,
"text": "101"
},
{
"code": null,
"e": 26525,
"s": 26520,
"text": "U.S."
},
{
"code": null,
"e": 26538,
"s": 26525,
"text": "1 = mm/dd/yy"
},
{
"code": null,
"e": 26555,
"s": 26538,
"text": "101 = mm/dd/yyyy"
},
{
"code": null,
"e": 26557,
"s": 26555,
"text": "2"
},
{
"code": null,
"e": 26561,
"s": 26557,
"text": "102"
},
{
"code": null,
"e": 26566,
"s": 26561,
"text": "ANSI"
},
{
"code": null,
"e": 26579,
"s": 26566,
"text": "2 = yy.mm.dd"
},
{
"code": null,
"e": 26596,
"s": 26579,
"text": "102 = yyyy.mm.dd"
},
{
"code": null,
"e": 26598,
"s": 26596,
"text": "3"
},
{
"code": null,
"e": 26602,
"s": 26598,
"text": "103"
},
{
"code": null,
"e": 26617,
"s": 26602,
"text": "British/French"
},
{
"code": null,
"e": 26630,
"s": 26617,
"text": "3 = dd/mm/yy"
},
{
"code": null,
"e": 26647,
"s": 26630,
"text": "103 = dd/mm/yyyy"
},
{
"code": null,
"e": 26649,
"s": 26647,
"text": "4"
},
{
"code": null,
"e": 26653,
"s": 26649,
"text": "104"
},
{
"code": null,
"e": 26660,
"s": 26653,
"text": "German"
},
{
"code": null,
"e": 26673,
"s": 26660,
"text": "4 = dd.mm.yy"
},
{
"code": null,
"e": 26690,
"s": 26673,
"text": "104 = dd.mm.yyyy"
},
{
"code": null,
"e": 26692,
"s": 26690,
"text": "5"
},
{
"code": null,
"e": 26696,
"s": 26692,
"text": "105"
},
{
"code": null,
"e": 26704,
"s": 26696,
"text": "Italian"
},
{
"code": null,
"e": 26717,
"s": 26704,
"text": "5 = dd-mm-yy"
},
{
"code": null,
"e": 26734,
"s": 26717,
"text": "105 = dd-mm-yyyy"
},
{
"code": null,
"e": 26736,
"s": 26734,
"text": "6"
},
{
"code": null,
"e": 26740,
"s": 26736,
"text": "106"
},
{
"code": null,
"e": 26742,
"s": 26740,
"text": "–"
},
{
"code": null,
"e": 26756,
"s": 26742,
"text": "6 = dd mon yy"
},
{
"code": null,
"e": 26774,
"s": 26756,
"text": "106 = dd mon yyyy"
},
{
"code": null,
"e": 26776,
"s": 26774,
"text": "7"
},
{
"code": null,
"e": 26780,
"s": 26776,
"text": "107"
},
{
"code": null,
"e": 26782,
"s": 26780,
"text": "–"
},
{
"code": null,
"e": 26797,
"s": 26782,
"text": "7 = Mon dd, yy"
},
{
"code": null,
"e": 26816,
"s": 26797,
"text": "107 = Mon dd, yyyy"
},
{
"code": null,
"e": 26818,
"s": 26816,
"text": "8"
},
{
"code": null,
"e": 26822,
"s": 26818,
"text": "108"
},
{
"code": null,
"e": 26824,
"s": 26822,
"text": "–"
},
{
"code": null,
"e": 26833,
"s": 26824,
"text": "hh:mm:ss"
},
{
"code": null,
"e": 26922,
"s": 26835,
"text": "In the below example, we will convert the DateTime into a string in different formats."
},
{
"code": null,
"e": 26948,
"s": 26922,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 26955,
"s": 26948,
"text": "Query:"
},
{
"code": null,
"e": 26986,
"s": 26955,
"text": "CREATE DATABASE Product_order;"
},
{
"code": null,
"e": 27010,
"s": 26986,
"text": "Figure: Create DATABASE"
},
{
"code": null,
"e": 27033,
"s": 27010,
"text": "Step 2: Create a table"
},
{
"code": null,
"e": 27125,
"s": 27033,
"text": "Now, we need to create a table inside our database. For this, we will use CREATE statement."
},
{
"code": null,
"e": 27132,
"s": 27125,
"text": "Query:"
},
{
"code": null,
"e": 27293,
"s": 27132,
"text": "CREATE TABLE orders (prod_id INT,\n prod_name VARCHAR(255),\n order_date DATE,\n PRIMARY KEY(prod_id));"
},
{
"code": null,
"e": 27323,
"s": 27293,
"text": "Figure: Create a table orders"
},
{
"code": null,
"e": 27356,
"s": 27323,
"text": "Step 3: Insert data into a table"
},
{
"code": null,
"e": 27467,
"s": 27356,
"text": "In this step, we will insert data inside our orders table. For inserting data we will use an INSERT statement."
},
{
"code": null,
"e": 27474,
"s": 27467,
"text": "Query:"
},
{
"code": null,
"e": 27698,
"s": 27474,
"text": "INSERT INTO orders VALUES (101, 'iPhone', '2020-07-20'),\n (102, 'iPad', '2018-01-01'),\n (103, 'iWatch', '2019-03-15'),\n (104, 'iMac', '2016-05-13');"
},
{
"code": null,
"e": 27739,
"s": 27698,
"text": "Figure: Insert data into the order table"
},
{
"code": null,
"e": 27832,
"s": 27739,
"text": "Step 4: In order to verify the contents of the table, we will be using the SELECT statement."
},
{
"code": null,
"e": 27854,
"s": 27832,
"text": "SELECT * FROM orders;"
},
{
"code": null,
"e": 27885,
"s": 27854,
"text": "Figure: Select statement query"
},
{
"code": null,
"e": 27893,
"s": 27885,
"text": "Output:"
},
{
"code": null,
"e": 27913,
"s": 27893,
"text": "Figure: Order table"
},
{
"code": null,
"e": 27946,
"s": 27913,
"text": "Step 5: Using CONVERT() function"
},
{
"code": null,
"e": 27954,
"s": 27946,
"text": "Query :"
},
{
"code": null,
"e": 28156,
"s": 27954,
"text": "/*Declaring DATETIME as dt*/\nDECLARE @dt DATETIME = (SELECT order_date \nFROM orders WHERE prod_id = 101);\n/*SELECT statement is used to print the s1 message*/\nSELECT \n CONVERT(VARCHAR(20),@dt,0) s1;"
},
{
"code": null,
"e": 28189,
"s": 28156,
"text": "Figure: CONVERT() function query"
},
{
"code": null,
"e": 28197,
"s": 28189,
"text": "Output:"
},
{
"code": null,
"e": 28212,
"s": 28197,
"text": "Figure: Output"
},
{
"code": null,
"e": 28220,
"s": 28212,
"text": "Query :"
},
{
"code": null,
"e": 28349,
"s": 28220,
"text": "In this, we are changing the style parameter to 1. Similarly, you can use different style parameter values from the above table."
},
{
"code": null,
"e": 28547,
"s": 28349,
"text": "/*Declaring DATETIME as dt*/\nDECLARE @dt DATETIME = (SELECT order_date \nFROM orders WHERE prod_id = 103);\n/*SELECT statement is used to print the s1 message*/\nSELECT \nCONVERT(VARCHAR(20),@dt,1) s1;"
},
{
"code": null,
"e": 28580,
"s": 28547,
"text": "Figure: CONVERT() function query"
},
{
"code": null,
"e": 28589,
"s": 28580,
"text": "Output :"
},
{
"code": null,
"e": 28604,
"s": 28589,
"text": "Figure: Output"
},
{
"code": null,
"e": 28634,
"s": 28604,
"text": "Step 6: Using CAST() function"
},
{
"code": null,
"e": 28641,
"s": 28634,
"text": "Query:"
},
{
"code": null,
"e": 28838,
"s": 28641,
"text": "/*Declaring DATETIME as dt*/\nDECLARE @dt DATETIME = (SELECT order_date \nFROM orders WHERE prod_id = 102);\n/*SELECT statement is used to print the s1 message*/\nSELECT \n CAST(@dt AS DATETIME) s1;"
},
{
"code": null,
"e": 28868,
"s": 28838,
"text": "Figure: CAST() function query"
},
{
"code": null,
"e": 28876,
"s": 28868,
"text": "Output:"
},
{
"code": null,
"e": 28891,
"s": 28876,
"text": "Figure: Output"
},
{
"code": null,
"e": 28898,
"s": 28891,
"text": "Picked"
},
{
"code": null,
"e": 28902,
"s": 28898,
"text": "SQL"
},
{
"code": null,
"e": 28906,
"s": 28902,
"text": "SQL"
},
{
"code": null,
"e": 29004,
"s": 28906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29070,
"s": 29004,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 29127,
"s": 29070,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 29159,
"s": 29127,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 29195,
"s": 29159,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 29210,
"s": 29195,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 29288,
"s": 29210,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 29305,
"s": 29288,
"text": "SQL using Python"
},
{
"code": null,
"e": 29367,
"s": 29305,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 29433,
"s": 29367,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
}
] |
UPI Payment Integration in Android - GeeksforGeeks
|
14 Dec, 2021
If you are selling any product or providing any service in your android application, then you should have integrated a feature in your android application where you can allow users to make payment through your application. In this article, we will take a look at the implementation of payment gateway integration in Android. In this article, we will be using the Easy UPI Payment gateway library for adding this feature.
We will be creating a simple application in which we will display multiple edit text fields in which we will be allowing users to enter the details for making a payment. After clicking on make payment button we will display a dialog box to our users for making payment through different apps which are installed in users device. Below is the video in which we will get to see what we are going to build in this article.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding a dependency for easy payment gateway in android
Navigate to the app > Gradle Scripts > build.gradle(:app) and add the below dependency in the dependencies section.
implementation ‘com.shreyaspatil:EasyUpiPayment:2.0’
After adding this dependency now sync your project and now we will move towards adding internet permissions.
Step 3: Adding internet permissions in AndroidManifest.xml.
Navigate to app > AndroidManifest.xml and add the below code to it.
XML
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--edit text for entering amount to be paid-->
<EditText
android:id="@+id/idEdtAmount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="8dp"
android:hint="Enter Amount to be paid"
android:inputType="numberDecimal" />
<!--edit text for entering the upi id
to which we have to make payment-->
<EditText
android:id="@+id/idEdtUpi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtAmount"
android:layout_marginStart="8dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="8dp"
android:hint="Enter your UPI Id"
android:inputType="text" />
<!--edit text for adding the name of the
user whom we have to make payment-->
<EditText
android:id="@+id/idEdtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtUpi"
android:layout_marginStart="8dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="8dp"
android:hint="Enter your Name"
android:inputType="text" />
<!--edit text for adding the description for
the payment which we are making-->
<EditText
android:id="@+id/idEdtDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtName"
android:layout_marginStart="8dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="8dp"
android:hint="Enter Payment Description"
android:inputType="text" />
<!--button for making a payment-->
<Button
android:id="@+id/idBtnMakePayment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtDescription"
android:layout_margin="12dp"
android:text="Make Payment"
android:textAllCaps="false" />
<!--text view for displaying transaction status-->
<TextView
android:id="@+id/idTVTransactionDetails"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idBtnMakePayment"
android:layout_marginTop="30dp"
android:text="Transaction Details"
android:textAlignment="center"
android:textColor="@color/purple_700"
android:visibility="gone" />
</RelativeLayout>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.shreyaspatil.EasyUpiPayment.EasyUpiPayment;
import com.shreyaspatil.EasyUpiPayment.listener.PaymentStatusListener;
import com.shreyaspatil.EasyUpiPayment.model.TransactionDetails;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements PaymentStatusListener {
// initializing variables for our edit text and button.
private EditText amountEdt, upiEdt, nameEdt, descEdt;
private TextView transactionDetailsTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing all our variables.
amountEdt = findViewById(R.id.idEdtAmount);
upiEdt = findViewById(R.id.idEdtUpi);
nameEdt = findViewById(R.id.idEdtName);
descEdt = findViewById(R.id.idEdtDescription);
Button makePaymentBtn = findViewById(R.id.idBtnMakePayment);
transactionDetailsTV = findViewById(R.id.idTVTransactionDetails);
// on below line we are getting date and then we are setting this date as transaction id.
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyyHHmmss", Locale.getDefault());
String transcId = df.format(c);
// on below line we are adding click listener for our payment button.
makePaymentBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line we are getting data from our edit text.
String amount = amountEdt.getText().toString();
String upi = upiEdt.getText().toString();
String name = nameEdt.getText().toString();
String desc = descEdt.getText().toString();
// on below line we are validating our text field.
if (TextUtils.isEmpty(amount) && TextUtils.isEmpty(upi) && TextUtils.isEmpty(name) && TextUtils.isEmpty(desc)) {
Toast.makeText(MainActivity.this, "Please enter all the details..", Toast.LENGTH_SHORT).show();
} else {
// if the edit text is not empty then
// we are calling method to make payment.
makePayment(amount, upi, name, desc, transcId);
}
}
});
}
private void makePayment(String amount, String upi, String name, String desc, String transactionId) {
// on below line we are calling an easy payment method and passing
// all parameters to it such as upi id,name, description and others.
final EasyUpiPayment easyUpiPayment = new EasyUpiPayment.Builder()
.with(this)
// on below line we are adding upi id.
.setPayeeVpa(upi)
// on below line we are setting name to which we are making oayment.
.setPayeeName(name)
// on below line we are passing transaction id.
.setTransactionId(transactionId)
// on below line we are passing transaction ref id.
.setTransactionRefId(transactionId)
// on below line we are adding description to payment.
.setDescription(desc)
// on below line we are passing amount which is being paid.
.setAmount(amount)
// on below line we are calling a build method to build this ui.
.build();
// on below line we are calling a start
// payment method to start a payment.
easyUpiPayment.startPayment();
// on below line we are calling a set payment
// status listener method to call other payment methods.
easyUpiPayment.setPaymentStatusListener(this);
}
@Override
public void onTransactionCompleted(TransactionDetails transactionDetails) {
// on below line we are getting details about transaction when completed.
String transcDetails = transactionDetails.getStatus().toString() + "\n" + "Transaction ID : " + transactionDetails.getTransactionId();
transactionDetailsTV.setVisibility(View.VISIBLE);
// on below line we are setting details to our text view.
transactionDetailsTV.setText(transcDetails);
}
@Override
public void onTransactionSuccess() {
// this method is called when transaction is successful and we are displaying a toast message.
Toast.makeText(this, "Transaction successfully completed..", Toast.LENGTH_SHORT).show();
}
@Override
public void onTransactionSubmitted() {
// this method is called when transaction is done
// but it may be successful or failure.
Log.e("TAG", "TRANSACTION SUBMIT");
}
@Override
public void onTransactionFailed() {
// this method is called when transaction is failure.
Toast.makeText(this, "Failed to complete transaction", Toast.LENGTH_SHORT).show();
}
@Override
public void onTransactionCancelled() {
// this method is called when transaction is cancelled.
Toast.makeText(this, "Transaction cancelled..", Toast.LENGTH_SHORT).show();
}
@Override
public void onAppNotFound() {
// this method is called when the users device is not having any app installed for making payment.
Toast.makeText(this, "No app found for making transaction..", Toast.LENGTH_SHORT).show();
}
}
Now run your app and see the output of the app.
Note: Make sure to run your app on a real device and you should be having an app for making payments. And put the amount in decimal.
Output:
gulshankumarar231
Android
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Read Data from SQLite Database in Android?
Flutter - Custom Bottom Navigation Bar
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java
|
[
{
"code": null,
"e": 25136,
"s": 25105,
"text": " \n14 Dec, 2021\n"
},
{
"code": null,
"e": 25558,
"s": 25136,
"text": "If you are selling any product or providing any service in your android application, then you should have integrated a feature in your android application where you can allow users to make payment through your application. In this article, we will take a look at the implementation of payment gateway integration in Android. In this article, we will be using the Easy UPI Payment gateway library for adding this feature. "
},
{
"code": null,
"e": 25979,
"s": 25558,
"text": "We will be creating a simple application in which we will display multiple edit text fields in which we will be allowing users to enter the details for making a payment. After clicking on make payment button we will display a dialog box to our users for making payment through different apps which are installed in users device. Below is the video in which we will get to see what we are going to build in this article. "
},
{
"code": null,
"e": 26008,
"s": 25979,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26170,
"s": 26008,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26235,
"s": 26170,
"text": "Step 2: Adding a dependency for easy payment gateway in android "
},
{
"code": null,
"e": 26352,
"s": 26235,
"text": "Navigate to the app > Gradle Scripts > build.gradle(:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 26405,
"s": 26352,
"text": "implementation ‘com.shreyaspatil:EasyUpiPayment:2.0’"
},
{
"code": null,
"e": 26515,
"s": 26405,
"text": "After adding this dependency now sync your project and now we will move towards adding internet permissions. "
},
{
"code": null,
"e": 26576,
"s": 26515,
"text": "Step 3: Adding internet permissions in AndroidManifest.xml. "
},
{
"code": null,
"e": 26645,
"s": 26576,
"text": "Navigate to app > AndroidManifest.xml and add the below code to it. "
},
{
"code": null,
"e": 26649,
"s": 26645,
"text": "XML"
},
{
"code": "\n\n\n\n\n\n\n<uses-permission android:name=\"android.permission.INTERNET\" />\n\n\n\n\n\n",
"e": 26735,
"s": 26659,
"text": null
},
{
"code": null,
"e": 26783,
"s": 26735,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26926,
"s": 26783,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 26930,
"s": 26926,
"text": "XML"
},
{
"code": "\n\n\n\n\n\n\n<?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 android:orientation=\"vertical\"\n tools:context=\".MainActivity\"> \n \n <!--edit text for entering amount to be paid-->\n <EditText\n android:id=\"@+id/idEdtAmount\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"8dp\"\n android:layout_marginTop=\"15dp\"\n android:layout_marginEnd=\"8dp\"\n android:hint=\"Enter Amount to be paid\"\n android:inputType=\"numberDecimal\" /> \n \n <!--edit text for entering the upi id \n to which we have to make payment-->\n <EditText\n android:id=\"@+id/idEdtUpi\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/idEdtAmount\"\n android:layout_marginStart=\"8dp\"\n android:layout_marginTop=\"15dp\"\n android:layout_marginEnd=\"8dp\"\n android:hint=\"Enter your UPI Id\"\n android:inputType=\"text\" /> \n \n <!--edit text for adding the name of the \n user whom we have to make payment-->\n <EditText\n android:id=\"@+id/idEdtName\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/idEdtUpi\"\n android:layout_marginStart=\"8dp\"\n android:layout_marginTop=\"15dp\"\n android:layout_marginEnd=\"8dp\"\n android:hint=\"Enter your Name\"\n android:inputType=\"text\" /> \n \n <!--edit text for adding the description for \n the payment which we are making-->\n <EditText\n android:id=\"@+id/idEdtDescription\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/idEdtName\"\n android:layout_marginStart=\"8dp\"\n android:layout_marginTop=\"15dp\"\n android:layout_marginEnd=\"8dp\"\n android:hint=\"Enter Payment Description\"\n android:inputType=\"text\" /> \n \n <!--button for making a payment-->\n <Button\n android:id=\"@+id/idBtnMakePayment\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/idEdtDescription\"\n android:layout_margin=\"12dp\"\n android:text=\"Make Payment\"\n android:textAllCaps=\"false\" /> \n \n <!--text view for displaying transaction status-->\n <TextView\n android:id=\"@+id/idTVTransactionDetails\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/idBtnMakePayment\"\n android:layout_marginTop=\"30dp\"\n android:text=\"Transaction Details\"\n android:textAlignment=\"center\"\n android:textColor=\"@color/purple_700\"\n android:visibility=\"gone\" /> \n \n</RelativeLayout>\n\n\n\n\n\n",
"e": 29963,
"s": 26940,
"text": null
},
{
"code": null,
"e": 30011,
"s": 29963,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 30201,
"s": 30011,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30206,
"s": 30201,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\nimport android.os.Bundle; \nimport android.text.TextUtils; \nimport android.util.Log; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.EditText; \nimport android.widget.TextView; \nimport android.widget.Toast; \n \nimport androidx.appcompat.app.AppCompatActivity; \n \nimport com.shreyaspatil.EasyUpiPayment.EasyUpiPayment; \nimport com.shreyaspatil.EasyUpiPayment.listener.PaymentStatusListener; \nimport com.shreyaspatil.EasyUpiPayment.model.TransactionDetails; \n \nimport java.text.SimpleDateFormat; \nimport java.util.Calendar; \nimport java.util.Date; \nimport java.util.Locale; \n \npublic class MainActivity extends AppCompatActivity implements PaymentStatusListener { \n \n // initializing variables for our edit text and button. \n private EditText amountEdt, upiEdt, nameEdt, descEdt; \n private TextView transactionDetailsTV; \n \n @Override\n protected void onCreate(Bundle savedInstanceState) { \n super.onCreate(savedInstanceState); \n setContentView(R.layout.activity_main); \n \n // initializing all our variables. \n amountEdt = findViewById(R.id.idEdtAmount); \n upiEdt = findViewById(R.id.idEdtUpi); \n nameEdt = findViewById(R.id.idEdtName); \n descEdt = findViewById(R.id.idEdtDescription); \n Button makePaymentBtn = findViewById(R.id.idBtnMakePayment); \n transactionDetailsTV = findViewById(R.id.idTVTransactionDetails); \n \n // on below line we are getting date and then we are setting this date as transaction id. \n Date c = Calendar.getInstance().getTime(); \n SimpleDateFormat df = new SimpleDateFormat(\"ddMMyyyyHHmmss\", Locale.getDefault()); \n String transcId = df.format(c); \n \n // on below line we are adding click listener for our payment button. \n makePaymentBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n // on below line we are getting data from our edit text. \n String amount = amountEdt.getText().toString(); \n String upi = upiEdt.getText().toString(); \n String name = nameEdt.getText().toString(); \n String desc = descEdt.getText().toString(); \n // on below line we are validating our text field. \n if (TextUtils.isEmpty(amount) && TextUtils.isEmpty(upi) && TextUtils.isEmpty(name) && TextUtils.isEmpty(desc)) { \n Toast.makeText(MainActivity.this, \"Please enter all the details..\", Toast.LENGTH_SHORT).show(); \n } else { \n // if the edit text is not empty then \n // we are calling method to make payment. \n makePayment(amount, upi, name, desc, transcId); \n } \n } \n }); \n } \n \n private void makePayment(String amount, String upi, String name, String desc, String transactionId) { \n // on below line we are calling an easy payment method and passing \n // all parameters to it such as upi id,name, description and others. \n final EasyUpiPayment easyUpiPayment = new EasyUpiPayment.Builder() \n .with(this) \n // on below line we are adding upi id. \n .setPayeeVpa(upi) \n // on below line we are setting name to which we are making oayment. \n .setPayeeName(name) \n // on below line we are passing transaction id. \n .setTransactionId(transactionId) \n // on below line we are passing transaction ref id. \n .setTransactionRefId(transactionId) \n // on below line we are adding description to payment. \n .setDescription(desc) \n // on below line we are passing amount which is being paid. \n .setAmount(amount) \n // on below line we are calling a build method to build this ui. \n .build(); \n // on below line we are calling a start \n // payment method to start a payment. \n easyUpiPayment.startPayment(); \n // on below line we are calling a set payment \n // status listener method to call other payment methods. \n easyUpiPayment.setPaymentStatusListener(this); \n } \n \n @Override\n public void onTransactionCompleted(TransactionDetails transactionDetails) { \n // on below line we are getting details about transaction when completed. \n String transcDetails = transactionDetails.getStatus().toString() + \"\\n\" + \"Transaction ID : \" + transactionDetails.getTransactionId(); \n transactionDetailsTV.setVisibility(View.VISIBLE); \n // on below line we are setting details to our text view. \n transactionDetailsTV.setText(transcDetails); \n } \n \n @Override\n public void onTransactionSuccess() { \n // this method is called when transaction is successful and we are displaying a toast message. \n Toast.makeText(this, \"Transaction successfully completed..\", Toast.LENGTH_SHORT).show(); \n } \n \n @Override\n public void onTransactionSubmitted() { \n // this method is called when transaction is done \n // but it may be successful or failure. \n Log.e(\"TAG\", \"TRANSACTION SUBMIT\"); \n } \n \n @Override\n public void onTransactionFailed() { \n // this method is called when transaction is failure. \n Toast.makeText(this, \"Failed to complete transaction\", Toast.LENGTH_SHORT).show(); \n } \n \n @Override\n public void onTransactionCancelled() { \n // this method is called when transaction is cancelled. \n Toast.makeText(this, \"Transaction cancelled..\", Toast.LENGTH_SHORT).show(); \n } \n \n @Override\n public void onAppNotFound() { \n // this method is called when the users device is not having any app installed for making payment. \n Toast.makeText(this, \"No app found for making transaction..\", Toast.LENGTH_SHORT).show(); \n } \n}\n\n\n\n\n\n",
"e": 36282,
"s": 30216,
"text": null
},
{
"code": null,
"e": 36331,
"s": 36282,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 36464,
"s": 36331,
"text": "Note: Make sure to run your app on a real device and you should be having an app for making payments. And put the amount in decimal."
},
{
"code": null,
"e": 36472,
"s": 36464,
"text": "Output:"
},
{
"code": null,
"e": 36490,
"s": 36472,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 36500,
"s": 36490,
"text": "\nAndroid\n"
},
{
"code": null,
"e": 36507,
"s": 36500,
"text": "\nJava\n"
},
{
"code": null,
"e": 36712,
"s": 36507,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 36754,
"s": 36712,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 36792,
"s": 36754,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 36842,
"s": 36792,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 36881,
"s": 36842,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36954,
"s": 36881,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 36969,
"s": 36954,
"text": "Arrays in Java"
},
{
"code": null,
"e": 37013,
"s": 36969,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37035,
"s": 37013,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37071,
"s": 37035,
"text": "Arrays.sort() in Java with examples"
}
] |
How do we use file.readlines() to read multiple lines using Python?
|
The read function reads the whole file at once. You can use the readlines function to read the file line by line.
You can use the following to read the file line by line:
f = open('my_file.txt', 'r+')
for line in f.readlines():
print line
f.close()
You can also use the with...open statement to open the file and read line by line. For example,
with open('my_file.txt', 'r+') as f:
for line in f.readlines():
print line
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "The read function reads the whole file at once. You can use the readlines function to read the file line by line."
},
{
"code": null,
"e": 1233,
"s": 1176,
"text": "You can use the following to read the file line by line:"
},
{
"code": null,
"e": 1315,
"s": 1233,
"text": "f = open('my_file.txt', 'r+')\nfor line in f.readlines():\n print line\nf.close()"
},
{
"code": null,
"e": 1411,
"s": 1315,
"text": "You can also use the with...open statement to open the file and read line by line. For example,"
},
{
"code": null,
"e": 1498,
"s": 1411,
"text": "with open('my_file.txt', 'r+') as f:\n for line in f.readlines():\n print line"
}
] |
Starbucks Customer profiling using CatBoost and Bokeh | by Hardik B. | Towards Data Science
|
In this post, I explore the customer data provided by Starbucks in collaboration with Udacity to understand customer behaviors in light of potential rewards. The Starbucks mobile app sends out different kinds of incentive offers to its customers to keep them engaged with the brand.
The motivation of this post is to discuss a solution approach taken to analyze the data and machine learning solution that predicts customer responsiveness.
I have used a machine learning library CatBoost for a multiclass classification problem and Bokeh as a primary visualization tool.
The GitHub Repo of the project can be found here.
This data set contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer, such as a discount or BOGO (buy one get one free). Some users might not receive any offers during certain weeks.
Every offer has a validity period before the offer expires. As an example, a BOGO offer might be valid for only five days. You’ll see in the data set that informational offers have a validity period even though these ads are merely providing information about a product; for example, if an informational offer has seven days of validity, you can assume the customer is feeling the influence of the offer for seven days after receiving the advertisement.
[Project Overview is taken from Udacity’s Capstone Project for DataScience NanoDegree Program]
Data Sets
The data is contained in three files:
portfolio.json — containing offer ids and metadata about each offer (duration, type)
profile.json — demographic data for each customer
transcript.json — records for transactions, offers received, offers viewed, and offers complete
The aim is to analyze individual customer behaviors to identify unusual patterns. The finding of such an analysis should help Starbucks business to re-evaluate its rewards program based on specific outcomes.
I aim to provide analysis targeting the following business questions:
Can we classify customers based on their responsiveness?
Can we identify high paying customers who don’t care about the rewards program?
Can we identify customers who haven’t made any transactions in the past?
Can we visualize customers’ interaction with offers and spending activities to gain interesting insights?
There are three different datasets, which I explore one by one and identify any issues like missing information, extra/redundant information, other inconsistencies. I accomplish this by making good use of visualization as necessary. At the end of this step, I have a clean dataset ready for further exploration.
I combine all the three datasets into one single set and perform further analysis through advanced visualization. Based on this, I frame a classification problem to tackle through some machine learning algorithms.
I have chosen a CatBoost algorithm, a multiclass classification algorithm. It identifies the relations between highly co-related features automatically and comes with built-in visualizations. It is straightforward to train and evaluate the model using it. The final results are usually better with default parameters because CatBoots uses horizontal decision trees internally. Since we are dealing with classification and the error of misclassification doesn’t result in any adverse effects, in this case, model accuracy should be our standard evaluation criteria, including the confusion matrix.
In the end, I evaluate the results of the overall analysis, including machine learning model evaluation.
By looking at the ‘channels’ columns, it makes sense to disaggregate each channel values into separate columns and encode it using 0|1 identifiers.
Let’s create dummies for the ‘offer_type’ column and encode it and also drop the original column as we no longer require it.
Here each offer is always sent via the ‘email’ channel. Therefore this feature is only informative and may not add any value to the predictive power of any machine learning algorithm.
It is obvious that ‘age’ value 118 is a placeholder for the missing value.Further analysis reveals 2175 missing entries for gender, age, and income columns together.
‘became_member_on’ column is a timestamped date, let’s transform it into a more readable format and also extract the number of days since the customer has signed up.
Let’s create some visualizations to analyze the demographic data
The left chart shows that there is a steady increase in the number of customers over the years. However, there is a steep fall at the end of 2017. This could also be due to sampling to prepare the dataset.
Surprisingly, there are many customers who fall into relatively lower-income groups and very few customers who fall into relatively high-income groups.
The pair chart shows that there are not many female customers, and the female group is relatively older and has a higher income.
Specific Observations
There exist no customers in the age group [20, 30] having an income higher than 80K.
There exists no customer in the age group [40, 50] having an income higher than 100K.
All the customer who became a member more than 2000 days ago has income less than 100K.
The quick look at the transcript dataset reveals that the ‘value’ column is encoded as a dictionary. If the event is related to offers, then the ‘value’ column encode offer id, and in case of transaction event, it encodes the amount of transaction.
Therefore, it makes sense to decode the ‘value’ column into separate columns to understand the relationship between offers and the amount spent by the customers.
First of all, we should calculate the total number of offers completed and the total number of offers viewed by each customer.The data includes ‘offers completed’ by customers, knowingly or unknowingly. The customers who have unknowingly completed offers should not be sent out further offers. This group represents profitable customers for the company.
We combine our transcript dataset with the customer demographics (profile) and portfolio data.
After several preprocessing steps applied to the joint dataset,
The above chart displays the number of offers viewed against timestamp in hours. There are six peaks where the number of viewed offers increases dramatically.
I have embedded the number of offers received (correct received offer count is four times the marked one) in the chart. When new offers get received, the count of viewed offer increases and then slowly decreases over time. Generally speaking, most offers are viewed within 24 hours of receipt.
The above chart shows the number of completed offers against a timestamp in hours. It follows a similar pattern as the graph before because new offers are sent six times in 24 day period, and hence the chart has six peaks.
Between each peak, the chart decreases gradually, just like viewed offers chart. However, the decrease is not as smooth as for the viewed offer chart. There are some local picks during the decline.
The above chart combines a number of transactions and offers completed together. There is a local peak between each ‘offer sent out interval’ for transactions. This implies that when offers are received, customers quickly perform some transactions resulting in offer completion.
At time stamp 0, there exist around 600 transactions. Around 200 of them contribute to ‘offer completion’ (number of offers completed at timestamp 0), which is roughly a 25% conversion rate. This figure is roughly in agreement with the ratio of the total number of completed offers to the total number of transactions => 138953/33579)*100 = 24.16%.
There exist some high-value transactions (above 100 USD). It could be a large order from individuals for special events or from corporate clients. Such a high-value transaction leads to all of the current offers associated with a customer to complete.
In reality, these transactions were not motivated to complete the offers, and therefore it should be considered side effects. Sending out offers to such high paying customers would not lead to an increase or decrease in their purchasing behavior. Therefore we should remove such high-value transactions from the dataset.
Next, we should also find out and remove non-responsive customers. I define non-responsive customer = no received offered viewed + no transaction made.
After some further preprocessing steps, I found 422 customers having made no transaction. Out of them, 412 has received and viewed offers while 10 of them have received and not viewed any offers.
Similarly, analyzing the transaction amount, the following observations were collected:
There are some transactions > 1000 USD.
There are many more transactions in the range [0.05,50] than the rest of the range.
Any transaction greater than 50 USD can be treated as a high-value transaction and not necessarily motivated to complete the offers.
In this section, we look at the customer’s interaction with offers through some advanced visualizations. Based on that, I define some calculated features.
Here in the above chart, we have a customer who has completed all the offers sent out to him/her. It usually takes more than one transaction to complete an offer if those transactions are low value.
Sometimes, the customer views the offer instantly while sometimes, he/she views it at a later time.
Out of 4 offers completed, only 1 (last completed) is not viewed by the customer.
Here we have two high paying customers side by side who has completed all the received offers.
Interestingly, for customer ‘9fa’ after completing the first offer, he/she has made five transactions amounting in total around 75 USD without any pending offer to complete. It demonstrates that those transactions were not motivated to complete the offer and show customers spending tendencies in the absence of any offers.
Based on the above analysis I derive the following custom features1. Percentage of Offers completed by a given customer2. Absolute count of Offers completed by a given customer3. Percentage of Offers viewed by a given customer4. Absolute count of Offers viewed by a given customer5. Total amount spent by a given customer
Considerations:
Our problem falls into the category of multi-class classification. The multi-class classification problem can be summarised as below:Given a dataset with instances xi together with N classes where every instance xi belongs precisely to one class yi is a problem targeted for a multiclass classifier.After the training and testing, we have a table with the correct class yi and the predicted class ai for every instance xi in the test set. So for every instance, we have either a match (yi=ai) or a miss (yi≠ai).Assuming we have balanced class distribution in our training set, evaluation using a confusion matrix together with the average accuracy score should be sufficient. However, F1-score can also be used for the evaluation of the multi-class problem.
Since the cost of misclassification is not high in our case (sending an offer to the non-responsive customer doesn’t cost the company extra money), F1-score is not necessary.
In this project, I prefer to use the confusion matrix and the average score as our evaluation measures.Confusion Matrix:A confusion matrix shows the combination of the actual and predicted classes. Each row of the matrix represents the instances in a predicted class, while each column represents the instances in an actual class. It is a good measure of whether models can account for the overlap in class properties and understand which classes are most easily confused.
Accuracy:Percentage of total items classified correctly- (TP+TN)/(N+P) TP: True PositiveTN: True Negative N: Negative P: Positive
For unbalanced class distribution, I have provided weights to each class label, and CatBoost automatically handles it.
I have created a custom target label indicating customer’s responsiveness.
For binary classification, it would simply classify the customer based on the percentage of offers completed. If the offer completed percentage is >50 %, a customer belongs to a ‘responsive’ class. Otherwise, it belongs to the ‘unresponsive’ class.
Later, I extend the problem to multiclass classification. For this, I have created 3-class, 4-class, and 5-class labels by assigning the percentage of offers completed to a specific class and assigning an appropriate label to each class.
For 5-class problem, the label encoding looks like this:
encoding = {
‘responsive’: 4, ‘very_responsive’: 0, ‘moderately_responsive’: 3, ‘very_moderately_responsive’:2, ‘unresponsive’:1 }
1. Model Evaluation with fixed values of hyperparameters (Base Model)
I evaluate CatBoost Classifier with following fixed hyperparameters on all classification problems (class_2, class_3, class_4, class_5)
number of iterations = 2000
loss_function = [‘MultiClass’]
early_stopping_rounds = 50
eval_metric = ‘Accuracy’
and the rest of the parameter values as default provided by CatBoost Classifier.
2. Model Evaluation with hyperparameters found using GridSearch (Tuned Model)
In this round of experiments, I wrote a custom GridSearch function, which finds the best values for each given hyperparameter ranges and returns the model hyperparameters with the best average accuracy on training data.
For CatBoost Multiclassifier, there are numerous hyperparameters to tune. An extensive list can be found here:
I selected only the following hyperparameters with a specified range(found via some research on CatBoost website and Kaggle) to find the model with the best performance.
- iterations = [1000,3000]- loss_function = ['Logloss','MultiClass','MultiClassOneVsAll']- depth = [4,6,8] - early_stopping_rounds = [10, 20, 50]
I evaluate four multiclass classification models and document the results. It seems that training accuracy is a reliable indicator of the model performance rather than test accuracy.
This shows that the base model actually performed better than the model with parameters found via GridSearch. It could be due to the fact that range selection was not optimized. In future work, evaluating a model using RadomizedGridSearch could be interesting.
Providing too many parameters to GridSearch lead to a very slow search (more than 7 hours for one model), therefore I have reduced the parameter range, and then it took on average 20 minutes for searching the best parameters.
Initially, I faced some challenges about cleaning up transactions and identifying how to use transaction data for data modeling. The critical insight was to identify that the same timeline relates to different events. That allowed me to plot some great customer journey visualizations and subsequent custom feature creations.
Overall, I find it exciting to work on this project. I learned lots of stuff regarding data analysis and particularly, data visualization using Bokeh.
It took some initial trial and error to make a model using CatBoost work. Even though I haven’t changed much of the default parameters, the results were excellent. Part of the reason is due to the fact that I have included features like ‘the number of offers viewed’ in the training set, which is an excellent indicator of the offer completion rate, and based on it, I have encoded target classes.
Future refinement
I suggest trying out custom categorical features to train a model.
Also, removing some custom features from the dataset and evaluating the model would be interesting.
Concerning feature engineering, there could be features developed regarding how much the customer has spent before viewing offers.
Many thanks for reading the article. If you are interested in more detail about the project, please have a look at the project repository here.
|
[
{
"code": null,
"e": 455,
"s": 172,
"text": "In this post, I explore the customer data provided by Starbucks in collaboration with Udacity to understand customer behaviors in light of potential rewards. The Starbucks mobile app sends out different kinds of incentive offers to its customers to keep them engaged with the brand."
},
{
"code": null,
"e": 612,
"s": 455,
"text": "The motivation of this post is to discuss a solution approach taken to analyze the data and machine learning solution that predicts customer responsiveness."
},
{
"code": null,
"e": 743,
"s": 612,
"text": "I have used a machine learning library CatBoost for a multiclass classification problem and Bokeh as a primary visualization tool."
},
{
"code": null,
"e": 793,
"s": 743,
"text": "The GitHub Repo of the project can be found here."
},
{
"code": null,
"e": 1161,
"s": 793,
"text": "This data set contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer, such as a discount or BOGO (buy one get one free). Some users might not receive any offers during certain weeks."
},
{
"code": null,
"e": 1615,
"s": 1161,
"text": "Every offer has a validity period before the offer expires. As an example, a BOGO offer might be valid for only five days. You’ll see in the data set that informational offers have a validity period even though these ads are merely providing information about a product; for example, if an informational offer has seven days of validity, you can assume the customer is feeling the influence of the offer for seven days after receiving the advertisement."
},
{
"code": null,
"e": 1710,
"s": 1615,
"text": "[Project Overview is taken from Udacity’s Capstone Project for DataScience NanoDegree Program]"
},
{
"code": null,
"e": 1720,
"s": 1710,
"text": "Data Sets"
},
{
"code": null,
"e": 1758,
"s": 1720,
"text": "The data is contained in three files:"
},
{
"code": null,
"e": 1843,
"s": 1758,
"text": "portfolio.json — containing offer ids and metadata about each offer (duration, type)"
},
{
"code": null,
"e": 1893,
"s": 1843,
"text": "profile.json — demographic data for each customer"
},
{
"code": null,
"e": 1989,
"s": 1893,
"text": "transcript.json — records for transactions, offers received, offers viewed, and offers complete"
},
{
"code": null,
"e": 2197,
"s": 1989,
"text": "The aim is to analyze individual customer behaviors to identify unusual patterns. The finding of such an analysis should help Starbucks business to re-evaluate its rewards program based on specific outcomes."
},
{
"code": null,
"e": 2267,
"s": 2197,
"text": "I aim to provide analysis targeting the following business questions:"
},
{
"code": null,
"e": 2324,
"s": 2267,
"text": "Can we classify customers based on their responsiveness?"
},
{
"code": null,
"e": 2404,
"s": 2324,
"text": "Can we identify high paying customers who don’t care about the rewards program?"
},
{
"code": null,
"e": 2477,
"s": 2404,
"text": "Can we identify customers who haven’t made any transactions in the past?"
},
{
"code": null,
"e": 2583,
"s": 2477,
"text": "Can we visualize customers’ interaction with offers and spending activities to gain interesting insights?"
},
{
"code": null,
"e": 2895,
"s": 2583,
"text": "There are three different datasets, which I explore one by one and identify any issues like missing information, extra/redundant information, other inconsistencies. I accomplish this by making good use of visualization as necessary. At the end of this step, I have a clean dataset ready for further exploration."
},
{
"code": null,
"e": 3109,
"s": 2895,
"text": "I combine all the three datasets into one single set and perform further analysis through advanced visualization. Based on this, I frame a classification problem to tackle through some machine learning algorithms."
},
{
"code": null,
"e": 3706,
"s": 3109,
"text": "I have chosen a CatBoost algorithm, a multiclass classification algorithm. It identifies the relations between highly co-related features automatically and comes with built-in visualizations. It is straightforward to train and evaluate the model using it. The final results are usually better with default parameters because CatBoots uses horizontal decision trees internally. Since we are dealing with classification and the error of misclassification doesn’t result in any adverse effects, in this case, model accuracy should be our standard evaluation criteria, including the confusion matrix."
},
{
"code": null,
"e": 3811,
"s": 3706,
"text": "In the end, I evaluate the results of the overall analysis, including machine learning model evaluation."
},
{
"code": null,
"e": 3959,
"s": 3811,
"text": "By looking at the ‘channels’ columns, it makes sense to disaggregate each channel values into separate columns and encode it using 0|1 identifiers."
},
{
"code": null,
"e": 4084,
"s": 3959,
"text": "Let’s create dummies for the ‘offer_type’ column and encode it and also drop the original column as we no longer require it."
},
{
"code": null,
"e": 4268,
"s": 4084,
"text": "Here each offer is always sent via the ‘email’ channel. Therefore this feature is only informative and may not add any value to the predictive power of any machine learning algorithm."
},
{
"code": null,
"e": 4434,
"s": 4268,
"text": "It is obvious that ‘age’ value 118 is a placeholder for the missing value.Further analysis reveals 2175 missing entries for gender, age, and income columns together."
},
{
"code": null,
"e": 4600,
"s": 4434,
"text": "‘became_member_on’ column is a timestamped date, let’s transform it into a more readable format and also extract the number of days since the customer has signed up."
},
{
"code": null,
"e": 4665,
"s": 4600,
"text": "Let’s create some visualizations to analyze the demographic data"
},
{
"code": null,
"e": 4871,
"s": 4665,
"text": "The left chart shows that there is a steady increase in the number of customers over the years. However, there is a steep fall at the end of 2017. This could also be due to sampling to prepare the dataset."
},
{
"code": null,
"e": 5023,
"s": 4871,
"text": "Surprisingly, there are many customers who fall into relatively lower-income groups and very few customers who fall into relatively high-income groups."
},
{
"code": null,
"e": 5152,
"s": 5023,
"text": "The pair chart shows that there are not many female customers, and the female group is relatively older and has a higher income."
},
{
"code": null,
"e": 5174,
"s": 5152,
"text": "Specific Observations"
},
{
"code": null,
"e": 5259,
"s": 5174,
"text": "There exist no customers in the age group [20, 30] having an income higher than 80K."
},
{
"code": null,
"e": 5345,
"s": 5259,
"text": "There exists no customer in the age group [40, 50] having an income higher than 100K."
},
{
"code": null,
"e": 5433,
"s": 5345,
"text": "All the customer who became a member more than 2000 days ago has income less than 100K."
},
{
"code": null,
"e": 5682,
"s": 5433,
"text": "The quick look at the transcript dataset reveals that the ‘value’ column is encoded as a dictionary. If the event is related to offers, then the ‘value’ column encode offer id, and in case of transaction event, it encodes the amount of transaction."
},
{
"code": null,
"e": 5844,
"s": 5682,
"text": "Therefore, it makes sense to decode the ‘value’ column into separate columns to understand the relationship between offers and the amount spent by the customers."
},
{
"code": null,
"e": 6198,
"s": 5844,
"text": "First of all, we should calculate the total number of offers completed and the total number of offers viewed by each customer.The data includes ‘offers completed’ by customers, knowingly or unknowingly. The customers who have unknowingly completed offers should not be sent out further offers. This group represents profitable customers for the company."
},
{
"code": null,
"e": 6293,
"s": 6198,
"text": "We combine our transcript dataset with the customer demographics (profile) and portfolio data."
},
{
"code": null,
"e": 6357,
"s": 6293,
"text": "After several preprocessing steps applied to the joint dataset,"
},
{
"code": null,
"e": 6516,
"s": 6357,
"text": "The above chart displays the number of offers viewed against timestamp in hours. There are six peaks where the number of viewed offers increases dramatically."
},
{
"code": null,
"e": 6810,
"s": 6516,
"text": "I have embedded the number of offers received (correct received offer count is four times the marked one) in the chart. When new offers get received, the count of viewed offer increases and then slowly decreases over time. Generally speaking, most offers are viewed within 24 hours of receipt."
},
{
"code": null,
"e": 7033,
"s": 6810,
"text": "The above chart shows the number of completed offers against a timestamp in hours. It follows a similar pattern as the graph before because new offers are sent six times in 24 day period, and hence the chart has six peaks."
},
{
"code": null,
"e": 7231,
"s": 7033,
"text": "Between each peak, the chart decreases gradually, just like viewed offers chart. However, the decrease is not as smooth as for the viewed offer chart. There are some local picks during the decline."
},
{
"code": null,
"e": 7510,
"s": 7231,
"text": "The above chart combines a number of transactions and offers completed together. There is a local peak between each ‘offer sent out interval’ for transactions. This implies that when offers are received, customers quickly perform some transactions resulting in offer completion."
},
{
"code": null,
"e": 7859,
"s": 7510,
"text": "At time stamp 0, there exist around 600 transactions. Around 200 of them contribute to ‘offer completion’ (number of offers completed at timestamp 0), which is roughly a 25% conversion rate. This figure is roughly in agreement with the ratio of the total number of completed offers to the total number of transactions => 138953/33579)*100 = 24.16%."
},
{
"code": null,
"e": 8111,
"s": 7859,
"text": "There exist some high-value transactions (above 100 USD). It could be a large order from individuals for special events or from corporate clients. Such a high-value transaction leads to all of the current offers associated with a customer to complete."
},
{
"code": null,
"e": 8432,
"s": 8111,
"text": "In reality, these transactions were not motivated to complete the offers, and therefore it should be considered side effects. Sending out offers to such high paying customers would not lead to an increase or decrease in their purchasing behavior. Therefore we should remove such high-value transactions from the dataset."
},
{
"code": null,
"e": 8584,
"s": 8432,
"text": "Next, we should also find out and remove non-responsive customers. I define non-responsive customer = no received offered viewed + no transaction made."
},
{
"code": null,
"e": 8780,
"s": 8584,
"text": "After some further preprocessing steps, I found 422 customers having made no transaction. Out of them, 412 has received and viewed offers while 10 of them have received and not viewed any offers."
},
{
"code": null,
"e": 8868,
"s": 8780,
"text": "Similarly, analyzing the transaction amount, the following observations were collected:"
},
{
"code": null,
"e": 8908,
"s": 8868,
"text": "There are some transactions > 1000 USD."
},
{
"code": null,
"e": 8992,
"s": 8908,
"text": "There are many more transactions in the range [0.05,50] than the rest of the range."
},
{
"code": null,
"e": 9125,
"s": 8992,
"text": "Any transaction greater than 50 USD can be treated as a high-value transaction and not necessarily motivated to complete the offers."
},
{
"code": null,
"e": 9280,
"s": 9125,
"text": "In this section, we look at the customer’s interaction with offers through some advanced visualizations. Based on that, I define some calculated features."
},
{
"code": null,
"e": 9479,
"s": 9280,
"text": "Here in the above chart, we have a customer who has completed all the offers sent out to him/her. It usually takes more than one transaction to complete an offer if those transactions are low value."
},
{
"code": null,
"e": 9579,
"s": 9479,
"text": "Sometimes, the customer views the offer instantly while sometimes, he/she views it at a later time."
},
{
"code": null,
"e": 9661,
"s": 9579,
"text": "Out of 4 offers completed, only 1 (last completed) is not viewed by the customer."
},
{
"code": null,
"e": 9756,
"s": 9661,
"text": "Here we have two high paying customers side by side who has completed all the received offers."
},
{
"code": null,
"e": 10080,
"s": 9756,
"text": "Interestingly, for customer ‘9fa’ after completing the first offer, he/she has made five transactions amounting in total around 75 USD without any pending offer to complete. It demonstrates that those transactions were not motivated to complete the offer and show customers spending tendencies in the absence of any offers."
},
{
"code": null,
"e": 10402,
"s": 10080,
"text": "Based on the above analysis I derive the following custom features1. Percentage of Offers completed by a given customer2. Absolute count of Offers completed by a given customer3. Percentage of Offers viewed by a given customer4. Absolute count of Offers viewed by a given customer5. Total amount spent by a given customer"
},
{
"code": null,
"e": 10418,
"s": 10402,
"text": "Considerations:"
},
{
"code": null,
"e": 11177,
"s": 10418,
"text": "Our problem falls into the category of multi-class classification. The multi-class classification problem can be summarised as below:Given a dataset with instances xi together with N classes where every instance xi belongs precisely to one class yi is a problem targeted for a multiclass classifier.After the training and testing, we have a table with the correct class yi and the predicted class ai for every instance xi in the test set. So for every instance, we have either a match (yi=ai) or a miss (yi≠ai).Assuming we have balanced class distribution in our training set, evaluation using a confusion matrix together with the average accuracy score should be sufficient. However, F1-score can also be used for the evaluation of the multi-class problem."
},
{
"code": null,
"e": 11352,
"s": 11177,
"text": "Since the cost of misclassification is not high in our case (sending an offer to the non-responsive customer doesn’t cost the company extra money), F1-score is not necessary."
},
{
"code": null,
"e": 11825,
"s": 11352,
"text": "In this project, I prefer to use the confusion matrix and the average score as our evaluation measures.Confusion Matrix:A confusion matrix shows the combination of the actual and predicted classes. Each row of the matrix represents the instances in a predicted class, while each column represents the instances in an actual class. It is a good measure of whether models can account for the overlap in class properties and understand which classes are most easily confused."
},
{
"code": null,
"e": 11955,
"s": 11825,
"text": "Accuracy:Percentage of total items classified correctly- (TP+TN)/(N+P) TP: True PositiveTN: True Negative N: Negative P: Positive"
},
{
"code": null,
"e": 12074,
"s": 11955,
"text": "For unbalanced class distribution, I have provided weights to each class label, and CatBoost automatically handles it."
},
{
"code": null,
"e": 12149,
"s": 12074,
"text": "I have created a custom target label indicating customer’s responsiveness."
},
{
"code": null,
"e": 12398,
"s": 12149,
"text": "For binary classification, it would simply classify the customer based on the percentage of offers completed. If the offer completed percentage is >50 %, a customer belongs to a ‘responsive’ class. Otherwise, it belongs to the ‘unresponsive’ class."
},
{
"code": null,
"e": 12636,
"s": 12398,
"text": "Later, I extend the problem to multiclass classification. For this, I have created 3-class, 4-class, and 5-class labels by assigning the percentage of offers completed to a specific class and assigning an appropriate label to each class."
},
{
"code": null,
"e": 12693,
"s": 12636,
"text": "For 5-class problem, the label encoding looks like this:"
},
{
"code": null,
"e": 12706,
"s": 12693,
"text": "encoding = {"
},
{
"code": null,
"e": 12824,
"s": 12706,
"text": "‘responsive’: 4, ‘very_responsive’: 0, ‘moderately_responsive’: 3, ‘very_moderately_responsive’:2, ‘unresponsive’:1 }"
},
{
"code": null,
"e": 12894,
"s": 12824,
"text": "1. Model Evaluation with fixed values of hyperparameters (Base Model)"
},
{
"code": null,
"e": 13030,
"s": 12894,
"text": "I evaluate CatBoost Classifier with following fixed hyperparameters on all classification problems (class_2, class_3, class_4, class_5)"
},
{
"code": null,
"e": 13058,
"s": 13030,
"text": "number of iterations = 2000"
},
{
"code": null,
"e": 13089,
"s": 13058,
"text": "loss_function = [‘MultiClass’]"
},
{
"code": null,
"e": 13116,
"s": 13089,
"text": "early_stopping_rounds = 50"
},
{
"code": null,
"e": 13141,
"s": 13116,
"text": "eval_metric = ‘Accuracy’"
},
{
"code": null,
"e": 13222,
"s": 13141,
"text": "and the rest of the parameter values as default provided by CatBoost Classifier."
},
{
"code": null,
"e": 13300,
"s": 13222,
"text": "2. Model Evaluation with hyperparameters found using GridSearch (Tuned Model)"
},
{
"code": null,
"e": 13520,
"s": 13300,
"text": "In this round of experiments, I wrote a custom GridSearch function, which finds the best values for each given hyperparameter ranges and returns the model hyperparameters with the best average accuracy on training data."
},
{
"code": null,
"e": 13631,
"s": 13520,
"text": "For CatBoost Multiclassifier, there are numerous hyperparameters to tune. An extensive list can be found here:"
},
{
"code": null,
"e": 13801,
"s": 13631,
"text": "I selected only the following hyperparameters with a specified range(found via some research on CatBoost website and Kaggle) to find the model with the best performance."
},
{
"code": null,
"e": 13953,
"s": 13801,
"text": "- iterations = [1000,3000]- loss_function = ['Logloss','MultiClass','MultiClassOneVsAll']- depth = [4,6,8] - early_stopping_rounds = [10, 20, 50]"
},
{
"code": null,
"e": 14136,
"s": 13953,
"text": "I evaluate four multiclass classification models and document the results. It seems that training accuracy is a reliable indicator of the model performance rather than test accuracy."
},
{
"code": null,
"e": 14397,
"s": 14136,
"text": "This shows that the base model actually performed better than the model with parameters found via GridSearch. It could be due to the fact that range selection was not optimized. In future work, evaluating a model using RadomizedGridSearch could be interesting."
},
{
"code": null,
"e": 14623,
"s": 14397,
"text": "Providing too many parameters to GridSearch lead to a very slow search (more than 7 hours for one model), therefore I have reduced the parameter range, and then it took on average 20 minutes for searching the best parameters."
},
{
"code": null,
"e": 14949,
"s": 14623,
"text": "Initially, I faced some challenges about cleaning up transactions and identifying how to use transaction data for data modeling. The critical insight was to identify that the same timeline relates to different events. That allowed me to plot some great customer journey visualizations and subsequent custom feature creations."
},
{
"code": null,
"e": 15100,
"s": 14949,
"text": "Overall, I find it exciting to work on this project. I learned lots of stuff regarding data analysis and particularly, data visualization using Bokeh."
},
{
"code": null,
"e": 15498,
"s": 15100,
"text": "It took some initial trial and error to make a model using CatBoost work. Even though I haven’t changed much of the default parameters, the results were excellent. Part of the reason is due to the fact that I have included features like ‘the number of offers viewed’ in the training set, which is an excellent indicator of the offer completion rate, and based on it, I have encoded target classes."
},
{
"code": null,
"e": 15516,
"s": 15498,
"text": "Future refinement"
},
{
"code": null,
"e": 15583,
"s": 15516,
"text": "I suggest trying out custom categorical features to train a model."
},
{
"code": null,
"e": 15683,
"s": 15583,
"text": "Also, removing some custom features from the dataset and evaluating the model would be interesting."
},
{
"code": null,
"e": 15814,
"s": 15683,
"text": "Concerning feature engineering, there could be features developed regarding how much the customer has spent before viewing offers."
}
] |
Difference between Opening and Closing in Digital Image Processing - GeeksforGeeks
|
16 Jan, 2020
Opening and Closing are dual operations used in Digital Image Processing for restoring an eroded image. Opening is generally used to restore or recover the original image to the maximum possible extent. Closing is generally used to smoother the contour of the distorted image and fuse back the narrow breaks and long thin gulfs. Closing is also used for getting rid of the small holes of the obtained image.
The combination of Opening and Closing is generally used to clean up artifacts in the segmented image before using the image for digital analysis.
Some of the differences between Opening and Closing are:
Properties of Opening are:
1. XoY is a subset (subimage of X)
2. If X is a subset of Z then XoY is a subset of ZoY
3.(XoY)oY = XoY
Properties of Closing are:
1. X is a subset subimage of X.Y
2. (X.Y).Y = X.Y
Image-Processing
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Process and Thread
Stack vs Heap Memory Allocation
Difference Between Spark DataFrame and Pandas DataFrame
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Clustered and Non-clustered index
Differences between JDK, JRE and JVM
Differences between Procedural and Object Oriented Programming
Difference between Primary Key and Foreign Key
Differences between IPv4 and IPv6
|
[
{
"code": null,
"e": 24912,
"s": 24884,
"text": "\n16 Jan, 2020"
},
{
"code": null,
"e": 25320,
"s": 24912,
"text": "Opening and Closing are dual operations used in Digital Image Processing for restoring an eroded image. Opening is generally used to restore or recover the original image to the maximum possible extent. Closing is generally used to smoother the contour of the distorted image and fuse back the narrow breaks and long thin gulfs. Closing is also used for getting rid of the small holes of the obtained image."
},
{
"code": null,
"e": 25467,
"s": 25320,
"text": "The combination of Opening and Closing is generally used to clean up artifacts in the segmented image before using the image for digital analysis."
},
{
"code": null,
"e": 25524,
"s": 25467,
"text": "Some of the differences between Opening and Closing are:"
},
{
"code": null,
"e": 25669,
"s": 25524,
"text": "Properties of Opening are:\n 1. XoY is a subset (subimage of X)\n 2. If X is a subset of Z then XoY is a subset of ZoY\n 3.(XoY)oY = XoY\n"
},
{
"code": null,
"e": 25755,
"s": 25669,
"text": "Properties of Closing are:\n 1. X is a subset subimage of X.Y\n 2. (X.Y).Y = X.Y\n"
},
{
"code": null,
"e": 25772,
"s": 25755,
"text": "Image-Processing"
},
{
"code": null,
"e": 25791,
"s": 25772,
"text": "Difference Between"
},
{
"code": null,
"e": 25889,
"s": 25791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25898,
"s": 25889,
"text": "Comments"
},
{
"code": null,
"e": 25911,
"s": 25898,
"text": "Old Comments"
},
{
"code": null,
"e": 25949,
"s": 25911,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 25981,
"s": 25949,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 26037,
"s": 25981,
"text": "Difference Between Spark DataFrame and Pandas DataFrame"
},
{
"code": null,
"e": 26098,
"s": 26037,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26166,
"s": 26098,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 26219,
"s": 26166,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 26256,
"s": 26219,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 26319,
"s": 26256,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 26366,
"s": 26319,
"text": "Difference between Primary Key and Foreign Key"
}
] |
Clustering Based Unsupervised Learning | by Syed Sadat Nazrul | Towards Data Science
|
Unsupervised machine learning is the machine learning task of inferring a function to describe hidden structure from “unlabeled” data (a classification or categorization is not included in the observations). Common scenarios for using unsupervised learning algorithms include:- Data Exploration- Outlier Detection- Pattern Recognition
While there is an exhaustive list of clustering algorithms available (whether you use R or Python’s Scikit-Learn), I will attempt to cover the basic concepts.
The most common and simplest clustering algorithm out there is the K-Means clustering. This algorithms involve you telling the algorithms how many possible cluster (or K) there are in the dataset. The algorithm then iteratively moves the k-centers and selects the datapoints that are closest to that centroid in the cluster.
Taking K=3 as an example, the iterative process is given below:
One obvious question that may come to mind is the methodology for picking the K value. This is done using an elbow curve, where the x-axis is the K-value and the y axis is some objective function. A common objective function is the average distance between the datapoints and the nearest centroid.
The best number for K is the “elbow” or kinked region. After this point, it is generally established that adding more clusters will not add significant value to your analysis. Below is an example script for K-Means using Scikit-Learn on the iris dataset:
from sklearn.cluster import KMeansimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np%matplotlib inlinefrom sklearn import datasets#Iris Datasetiris = datasets.load_iris()X = iris.data#KMeanskm = KMeans(n_clusters=3)km.fit(X)km.predict(X)labels = km.labels_#Plottingfig = plt.figure(1, figsize=(7,7))ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=48, azim=134)ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float), edgecolor="k", s=50)ax.set_xlabel("Petal width")ax.set_ylabel("Sepal length")ax.set_zlabel("Petal length")plt.title("K Means", fontsize=14)
One issue with K-means, as see in the 3D diagram above, is that it does hard labels. However, you can see that datapoints at the boundary of the purple and yellow clusters can be either one. For such circumstances, a different approach may be necessary.
In K-Means, we do what is called “hard labeling”, where we simply add the label of the maximum probability. However, certain data points that exist at the boundary of clusters may simply have similar probabilities of being on either clusters. In such circumstances, we look at all the probabilities instead of the max probability. This is known as “soft labeling”.
from sklearn.mixture import GaussianMixtureimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np%matplotlib inlinefrom sklearn import datasets#Iris Datasetiris = datasets.load_iris()X = iris.data#Gaussian Mixture Modelgmm = GaussianMixture(n_components=3)gmm.fit(X)proba_lists = gmm.predict_proba(X)#Plottingcolored_arrays = np.matrix(proba_lists)colored_tuples = [tuple(i.tolist()[0]) for i in colored_arrays]fig = plt.figure(1, figsize=(7,7))ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=48, azim=134)ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=colored_tuples, edgecolor="k", s=50)ax.set_xlabel("Petal width")ax.set_ylabel("Sepal length")ax.set_zlabel("Petal length")plt.title("Gaussian Mixture Model", fontsize=14)
For the above Gaussian Mixure Model, the colors of the datapoints are based on the Gaussian probability of being near the cluster. The RGB values are based on the nearness to each of the red, blue and green clusters. If you look at the datapoints near the boundary of the blue and red cluster, you shall see purple, indicating the datapoints are close to either clusters.
Since we have talked about numerical values, let’s take a turn towards categorical values. One such application is text analytics. Common approach for such problems is topic modelling, where documents or words in a document are categorized into topics. The simplest of these is the TF-IDF model. The TF-IDF model classifies words based on their importance. This is determined by how frequent are they in specific documents (e.g. specific science topics in scientific journals) and words that are common among all documents (e.g. stop words).
One of my favorite algorithms is the Latent Dirichlet Allocation or LDA model. In this model, each word in the document is given a topic based on the entire document corpus. Below, I have attached a slide from the University of Washington’s Machine Learning specialization course:
The mechanics behind the LDA model itself is hard to explain in this blog. However, a common question people have is deciding on the number of topics. While there is no established answer for this, personally I prefer to implement a elbow curve of K-Means of the word vector of each document. The closeness of each word vector can be determined by the cosine distance.
Finally, let’s cover some timeseries analysis. For clustering, my favourite is using Hidden Markov Models or HMM. In a Markov Model, we look for states and the probability of the next state given the current state. An example below is of a dog’s life in Markov Model.
Let’s assume the dog is sick. Given the current state, there is a 0.6 chance it will continue being sick the next hour, 0.4 that it is sleeping, 05 pooping, 0.1 eating and 0.4 that it will be healthy again. In an HMM, you provide how many states there may be inside the timeseries data for the model to compute. An example of the Boston house prices dataset is given below with 3 states.
from hmmlearn import hmmimport numpy as np%matplotlib inlinefrom sklearn import datasets#Databoston = datasets.load_boston()ts_data = boston.data[1,:]#HMM Modelgm = hmm.GaussianHMM(n_components=3)gm.fit(ts_data.reshape(-1, 1))states = gm.predict(ts_data.reshape(-1, 1))#Plotcolor_dict = {0:"r",1:"g",2:"b"}color_array = [color_dict[i] for i in states]plt.scatter(range(len(ts_data)), ts_data, c=color_array)plt.title("HMM Model")
As with every clustering problem, deciding the number of states is also a common issue. This may either be domain based. e.g. in voice recognition, it is common practice to use 3 states. Another possibility is using an elbow curve.
As I have mentioned at the beginning of this blog, it is not possible for me to cover every single unsupervised models out there. At the same time, based on your use case, you may need a combination of algorithms to get a different perspective of the same data. With that I would like to leave you off with Scikit-Learn’s famous clustering demonstrations on the toy dataset:
|
[
{
"code": null,
"e": 506,
"s": 171,
"text": "Unsupervised machine learning is the machine learning task of inferring a function to describe hidden structure from “unlabeled” data (a classification or categorization is not included in the observations). Common scenarios for using unsupervised learning algorithms include:- Data Exploration- Outlier Detection- Pattern Recognition"
},
{
"code": null,
"e": 665,
"s": 506,
"text": "While there is an exhaustive list of clustering algorithms available (whether you use R or Python’s Scikit-Learn), I will attempt to cover the basic concepts."
},
{
"code": null,
"e": 990,
"s": 665,
"text": "The most common and simplest clustering algorithm out there is the K-Means clustering. This algorithms involve you telling the algorithms how many possible cluster (or K) there are in the dataset. The algorithm then iteratively moves the k-centers and selects the datapoints that are closest to that centroid in the cluster."
},
{
"code": null,
"e": 1054,
"s": 990,
"text": "Taking K=3 as an example, the iterative process is given below:"
},
{
"code": null,
"e": 1352,
"s": 1054,
"text": "One obvious question that may come to mind is the methodology for picking the K value. This is done using an elbow curve, where the x-axis is the K-value and the y axis is some objective function. A common objective function is the average distance between the datapoints and the nearest centroid."
},
{
"code": null,
"e": 1607,
"s": 1352,
"text": "The best number for K is the “elbow” or kinked region. After this point, it is generally established that adding more clusters will not add significant value to your analysis. Below is an example script for K-Means using Scikit-Learn on the iris dataset:"
},
{
"code": null,
"e": 2215,
"s": 1607,
"text": "from sklearn.cluster import KMeansimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np%matplotlib inlinefrom sklearn import datasets#Iris Datasetiris = datasets.load_iris()X = iris.data#KMeanskm = KMeans(n_clusters=3)km.fit(X)km.predict(X)labels = km.labels_#Plottingfig = plt.figure(1, figsize=(7,7))ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=48, azim=134)ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float), edgecolor=\"k\", s=50)ax.set_xlabel(\"Petal width\")ax.set_ylabel(\"Sepal length\")ax.set_zlabel(\"Petal length\")plt.title(\"K Means\", fontsize=14)"
},
{
"code": null,
"e": 2469,
"s": 2215,
"text": "One issue with K-means, as see in the 3D diagram above, is that it does hard labels. However, you can see that datapoints at the boundary of the purple and yellow clusters can be either one. For such circumstances, a different approach may be necessary."
},
{
"code": null,
"e": 2834,
"s": 2469,
"text": "In K-Means, we do what is called “hard labeling”, where we simply add the label of the maximum probability. However, certain data points that exist at the boundary of clusters may simply have similar probabilities of being on either clusters. In such circumstances, we look at all the probabilities instead of the max probability. This is known as “soft labeling”."
},
{
"code": null,
"e": 3590,
"s": 2834,
"text": "from sklearn.mixture import GaussianMixtureimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np%matplotlib inlinefrom sklearn import datasets#Iris Datasetiris = datasets.load_iris()X = iris.data#Gaussian Mixture Modelgmm = GaussianMixture(n_components=3)gmm.fit(X)proba_lists = gmm.predict_proba(X)#Plottingcolored_arrays = np.matrix(proba_lists)colored_tuples = [tuple(i.tolist()[0]) for i in colored_arrays]fig = plt.figure(1, figsize=(7,7))ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=48, azim=134)ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=colored_tuples, edgecolor=\"k\", s=50)ax.set_xlabel(\"Petal width\")ax.set_ylabel(\"Sepal length\")ax.set_zlabel(\"Petal length\")plt.title(\"Gaussian Mixture Model\", fontsize=14)"
},
{
"code": null,
"e": 3962,
"s": 3590,
"text": "For the above Gaussian Mixure Model, the colors of the datapoints are based on the Gaussian probability of being near the cluster. The RGB values are based on the nearness to each of the red, blue and green clusters. If you look at the datapoints near the boundary of the blue and red cluster, you shall see purple, indicating the datapoints are close to either clusters."
},
{
"code": null,
"e": 4504,
"s": 3962,
"text": "Since we have talked about numerical values, let’s take a turn towards categorical values. One such application is text analytics. Common approach for such problems is topic modelling, where documents or words in a document are categorized into topics. The simplest of these is the TF-IDF model. The TF-IDF model classifies words based on their importance. This is determined by how frequent are they in specific documents (e.g. specific science topics in scientific journals) and words that are common among all documents (e.g. stop words)."
},
{
"code": null,
"e": 4785,
"s": 4504,
"text": "One of my favorite algorithms is the Latent Dirichlet Allocation or LDA model. In this model, each word in the document is given a topic based on the entire document corpus. Below, I have attached a slide from the University of Washington’s Machine Learning specialization course:"
},
{
"code": null,
"e": 5154,
"s": 4785,
"text": "The mechanics behind the LDA model itself is hard to explain in this blog. However, a common question people have is deciding on the number of topics. While there is no established answer for this, personally I prefer to implement a elbow curve of K-Means of the word vector of each document. The closeness of each word vector can be determined by the cosine distance."
},
{
"code": null,
"e": 5422,
"s": 5154,
"text": "Finally, let’s cover some timeseries analysis. For clustering, my favourite is using Hidden Markov Models or HMM. In a Markov Model, we look for states and the probability of the next state given the current state. An example below is of a dog’s life in Markov Model."
},
{
"code": null,
"e": 5810,
"s": 5422,
"text": "Let’s assume the dog is sick. Given the current state, there is a 0.6 chance it will continue being sick the next hour, 0.4 that it is sleeping, 05 pooping, 0.1 eating and 0.4 that it will be healthy again. In an HMM, you provide how many states there may be inside the timeseries data for the model to compute. An example of the Boston house prices dataset is given below with 3 states."
},
{
"code": null,
"e": 6240,
"s": 5810,
"text": "from hmmlearn import hmmimport numpy as np%matplotlib inlinefrom sklearn import datasets#Databoston = datasets.load_boston()ts_data = boston.data[1,:]#HMM Modelgm = hmm.GaussianHMM(n_components=3)gm.fit(ts_data.reshape(-1, 1))states = gm.predict(ts_data.reshape(-1, 1))#Plotcolor_dict = {0:\"r\",1:\"g\",2:\"b\"}color_array = [color_dict[i] for i in states]plt.scatter(range(len(ts_data)), ts_data, c=color_array)plt.title(\"HMM Model\")"
},
{
"code": null,
"e": 6472,
"s": 6240,
"text": "As with every clustering problem, deciding the number of states is also a common issue. This may either be domain based. e.g. in voice recognition, it is common practice to use 3 states. Another possibility is using an elbow curve."
}
] |
Ext.js - Custom Events and listeners
|
Events are something which get fired when something happens to the class. For example when a button is getting clicked or before/ after element is rendered.
Methods of writing events:
Built in events using listeners
Attaching events later
Custom events
Built in events using listeners
Attaching events later
Custom events
Ext JS provides listener property for writing events and custom events in Ext JS files.
We will add the listener in the previous program itself by adding listen property to the panel as below:
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel = 'stylesheet' type ='text/css' href= 'extjs-4.1.1/resources/css/ext-all.css' />
<script type ='text/javascript' src = 'extjs-4.1.1/ext-all-debug.js'></script>
<script type ='text/javascript' src = 'app.js'></script>
</head>
<body>
<h1> Please click the button to see event listener </h1>
<div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >
</body>
</html>
app.js
A button is created using Ext.button class. On click event is written in listener.
On click of this button an alert will appear with text "Button is clicked"".
Ext.onReady(function(){
Ext.create('Ext.Button', {
renderTo: Ext.getElementById('helloWorldPanel'),
text: 'My Button',
listeners: {
click: function() {
this.message();
},
message: function() {
Ext.MessageBox.alert('Alert box', 'Button is clicked');
}
}
});
});
Output:
Before clicking button
After clicking button
This way we can write multiple events also in listeners property.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel = 'stylesheet' type ='text/css' href= 'extjs-4.1.1/resources/css/ext-all.css' />
<script type ='text/javascript' src = 'extjs-4.1.1/ext-all-debug.js'></script>
<script type ='text/javascript' src = 'app.js'></script>
</head>
<body>
<h1> Please click the button to see event listener </h1>
<div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >
</body>
</html>
app.js
Ext.onReady(function(){
Ext.create('Ext.Button', {
renderTo: Ext.getElementById('helloWorldPanel'),
text: 'My Button',
listeners: {
click: function() {
this.hide();
},
hide: function() {
Ext.MessageBox.alert('Alert box', 'Button is clicked');
},
mouseover: function() {
Ext.MessageBox.alert('Alert box', 'Mouse over event is called');
}
}
});
});
Output:
Before clicking button
After clicking button
On mouse over
In the previous method of writing events we have written events in listeners at the time of creating elements.
Other way is to attach events in the as:
app.js
Ext.onReady(function(){
var button = Ext.create('Ext.Button', {
renderTo: Ext.getElementById('helloWorldPanel'),
text: 'My Button',
});
// This way we can attach event to the button after the button is created.
button.on('click', function() {
Ext.MessageBox.alert('Alert box', Button is clicked');
});
});
Before clicking button
After clicking button
The events which we have used above are the events which are inbuild in Ext JS. We can write custom events as:
app.js
Ext.onReady(function(){
var button = Ext.create('Ext.Button', {
renderTo: Ext.getElementById('helloWorldPanel'),
text: 'My Button',
listeners: {
myEvent: function(button) {
Ext.MessageBox.alert('Alert box', 'My custom event is called');
}
}
});
Ext.defer(function() {
button.fireEvent('myEvent');
}, 5000);
});
Output:
Once the page is loaded and document is ready the UI page with button will appear and as we are firing an event after 5 sec the document is ready the alert box will appear after 5 seconds.
Here we have written the custom event 'myEvent' and we are firing events as button.fireEvent(eventName);
These are the three ways of writing events in Ext JS.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2181,
"s": 2023,
"text": "Events are something which get fired when something happens to the class. For example when a button is getting clicked or before/ after element is rendered.\n"
},
{
"code": null,
"e": 2208,
"s": 2181,
"text": "Methods of writing events:"
},
{
"code": null,
"e": 2281,
"s": 2210,
"text": "\nBuilt in events using listeners\nAttaching events later\nCustom events\n"
},
{
"code": null,
"e": 2313,
"s": 2281,
"text": "Built in events using listeners"
},
{
"code": null,
"e": 2336,
"s": 2313,
"text": "Attaching events later"
},
{
"code": null,
"e": 2350,
"s": 2336,
"text": "Custom events"
},
{
"code": null,
"e": 2438,
"s": 2350,
"text": "Ext JS provides listener property for writing events and custom events in Ext JS files."
},
{
"code": null,
"e": 2543,
"s": 2438,
"text": "We will add the listener in the previous program itself by adding listen property to the panel as below:"
},
{
"code": null,
"e": 2554,
"s": 2543,
"text": "Index.html"
},
{
"code": null,
"e": 3046,
"s": 2554,
"text": "<!DOCTYPE html>\n <html>\n <head>\n <link rel = 'stylesheet' type ='text/css' href= 'extjs-4.1.1/resources/css/ext-all.css' />\n <script type ='text/javascript' src = 'extjs-4.1.1/ext-all-debug.js'></script>\n <script type ='text/javascript' src = 'app.js'></script> \n </head>\n <body>\n <h1> Please click the button to see event listener </h1>\n <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >\n </body>\n </html>"
},
{
"code": null,
"e": 3053,
"s": 3046,
"text": "app.js"
},
{
"code": null,
"e": 3137,
"s": 3053,
"text": "A button is created using Ext.button class. On click event is written in listener. "
},
{
"code": null,
"e": 3214,
"s": 3137,
"text": "On click of this button an alert will appear with text \"Button is clicked\"\"."
},
{
"code": null,
"e": 3569,
"s": 3214,
"text": "Ext.onReady(function(){\n Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('helloWorldPanel'),\n text: 'My Button',\n listeners: {\n click: function() {\n this.message();\n },\n message: function() {\n Ext.MessageBox.alert('Alert box', 'Button is clicked');\t\t\t\t\n }\n }\n });\n});"
},
{
"code": null,
"e": 3577,
"s": 3569,
"text": "Output:"
},
{
"code": null,
"e": 3600,
"s": 3577,
"text": "Before clicking button"
},
{
"code": null,
"e": 3622,
"s": 3600,
"text": "After clicking button"
},
{
"code": null,
"e": 3688,
"s": 3622,
"text": "This way we can write multiple events also in listeners property."
},
{
"code": null,
"e": 3699,
"s": 3688,
"text": "Index.html"
},
{
"code": null,
"e": 4191,
"s": 3699,
"text": "<!DOCTYPE html>\n <html>\n <head>\n <link rel = 'stylesheet' type ='text/css' href= 'extjs-4.1.1/resources/css/ext-all.css' />\n <script type ='text/javascript' src = 'extjs-4.1.1/ext-all-debug.js'></script>\n <script type ='text/javascript' src = 'app.js'></script> \n </head>\n <body>\n <h1> Please click the button to see event listener </h1>\n <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >\n </body>\n </html>"
},
{
"code": null,
"e": 4198,
"s": 4191,
"text": "app.js"
},
{
"code": null,
"e": 4665,
"s": 4198,
"text": "Ext.onReady(function(){\n Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('helloWorldPanel'),\n text: 'My Button',\n listeners: {\n click: function() {\n this.hide();\n },\n hide: function() {\n Ext.MessageBox.alert('Alert box', 'Button is clicked');\n },\n mouseover: function() {\n Ext.MessageBox.alert('Alert box', 'Mouse over event is called');\n }\n }\n });\n});"
},
{
"code": null,
"e": 4673,
"s": 4665,
"text": "Output:"
},
{
"code": null,
"e": 4696,
"s": 4673,
"text": "Before clicking button"
},
{
"code": null,
"e": 4718,
"s": 4696,
"text": "After clicking button"
},
{
"code": null,
"e": 4732,
"s": 4718,
"text": "On mouse over"
},
{
"code": null,
"e": 4843,
"s": 4732,
"text": "In the previous method of writing events we have written events in listeners at the time of creating elements."
},
{
"code": null,
"e": 4884,
"s": 4843,
"text": "Other way is to attach events in the as:"
},
{
"code": null,
"e": 4891,
"s": 4884,
"text": "app.js"
},
{
"code": null,
"e": 5230,
"s": 4891,
"text": "Ext.onReady(function(){\n var button = Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('helloWorldPanel'),\n text: 'My Button',\n });\n // This way we can attach event to the button after the button is created.\n button.on('click', function() {\n Ext.MessageBox.alert('Alert box', Button is clicked');\n });\n});"
},
{
"code": null,
"e": 5253,
"s": 5230,
"text": "Before clicking button"
},
{
"code": null,
"e": 5275,
"s": 5253,
"text": "After clicking button"
},
{
"code": null,
"e": 5386,
"s": 5275,
"text": "The events which we have used above are the events which are inbuild in Ext JS. We can write custom events as:"
},
{
"code": null,
"e": 5393,
"s": 5386,
"text": "app.js"
},
{
"code": null,
"e": 5776,
"s": 5393,
"text": "Ext.onReady(function(){\n var button = Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('helloWorldPanel'),\n text: 'My Button',\n listeners: {\n myEvent: function(button) {\n Ext.MessageBox.alert('Alert box', 'My custom event is called');\n }\n }\n });\n Ext.defer(function() {\n button.fireEvent('myEvent');\n }, 5000);\n});"
},
{
"code": null,
"e": 5784,
"s": 5776,
"text": "Output:"
},
{
"code": null,
"e": 5973,
"s": 5784,
"text": "Once the page is loaded and document is ready the UI page with button will appear and as we are firing an event after 5 sec the document is ready the alert box will appear after 5 seconds."
},
{
"code": null,
"e": 6079,
"s": 5973,
"text": "Here we have written the custom event 'myEvent' and we are firing events as button.fireEvent(eventName);\n"
},
{
"code": null,
"e": 6133,
"s": 6079,
"text": "These are the three ways of writing events in Ext JS."
},
{
"code": null,
"e": 6140,
"s": 6133,
"text": " Print"
},
{
"code": null,
"e": 6151,
"s": 6140,
"text": " Add Notes"
}
] |
Tryit Editor v3.7
|
Tryit: Using the animation-delay property
|
[] |
Build an Extreme Learning Machine in Python | by Glenn Paul Gara | Towards Data Science
|
Extreme Learning Machines (ELMs) are single-hidden layer feedforward neural networks (SLFNs) capable to learn faster compared to gradient-based learning techniques. It’s like a classical one hidden layer neural network without a learning process. This kind of neural network does not perform iterative tuning, making it faster with better generalization performance than networks trained using backpropagation method.
ELMs are based on the Universal Approximation Theorem which states that:
“A feed-forward network with a single hidden layer containing a finite number of neurons can approximate continuous functions on compact subsets of R^n, under mild assumptions on the activation function.”
This simply means that ELMs can solve classification and regression tasks with significant accuracy if it has sufficient hidden neurons and training data to learn for all hidden neurons.
To understand how ELM works, let me show to you an illustration and the steps in building the model.
So, given the following:
Training set
Hidden node output function H(w, b, x)
Number of hidden nodes L
We can implement ELM in three simple steps:
Randomly assign the parameters of the hidden nodes (w, b)Compute the hidden layer output matrix HCompute the output weights β
Randomly assign the parameters of the hidden nodes (w, b)
Compute the hidden layer output matrix H
Compute the output weights β
Now, let’s proceed to the programming part. I am expecting that you know how to program in python and familiar already using packages in machine learning such as scikit-learn, numpy, and pandas.
We will train the network to classify handwritten digits using MNIST dataset.
First, we need to import necessary packages to build the model.
import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import OneHotEncoderfrom sklearn.preprocessing import MinMaxScaler
Next, we need to load our dataset to train the network and test the model.
train = pd.read_csv('mnist_train.csv')test = pd.read_csv('mnist_test.csv')
As a preprocessing technique, we will use MinMaxScaler and OneHotEncoder from scikit-learn package to normalize our features within the range of (0,1), and to transform our targets into a one-hot encoding format.
onehotencoder = OneHotEncoder(categories='auto')scaler = MinMaxScaler()X_train = scaler.fit_transform(train.values[:,1:])y_train = onehotencoder.fit_transform(train.values[:,:1]).toarray()X_test = scaler.fit_transform(test.values[:,1:])y_test = onehotencoder.fit_transform(test.values[:,:1]).toarray()
To initialize our network, we need to identify the following:1. The size of the input layer, which is the number of input features2. Number of hidden neurons3. Input to hidden weights4. Hidden layer activation function
The size of the input layer refers to the number of input features of the dataset.
input_size = X_train.shape[1]
Let’s initialize the number of hidden neurons to 1000.
hidden_size = 1000
Next, we need to initialize our input weights and biases randomly, drawn from a Gaussian distribution.
input_weights = np.random.normal(size=[input_size,hidden_size])biases = np.random.normal(size=[hidden_size])
We will use a Rectified Linear Unit (ReLU) as our hidden layer activation function.
Note: you can use different activation functions.
def relu(x): return np.maximum(x, 0, x)
We are done initializing our network!
The next thing to do is to create a function in computing the output weights which is our β. The goal is to minimize the least square error between the target (training labels) and the output (predicted labels) using the norm least-squares solution:
Where H (dagger) is the Moore–Penrose generalized inverse of matrix H, and T is our target.
Our H here is the hidden layer of our network. Let’s create a function to compute for our H vector.
def hidden_nodes(X): G = np.dot(X, input_weights) G = G + biases H = relu(G) return H
Now, we can compute our β in python in just one line of code. Let’s assign the output matrix to a variable name output_weights.
output_weights = np.dot(pinv2(hidden_nodes(X_train)), y_train)
The code computes the Moore-Penrose Pseudoinverse of H using the function pinv and we get the dot product of H (dagger) and T. The result is the computed β (hidden to output weights).
Finally, we have a model. We did not apply any techniques to tune our weights, we just simply compute them.
To ensure that our model produces a good result, we must first test it. Let’s create a function to handle the testing.
def predict(X): out = hidden_nodes(X) out = np.dot(out, output_weights) return out
We can start making predictions already. To do this, let’s write the following code:
prediction = predict(X_test)correct = 0total = X_test.shape[0for i in range(total): predicted = np.argmax(prediction[i]) actual = np.argmax(y_test[i]) correct += 1 if predicted == actual else 0accuracy = correct/totalprint('Accuracy for ', hidden_size, ' hidden nodes: ', accuracy)
The accuracy of the model is 0.9439, which is a good result already considering that we only have one hidden layer with 1000 hidden nodes, and a non-iterative tuning for learning, making it faster than any gradient-based techniques.
Referring to the graph above, ELM’s accuracy is increasing significantly when extending the number of hidden nodes to 1000 (0.9439 to 0.977). This means that ELM can generalize even better whenever we set the right number of hidden nodes of the network.
The jupyter notebook of this implementation is available in my GitHub tutorials repository below.
github.com
[1] Guang-Bin Huang, Qin-Yu Zhu and Chee-Kheong Siew, Extreme learning machine: Theory and applications (2006), Neurocomputing
[2] Guang-Bin Huang, Extreme Learning Machine, Nanyang Technological University
[3] Guang-Bin Huang, Qin-Yu Zhu and Chee-Kheong Siew, Extreme learning machine: a new learning scheme of feedforward neural networks (2004), IEEE International Joint Conference on Neural Networks
|
[
{
"code": null,
"e": 590,
"s": 172,
"text": "Extreme Learning Machines (ELMs) are single-hidden layer feedforward neural networks (SLFNs) capable to learn faster compared to gradient-based learning techniques. It’s like a classical one hidden layer neural network without a learning process. This kind of neural network does not perform iterative tuning, making it faster with better generalization performance than networks trained using backpropagation method."
},
{
"code": null,
"e": 663,
"s": 590,
"text": "ELMs are based on the Universal Approximation Theorem which states that:"
},
{
"code": null,
"e": 868,
"s": 663,
"text": "“A feed-forward network with a single hidden layer containing a finite number of neurons can approximate continuous functions on compact subsets of R^n, under mild assumptions on the activation function.”"
},
{
"code": null,
"e": 1055,
"s": 868,
"text": "This simply means that ELMs can solve classification and regression tasks with significant accuracy if it has sufficient hidden neurons and training data to learn for all hidden neurons."
},
{
"code": null,
"e": 1156,
"s": 1055,
"text": "To understand how ELM works, let me show to you an illustration and the steps in building the model."
},
{
"code": null,
"e": 1181,
"s": 1156,
"text": "So, given the following:"
},
{
"code": null,
"e": 1194,
"s": 1181,
"text": "Training set"
},
{
"code": null,
"e": 1233,
"s": 1194,
"text": "Hidden node output function H(w, b, x)"
},
{
"code": null,
"e": 1258,
"s": 1233,
"text": "Number of hidden nodes L"
},
{
"code": null,
"e": 1302,
"s": 1258,
"text": "We can implement ELM in three simple steps:"
},
{
"code": null,
"e": 1428,
"s": 1302,
"text": "Randomly assign the parameters of the hidden nodes (w, b)Compute the hidden layer output matrix HCompute the output weights β"
},
{
"code": null,
"e": 1486,
"s": 1428,
"text": "Randomly assign the parameters of the hidden nodes (w, b)"
},
{
"code": null,
"e": 1527,
"s": 1486,
"text": "Compute the hidden layer output matrix H"
},
{
"code": null,
"e": 1556,
"s": 1527,
"text": "Compute the output weights β"
},
{
"code": null,
"e": 1751,
"s": 1556,
"text": "Now, let’s proceed to the programming part. I am expecting that you know how to program in python and familiar already using packages in machine learning such as scikit-learn, numpy, and pandas."
},
{
"code": null,
"e": 1829,
"s": 1751,
"text": "We will train the network to classify handwritten digits using MNIST dataset."
},
{
"code": null,
"e": 1893,
"s": 1829,
"text": "First, we need to import necessary packages to build the model."
},
{
"code": null,
"e": 2076,
"s": 1893,
"text": "import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import OneHotEncoderfrom sklearn.preprocessing import MinMaxScaler"
},
{
"code": null,
"e": 2151,
"s": 2076,
"text": "Next, we need to load our dataset to train the network and test the model."
},
{
"code": null,
"e": 2226,
"s": 2151,
"text": "train = pd.read_csv('mnist_train.csv')test = pd.read_csv('mnist_test.csv')"
},
{
"code": null,
"e": 2439,
"s": 2226,
"text": "As a preprocessing technique, we will use MinMaxScaler and OneHotEncoder from scikit-learn package to normalize our features within the range of (0,1), and to transform our targets into a one-hot encoding format."
},
{
"code": null,
"e": 2741,
"s": 2439,
"text": "onehotencoder = OneHotEncoder(categories='auto')scaler = MinMaxScaler()X_train = scaler.fit_transform(train.values[:,1:])y_train = onehotencoder.fit_transform(train.values[:,:1]).toarray()X_test = scaler.fit_transform(test.values[:,1:])y_test = onehotencoder.fit_transform(test.values[:,:1]).toarray()"
},
{
"code": null,
"e": 2960,
"s": 2741,
"text": "To initialize our network, we need to identify the following:1. The size of the input layer, which is the number of input features2. Number of hidden neurons3. Input to hidden weights4. Hidden layer activation function"
},
{
"code": null,
"e": 3043,
"s": 2960,
"text": "The size of the input layer refers to the number of input features of the dataset."
},
{
"code": null,
"e": 3073,
"s": 3043,
"text": "input_size = X_train.shape[1]"
},
{
"code": null,
"e": 3128,
"s": 3073,
"text": "Let’s initialize the number of hidden neurons to 1000."
},
{
"code": null,
"e": 3147,
"s": 3128,
"text": "hidden_size = 1000"
},
{
"code": null,
"e": 3250,
"s": 3147,
"text": "Next, we need to initialize our input weights and biases randomly, drawn from a Gaussian distribution."
},
{
"code": null,
"e": 3359,
"s": 3250,
"text": "input_weights = np.random.normal(size=[input_size,hidden_size])biases = np.random.normal(size=[hidden_size])"
},
{
"code": null,
"e": 3443,
"s": 3359,
"text": "We will use a Rectified Linear Unit (ReLU) as our hidden layer activation function."
},
{
"code": null,
"e": 3493,
"s": 3443,
"text": "Note: you can use different activation functions."
},
{
"code": null,
"e": 3535,
"s": 3493,
"text": "def relu(x): return np.maximum(x, 0, x)"
},
{
"code": null,
"e": 3573,
"s": 3535,
"text": "We are done initializing our network!"
},
{
"code": null,
"e": 3823,
"s": 3573,
"text": "The next thing to do is to create a function in computing the output weights which is our β. The goal is to minimize the least square error between the target (training labels) and the output (predicted labels) using the norm least-squares solution:"
},
{
"code": null,
"e": 3915,
"s": 3823,
"text": "Where H (dagger) is the Moore–Penrose generalized inverse of matrix H, and T is our target."
},
{
"code": null,
"e": 4015,
"s": 3915,
"text": "Our H here is the hidden layer of our network. Let’s create a function to compute for our H vector."
},
{
"code": null,
"e": 4113,
"s": 4015,
"text": "def hidden_nodes(X): G = np.dot(X, input_weights) G = G + biases H = relu(G) return H"
},
{
"code": null,
"e": 4241,
"s": 4113,
"text": "Now, we can compute our β in python in just one line of code. Let’s assign the output matrix to a variable name output_weights."
},
{
"code": null,
"e": 4304,
"s": 4241,
"text": "output_weights = np.dot(pinv2(hidden_nodes(X_train)), y_train)"
},
{
"code": null,
"e": 4488,
"s": 4304,
"text": "The code computes the Moore-Penrose Pseudoinverse of H using the function pinv and we get the dot product of H (dagger) and T. The result is the computed β (hidden to output weights)."
},
{
"code": null,
"e": 4596,
"s": 4488,
"text": "Finally, we have a model. We did not apply any techniques to tune our weights, we just simply compute them."
},
{
"code": null,
"e": 4715,
"s": 4596,
"text": "To ensure that our model produces a good result, we must first test it. Let’s create a function to handle the testing."
},
{
"code": null,
"e": 4807,
"s": 4715,
"text": "def predict(X): out = hidden_nodes(X) out = np.dot(out, output_weights) return out"
},
{
"code": null,
"e": 4892,
"s": 4807,
"text": "We can start making predictions already. To do this, let’s write the following code:"
},
{
"code": null,
"e": 5183,
"s": 4892,
"text": "prediction = predict(X_test)correct = 0total = X_test.shape[0for i in range(total): predicted = np.argmax(prediction[i]) actual = np.argmax(y_test[i]) correct += 1 if predicted == actual else 0accuracy = correct/totalprint('Accuracy for ', hidden_size, ' hidden nodes: ', accuracy)"
},
{
"code": null,
"e": 5416,
"s": 5183,
"text": "The accuracy of the model is 0.9439, which is a good result already considering that we only have one hidden layer with 1000 hidden nodes, and a non-iterative tuning for learning, making it faster than any gradient-based techniques."
},
{
"code": null,
"e": 5670,
"s": 5416,
"text": "Referring to the graph above, ELM’s accuracy is increasing significantly when extending the number of hidden nodes to 1000 (0.9439 to 0.977). This means that ELM can generalize even better whenever we set the right number of hidden nodes of the network."
},
{
"code": null,
"e": 5768,
"s": 5670,
"text": "The jupyter notebook of this implementation is available in my GitHub tutorials repository below."
},
{
"code": null,
"e": 5779,
"s": 5768,
"text": "github.com"
},
{
"code": null,
"e": 5906,
"s": 5779,
"text": "[1] Guang-Bin Huang, Qin-Yu Zhu and Chee-Kheong Siew, Extreme learning machine: Theory and applications (2006), Neurocomputing"
},
{
"code": null,
"e": 5986,
"s": 5906,
"text": "[2] Guang-Bin Huang, Extreme Learning Machine, Nanyang Technological University"
}
] |
How to train Machine Learning models in the cloud using Cloud ML Engine | by Chris Rawles | Towards Data Science
|
And how to artfully write a task.py using the docopt package
Training ML models in the cloud makes a lot of sense. Why? Among many reasons, it allows you to train on large amounts of data with plentiful compute and perhaps train many models in parallel. Plus it’s not hard to do! On Google Cloud Platform, you can use Cloud ML Engine to train machine learning models in TensorFlow and other Python ML libraries (such as scikit-learn) without having to manage any infrastructure. In order to do this, you will need to put your code into a Python package (i.e. add setup.py and __init__.py files). In addition, it is a best practice to organize your code into a model.py and task.py. In this blog post, I will step you through what this involves.
The task.py file
As a teacher, one of the first things I see students, particularly those newer to Python, get hung up on is creating a task.py file. Although it’s technically optional (see below), it’s highly recommended because it allows you to separate hyperparameters from the model logic (located in model.py). It’s usually the actual file that is called by ML engine and its purpose is twofold:
Reads and parses model parameters, like location of the training data and output model, # hidden layers, batch size, etc.Calls the model training logic located in model.py with said parameters
Reads and parses model parameters, like location of the training data and output model, # hidden layers, batch size, etc.
Calls the model training logic located in model.py with said parameters
There are many different ways you can write a task.py file — there are even different names you can give it. In fact the task.py and model.py convention is merely that — a convention. We could have called task.py aReallyCoolArgument_parser.py and model.py very_deeeep_model.py.
We could even combine these two entities into a single file that does argument parsing and trains a model. ML Engine doesn’t care as long as you arrange your code into a Python package (i.e. it must contain setup.py and __init__.py). But, stick with the convention of two files named task.py and model.py inside a trainer folder (more details below) that house your argument parsing and model logic, respectively.
Check out the Cloud ML samples and Cloud ML training repos for full examples of using Cloud ML Engine and examples of model.py and task.py files.
Writing clean task.py files using docopt
Although many people use argparse, the standard Python library for parsing command-line arguments, I prefer to write my task.py files using the docopt package. Why? Because it’s the most concise way to write a documented task.py. In fact, pretty much the only thing you write is your program’s usage message (i.e. the help message) and docopt takes care of the rest. Based on the usage message you write in the module’s doc string (Python will call this __doc__), you call docopt(__doc__), which generates an argument parser for you based on the format you specify in the doc string. Here is the above example using docopt:
Pretty nice, right? Let me break it down. The first block of code is the usage for your task.py. If you call it with no arguments or incorrectly call task.py this will display to the user.
The line arguments = docopt(__doc__) parses the usage pattern (“Usage: ...”) and option descriptions (lines starting with dash “-”) from the help string and ensures that the program invocation matches the usage pattern.
The final section assigns these parameters to model.py variables and then executes the training and evaluation.
Let’s run a job. Remember the task.py is part of a family of files, called a Python package. In practice you will spend the bulk of your time writing the model.py file, a little time creating the task.py file, and the rest is basically boilerplate.
training_example # root directory setup.py # says how to install your package trainer # package name, “trainer” is convention model.py task.py __init__.py # Python convention indicating this is a package
Because we are using docopt, which is not part of the standard library, we must add it to setup.py, so we insert an additional line into setup.py:
This will tell Cloud ML Engine to install docopt by running pip install docopt when we submit a job to the cloud.
Finally once we have our files in the above structure we can submit a job to ML Engine. Before we do that, let’s first test our package locally using python -m and then ml-engine local predict. These two steps, while optional, can help you debug and test your packages functionality before submitting to the cloud. You typically do this on a tiny data set or just a very limited number of training steps.
%%bash
TRAIN_DATA_PATHS=path/to/training/data
OUTPUT_DIR=path/to/output/location
export PYTHONPATH=${PYTHONPATH}:${PWD}/training_example
python -m trainer.docopt_task --train_data_paths $TRAIN_DATA_PATHS\
--output_dir $OUTPUT_DIR\
--batch_size 100\
--hidden_units 50,25,10
Very useful for debugging ML Engine parameters
%%bash
TRAIN_DATA_PATHS=path/to/training/data
OUTPUT_DIR=path/to/output/location
JOBNAME=my_ml_job_$(date -u +%y%m%d_%H%M%S)
REGION='us-central1'
BUCKET='my-bucket'
gcloud ml-engine local train\
--package-path=$PWD/training_example/trainer \
--module-name=trainer.task \
-- \ # Required. Seperates ML engine params from package params.
--train_data_paths $TRAIN_DATA_PATHS \
--output_dir $OUTPUT_DIR\
--batch_size 100\
--hidden_units 50,25,10
Once we have tested our model locally we will submit our job to ML Engine using gcloud ml-engine jobs submit training
Note the arguments to ml-engine. Those before the empty -- are specific to ML Engine, while those after, named USER_ARGS, are for your package.
%%bash
TRAIN_DATA_PATHS=path/to/training/data
OUTPUT_DIR=path/to/output/location
JOBNAME=my_ml_job_$(date -u +%y%m%d_%H%M%S)
REGION='us-central1'
BUCKET='my-bucket-name'
gcloud ml-engine jobs submit training $JOBNAME \
--package-path=$PWD/training_example/trainer \
--module-name=trainer.task \
--region=$REGION \
--staging-bucket=gs://$BUCKET \
--scale-tier=BASIC \
--runtime-version=1.8 \
-- \ # Required.
--train_data_paths $TRAIN_DATA_PATHS \
--output_dir $OUTPUT_DIR\
--batch_size 100\
--hidden_units 50,25,10
These two lines are relevant to our discussion:
— package-path=$(pwd)/my_model_package/trainer \— module-name trainer.task
The first line indicates the location of our package name, which we always call trainer (a convention). The second line indicates, in the trainer package, that we will call the task module (task.py) in the trainer package.
Conclusion
By building a task.py we can process hyperparameters as command line arguments, which allows us to decouple our model logic from hyperparameters. A key benefit is this allows us to easily fire off multiple jobs in parallel using different parameters to determine an optimal hyperparameter set (we can even use the built in hyperparameter tuning service!). Finally, the docopt package automatically generates a parser for our task.py file, based on the usage string that the user writes.
That’s it! I hope this makes it clear how to submit a ML Engine job and build a task.py. Please leave a clap if you found this helpful so others can find it.
Additional Resources
Google Cloud ML samples
Google Cloud machine learning training
Cloud ML Engine documentation
docopt documentation
Packaging a Python module
|
[
{
"code": null,
"e": 233,
"s": 172,
"text": "And how to artfully write a task.py using the docopt package"
},
{
"code": null,
"e": 917,
"s": 233,
"text": "Training ML models in the cloud makes a lot of sense. Why? Among many reasons, it allows you to train on large amounts of data with plentiful compute and perhaps train many models in parallel. Plus it’s not hard to do! On Google Cloud Platform, you can use Cloud ML Engine to train machine learning models in TensorFlow and other Python ML libraries (such as scikit-learn) without having to manage any infrastructure. In order to do this, you will need to put your code into a Python package (i.e. add setup.py and __init__.py files). In addition, it is a best practice to organize your code into a model.py and task.py. In this blog post, I will step you through what this involves."
},
{
"code": null,
"e": 934,
"s": 917,
"text": "The task.py file"
},
{
"code": null,
"e": 1318,
"s": 934,
"text": "As a teacher, one of the first things I see students, particularly those newer to Python, get hung up on is creating a task.py file. Although it’s technically optional (see below), it’s highly recommended because it allows you to separate hyperparameters from the model logic (located in model.py). It’s usually the actual file that is called by ML engine and its purpose is twofold:"
},
{
"code": null,
"e": 1511,
"s": 1318,
"text": "Reads and parses model parameters, like location of the training data and output model, # hidden layers, batch size, etc.Calls the model training logic located in model.py with said parameters"
},
{
"code": null,
"e": 1633,
"s": 1511,
"text": "Reads and parses model parameters, like location of the training data and output model, # hidden layers, batch size, etc."
},
{
"code": null,
"e": 1705,
"s": 1633,
"text": "Calls the model training logic located in model.py with said parameters"
},
{
"code": null,
"e": 1983,
"s": 1705,
"text": "There are many different ways you can write a task.py file — there are even different names you can give it. In fact the task.py and model.py convention is merely that — a convention. We could have called task.py aReallyCoolArgument_parser.py and model.py very_deeeep_model.py."
},
{
"code": null,
"e": 2397,
"s": 1983,
"text": "We could even combine these two entities into a single file that does argument parsing and trains a model. ML Engine doesn’t care as long as you arrange your code into a Python package (i.e. it must contain setup.py and __init__.py). But, stick with the convention of two files named task.py and model.py inside a trainer folder (more details below) that house your argument parsing and model logic, respectively."
},
{
"code": null,
"e": 2543,
"s": 2397,
"text": "Check out the Cloud ML samples and Cloud ML training repos for full examples of using Cloud ML Engine and examples of model.py and task.py files."
},
{
"code": null,
"e": 2584,
"s": 2543,
"text": "Writing clean task.py files using docopt"
},
{
"code": null,
"e": 3208,
"s": 2584,
"text": "Although many people use argparse, the standard Python library for parsing command-line arguments, I prefer to write my task.py files using the docopt package. Why? Because it’s the most concise way to write a documented task.py. In fact, pretty much the only thing you write is your program’s usage message (i.e. the help message) and docopt takes care of the rest. Based on the usage message you write in the module’s doc string (Python will call this __doc__), you call docopt(__doc__), which generates an argument parser for you based on the format you specify in the doc string. Here is the above example using docopt:"
},
{
"code": null,
"e": 3397,
"s": 3208,
"text": "Pretty nice, right? Let me break it down. The first block of code is the usage for your task.py. If you call it with no arguments or incorrectly call task.py this will display to the user."
},
{
"code": null,
"e": 3617,
"s": 3397,
"text": "The line arguments = docopt(__doc__) parses the usage pattern (“Usage: ...”) and option descriptions (lines starting with dash “-”) from the help string and ensures that the program invocation matches the usage pattern."
},
{
"code": null,
"e": 3729,
"s": 3617,
"text": "The final section assigns these parameters to model.py variables and then executes the training and evaluation."
},
{
"code": null,
"e": 3978,
"s": 3729,
"text": "Let’s run a job. Remember the task.py is part of a family of files, called a Python package. In practice you will spend the bulk of your time writing the model.py file, a little time creating the task.py file, and the rest is basically boilerplate."
},
{
"code": null,
"e": 4201,
"s": 3978,
"text": "training_example # root directory setup.py # says how to install your package trainer # package name, “trainer” is convention model.py task.py __init__.py # Python convention indicating this is a package"
},
{
"code": null,
"e": 4348,
"s": 4201,
"text": "Because we are using docopt, which is not part of the standard library, we must add it to setup.py, so we insert an additional line into setup.py:"
},
{
"code": null,
"e": 4462,
"s": 4348,
"text": "This will tell Cloud ML Engine to install docopt by running pip install docopt when we submit a job to the cloud."
},
{
"code": null,
"e": 4867,
"s": 4462,
"text": "Finally once we have our files in the above structure we can submit a job to ML Engine. Before we do that, let’s first test our package locally using python -m and then ml-engine local predict. These two steps, while optional, can help you debug and test your packages functionality before submitting to the cloud. You typically do this on a tiny data set or just a very limited number of training steps."
},
{
"code": null,
"e": 5153,
"s": 4867,
"text": "%%bash\nTRAIN_DATA_PATHS=path/to/training/data\nOUTPUT_DIR=path/to/output/location\nexport PYTHONPATH=${PYTHONPATH}:${PWD}/training_example\npython -m trainer.docopt_task --train_data_paths $TRAIN_DATA_PATHS\\\n --output_dir $OUTPUT_DIR\\\n --batch_size 100\\\n --hidden_units 50,25,10\n"
},
{
"code": null,
"e": 5200,
"s": 5153,
"text": "Very useful for debugging ML Engine parameters"
},
{
"code": null,
"e": 5702,
"s": 5200,
"text": "%%bash\nTRAIN_DATA_PATHS=path/to/training/data\nOUTPUT_DIR=path/to/output/location\nJOBNAME=my_ml_job_$(date -u +%y%m%d_%H%M%S)\nREGION='us-central1'\nBUCKET='my-bucket'\n\ngcloud ml-engine local train\\\n --package-path=$PWD/training_example/trainer \\\n --module-name=trainer.task \\\n -- \\ # Required. Seperates ML engine params from package params.\n --train_data_paths $TRAIN_DATA_PATHS \\\n --output_dir $OUTPUT_DIR\\\n --batch_size 100\\\n --hidden_units 50,25,10\n"
},
{
"code": null,
"e": 5820,
"s": 5702,
"text": "Once we have tested our model locally we will submit our job to ML Engine using gcloud ml-engine jobs submit training"
},
{
"code": null,
"e": 5964,
"s": 5820,
"text": "Note the arguments to ml-engine. Those before the empty -- are specific to ML Engine, while those after, named USER_ARGS, are for your package."
},
{
"code": null,
"e": 6570,
"s": 5964,
"text": "%%bash\nTRAIN_DATA_PATHS=path/to/training/data\nOUTPUT_DIR=path/to/output/location\nJOBNAME=my_ml_job_$(date -u +%y%m%d_%H%M%S)\nREGION='us-central1'\nBUCKET='my-bucket-name'\n\ngcloud ml-engine jobs submit training $JOBNAME \\\n --package-path=$PWD/training_example/trainer \\\n --module-name=trainer.task \\\n --region=$REGION \\\n --staging-bucket=gs://$BUCKET \\\n --scale-tier=BASIC \\\n --runtime-version=1.8 \\\n -- \\ # Required.\n --train_data_paths $TRAIN_DATA_PATHS \\\n --output_dir $OUTPUT_DIR\\\n --batch_size 100\\\n --hidden_units 50,25,10\n"
},
{
"code": null,
"e": 6618,
"s": 6570,
"text": "These two lines are relevant to our discussion:"
},
{
"code": null,
"e": 6693,
"s": 6618,
"text": "— package-path=$(pwd)/my_model_package/trainer \\— module-name trainer.task"
},
{
"code": null,
"e": 6916,
"s": 6693,
"text": "The first line indicates the location of our package name, which we always call trainer (a convention). The second line indicates, in the trainer package, that we will call the task module (task.py) in the trainer package."
},
{
"code": null,
"e": 6927,
"s": 6916,
"text": "Conclusion"
},
{
"code": null,
"e": 7414,
"s": 6927,
"text": "By building a task.py we can process hyperparameters as command line arguments, which allows us to decouple our model logic from hyperparameters. A key benefit is this allows us to easily fire off multiple jobs in parallel using different parameters to determine an optimal hyperparameter set (we can even use the built in hyperparameter tuning service!). Finally, the docopt package automatically generates a parser for our task.py file, based on the usage string that the user writes."
},
{
"code": null,
"e": 7572,
"s": 7414,
"text": "That’s it! I hope this makes it clear how to submit a ML Engine job and build a task.py. Please leave a clap if you found this helpful so others can find it."
},
{
"code": null,
"e": 7593,
"s": 7572,
"text": "Additional Resources"
},
{
"code": null,
"e": 7617,
"s": 7593,
"text": "Google Cloud ML samples"
},
{
"code": null,
"e": 7656,
"s": 7617,
"text": "Google Cloud machine learning training"
},
{
"code": null,
"e": 7686,
"s": 7656,
"text": "Cloud ML Engine documentation"
},
{
"code": null,
"e": 7707,
"s": 7686,
"text": "docopt documentation"
}
] |
Ways To Reduce The Loading Time Of Website | Set 1
|
07 Nov, 2019
“Patience is a virtue” – an adage that hardly holds when we consider online activities. The page load time of your website is very important. Why?It decides whether a visitor to your site will explore further, or shall part ways on the first click.Some statistical facts:
A 1-second load time delay leads to 11% fewer page views, 16% decrease in customer satisfaction and 7% loss in conversions.
44% of customers develop a negative image of the company, if its website load time is poor.
According to Amazon, there is a 1% increase in revenue for every 100 milliseconds improvement.
Also, studies say, 47% visitors expect the load time to be 2 seconds or less, and if it takes longer than 3 seconds, 57% of your prospects will abandon the site and go elsewhere to serve their needs.
The speed also determines the Google search ranking of your website. Below are provided certain ways that shall help in decreasing the load time of your website.
Ways to decrease load time of your Website
1. Optimize Images : Images should be scaled appropriately, before uploading. We need to understand this: if we have a 1000 X 1000 pixels image, which we have scaled down to 100 X 100 pixels with the help of CSS, the browser still loads the actual size, that is, in this case, 10 times more than necessary.
To avoid this, crop or scale your images before uploading them to your site using various image editing tools. Some of these image optimization tools are :
Smush.it
Online Image Optimizer
JPEG &PNG Stripper
SuperGIF
Talking of image format, JPEG is the best option. PNG is good too, though not supported by many older browsers.
2. Minify JavaScript and Style Sheets : Minification is removal of all unnecessary characters from code so as to reduce the size. Unneeded white space characters like space, newline, tab etc. and comments are removed. Recommended tools for minifying HTML, CSS and JavaScript:
For HTML, we can use the PageSpeed Insights Chrome Extension to generate optimized version of your HTML code.
For CSS, use the YUI Compressor and cssmin.js
For JavaScript, Closure Compiler, JSMin, or the YUI Compressor may be used.
There are some online tools also that can be used, https://javascript-minifier.com/, https://cssminifier.com/
3. Enable Compression : Large pages can be compressed by zipping them. Compression reduces the bandwidth of your pages, subsequently reducing HTTP response.
Gzip is one tool often used to achieve this.Since 90% of today’s Internet traffic uses Gzip, it is worth an option. After Gzip Compression, set up your server to enable compression.
Apache: Use mod_deflate
Nginx: Use HttpGzipModule
IIS: Configure HTTP Compression
4. Browser Caching : Temporary storage of data on the visitor’s hard drive will do away with the waiting time visitors undergo every time they visit your site. This can be done using browser caching. However, the duration for which this data is stored depends on your server-side cache configuration. To enable browser caching, you need to edit your HTTP headers to set up expiry times for certain types of files.
This example shows how to configure Apache to serve appropriate headers:
Find your .htaccess file in the root of your domain. The file is hidden , but FTP clients like FileZilla would help it show up.
Use notepad or any other basic editor to add following to the .htaccess file.
## EXPIRES CACHING ##<IfModule mod_expires.c>ExpiresActive OnExpiresByType image/jpg "access plus 1 year"ExpiresByType image/jpeg "access plus 1 year"ExpiresByType image/gif "access plus 1 year"ExpiresByType image/png "access plus 1 year"ExpiresByType text/css "access plus 1 month"ExpiresByType application/pdf "access plus 1 month"ExpiresByType text/x-javascript "access plus 1 month"ExpiresByType application/x-shockwave-flash "access plus 1 month"ExpiresByType image/x-icon "access plus 1 year"ExpiresDefault "access plus 2 days"</IfModule>## EXPIRES CACHING ##
Important Points
Different expiry times could be set depending on your website’s files. Frequently updated files would require an earlier expiry time.
When you are done, save the file as it is.
More ways shall be explored in the below next set.Ways To Reduce The Loading Time Of Your Website | Set 2
References:
https://www.crazyegg.com/blog/speed-up-your-website/
https://www.truconversion.com/blog/conversion-rate-optimization/9-tips-to-reduce-page-load-time-and-improve-website-speed/
http://cubewires.com/insights/reduce-web-page-load-time/
https://gtmetrix.com/leverage-browser-caching.html
This article is contributed by Nihar Ranjan Sarkar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 324,
"s": 52,
"text": "“Patience is a virtue” – an adage that hardly holds when we consider online activities. The page load time of your website is very important. Why?It decides whether a visitor to your site will explore further, or shall part ways on the first click.Some statistical facts:"
},
{
"code": null,
"e": 448,
"s": 324,
"text": "A 1-second load time delay leads to 11% fewer page views, 16% decrease in customer satisfaction and 7% loss in conversions."
},
{
"code": null,
"e": 540,
"s": 448,
"text": "44% of customers develop a negative image of the company, if its website load time is poor."
},
{
"code": null,
"e": 635,
"s": 540,
"text": "According to Amazon, there is a 1% increase in revenue for every 100 milliseconds improvement."
},
{
"code": null,
"e": 835,
"s": 635,
"text": "Also, studies say, 47% visitors expect the load time to be 2 seconds or less, and if it takes longer than 3 seconds, 57% of your prospects will abandon the site and go elsewhere to serve their needs."
},
{
"code": null,
"e": 997,
"s": 835,
"text": "The speed also determines the Google search ranking of your website. Below are provided certain ways that shall help in decreasing the load time of your website."
},
{
"code": null,
"e": 1040,
"s": 997,
"text": "Ways to decrease load time of your Website"
},
{
"code": null,
"e": 1347,
"s": 1040,
"text": "1. Optimize Images : Images should be scaled appropriately, before uploading. We need to understand this: if we have a 1000 X 1000 pixels image, which we have scaled down to 100 X 100 pixels with the help of CSS, the browser still loads the actual size, that is, in this case, 10 times more than necessary."
},
{
"code": null,
"e": 1503,
"s": 1347,
"text": "To avoid this, crop or scale your images before uploading them to your site using various image editing tools. Some of these image optimization tools are :"
},
{
"code": null,
"e": 1512,
"s": 1503,
"text": "Smush.it"
},
{
"code": null,
"e": 1535,
"s": 1512,
"text": "Online Image Optimizer"
},
{
"code": null,
"e": 1554,
"s": 1535,
"text": "JPEG &PNG Stripper"
},
{
"code": null,
"e": 1563,
"s": 1554,
"text": "SuperGIF"
},
{
"code": null,
"e": 1675,
"s": 1563,
"text": "Talking of image format, JPEG is the best option. PNG is good too, though not supported by many older browsers."
},
{
"code": null,
"e": 1952,
"s": 1675,
"text": "2. Minify JavaScript and Style Sheets : Minification is removal of all unnecessary characters from code so as to reduce the size. Unneeded white space characters like space, newline, tab etc. and comments are removed. Recommended tools for minifying HTML, CSS and JavaScript:"
},
{
"code": null,
"e": 2062,
"s": 1952,
"text": "For HTML, we can use the PageSpeed Insights Chrome Extension to generate optimized version of your HTML code."
},
{
"code": null,
"e": 2108,
"s": 2062,
"text": "For CSS, use the YUI Compressor and cssmin.js"
},
{
"code": null,
"e": 2184,
"s": 2108,
"text": "For JavaScript, Closure Compiler, JSMin, or the YUI Compressor may be used."
},
{
"code": null,
"e": 2294,
"s": 2184,
"text": "There are some online tools also that can be used, https://javascript-minifier.com/, https://cssminifier.com/"
},
{
"code": null,
"e": 2451,
"s": 2294,
"text": "3. Enable Compression : Large pages can be compressed by zipping them. Compression reduces the bandwidth of your pages, subsequently reducing HTTP response."
},
{
"code": null,
"e": 2633,
"s": 2451,
"text": "Gzip is one tool often used to achieve this.Since 90% of today’s Internet traffic uses Gzip, it is worth an option. After Gzip Compression, set up your server to enable compression."
},
{
"code": null,
"e": 2657,
"s": 2633,
"text": "Apache: Use mod_deflate"
},
{
"code": null,
"e": 2683,
"s": 2657,
"text": "Nginx: Use HttpGzipModule"
},
{
"code": null,
"e": 2715,
"s": 2683,
"text": "IIS: Configure HTTP Compression"
},
{
"code": null,
"e": 3129,
"s": 2715,
"text": "4. Browser Caching : Temporary storage of data on the visitor’s hard drive will do away with the waiting time visitors undergo every time they visit your site. This can be done using browser caching. However, the duration for which this data is stored depends on your server-side cache configuration. To enable browser caching, you need to edit your HTTP headers to set up expiry times for certain types of files."
},
{
"code": null,
"e": 3202,
"s": 3129,
"text": "This example shows how to configure Apache to serve appropriate headers:"
},
{
"code": null,
"e": 3330,
"s": 3202,
"text": "Find your .htaccess file in the root of your domain. The file is hidden , but FTP clients like FileZilla would help it show up."
},
{
"code": null,
"e": 3408,
"s": 3330,
"text": "Use notepad or any other basic editor to add following to the .htaccess file."
},
{
"code": "## EXPIRES CACHING ##<IfModule mod_expires.c>ExpiresActive OnExpiresByType image/jpg \"access plus 1 year\"ExpiresByType image/jpeg \"access plus 1 year\"ExpiresByType image/gif \"access plus 1 year\"ExpiresByType image/png \"access plus 1 year\"ExpiresByType text/css \"access plus 1 month\"ExpiresByType application/pdf \"access plus 1 month\"ExpiresByType text/x-javascript \"access plus 1 month\"ExpiresByType application/x-shockwave-flash \"access plus 1 month\"ExpiresByType image/x-icon \"access plus 1 year\"ExpiresDefault \"access plus 2 days\"</IfModule>## EXPIRES CACHING ##",
"e": 3974,
"s": 3408,
"text": null
},
{
"code": null,
"e": 3991,
"s": 3974,
"text": "Important Points"
},
{
"code": null,
"e": 4125,
"s": 3991,
"text": "Different expiry times could be set depending on your website’s files. Frequently updated files would require an earlier expiry time."
},
{
"code": null,
"e": 4168,
"s": 4125,
"text": "When you are done, save the file as it is."
},
{
"code": null,
"e": 4274,
"s": 4168,
"text": "More ways shall be explored in the below next set.Ways To Reduce The Loading Time Of Your Website | Set 2"
},
{
"code": null,
"e": 4286,
"s": 4274,
"text": "References:"
},
{
"code": null,
"e": 4339,
"s": 4286,
"text": "https://www.crazyegg.com/blog/speed-up-your-website/"
},
{
"code": null,
"e": 4462,
"s": 4339,
"text": "https://www.truconversion.com/blog/conversion-rate-optimization/9-tips-to-reduce-page-load-time-and-improve-website-speed/"
},
{
"code": null,
"e": 4519,
"s": 4462,
"text": "http://cubewires.com/insights/reduce-web-page-load-time/"
},
{
"code": null,
"e": 4570,
"s": 4519,
"text": "https://gtmetrix.com/leverage-browser-caching.html"
},
{
"code": null,
"e": 4877,
"s": 4570,
"text": "This article is contributed by Nihar Ranjan Sarkar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5002,
"s": 4877,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5015,
"s": 5002,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5032,
"s": 5015,
"text": "Web Technologies"
}
] |
Warnsdorff’s algorithm for Knight’s tour problem
|
31 May, 2022
Problem : A knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once.
Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight.
We have discussed Backtracking Algorithm for solution of Knight’s tour. In this post Warnsdorff’s heuristic is discussed. Warnsdorff’s Rule:
We can start from any initial position of the knight on the board.We always move to an adjacent, unvisited square with minimal degree (minimum number of unvisited adjacent).
We can start from any initial position of the knight on the board.
We always move to an adjacent, unvisited square with minimal degree (minimum number of unvisited adjacent).
This algorithm may also more generally be applied to any graph.
Some definitions:
A position Q is accessible from a position P if P can move to Q by a single Knight’s move, and Q has not yet been visited.
The accessibility of a position P is the number of positions accessible from P.
Algorithm:
Set P to be a random initial position on the boardMark the board at P with the move number “1”Do following for each move number from 2 to the number of squares on the board: let S be the set of positions accessible from P.Set P to be the position in S with minimum accessibilityMark the board at P with the current move numberReturn the marked board — each square will be marked with the move number on which it is visited.
Set P to be a random initial position on the board
Mark the board at P with the move number “1”
Do following for each move number from 2 to the number of squares on the board: let S be the set of positions accessible from P.Set P to be the position in S with minimum accessibilityMark the board at P with the current move number
let S be the set of positions accessible from P.
Set P to be the position in S with minimum accessibility
Mark the board at P with the current move number
Return the marked board — each square will be marked with the move number on which it is visited.
Below is implementation of above algorithm.
C++
Java
C#
// C++ program to for Knight's tour problem using// Warnsdorff's algorithm#include <bits/stdc++.h>#define N 8 // Move pattern on basis of the change of// x coordinates and y coordinates respectivelystatic int cx[N] = {1,1,2,2,-1,-1,-2,-2};static int cy[N] = {2,-2,1,-1,2,-2,1,-1}; // function restricts the knight to remain within// the 8x8 chessboardbool limits(int x, int y){ return ((x >= 0 && y >= 0) && (x < N && y < N));} /* Checks whether a square is valid and empty or not */bool isempty(int a[], int x, int y){ return (limits(x, y)) && (a[y*N+x] < 0);} /* Returns the number of empty squares adjacent to (x, y) */int getDegree(int a[], int x, int y){ int count = 0; for (int i = 0; i < N; ++i) if (isempty(a, (x + cx[i]), (y + cy[i]))) count++; return count;} // Picks next point using Warnsdorff's heuristic.// Returns false if it is not possible to pick// next point.bool nextMove(int a[], int *x, int *y){ int min_deg_idx = -1, c, min_deg = (N+1), nx, ny; // Try all N adjacent of (*x, *y) starting // from a random adjacent. Find the adjacent // with minimum degree. int start = rand()%N; for (int count = 0; count < N; ++count) { int i = (start + count)%N; nx = *x + cx[i]; ny = *y + cy[i]; if ((isempty(a, nx, ny)) && (c = getDegree(a, nx, ny)) < min_deg) { min_deg_idx = i; min_deg = c; } } // IF we could not find a next cell if (min_deg_idx == -1) return false; // Store coordinates of next point nx = *x + cx[min_deg_idx]; ny = *y + cy[min_deg_idx]; // Mark next move a[ny*N + nx] = a[(*y)*N + (*x)]+1; // Update next point *x = nx; *y = ny; return true;} /* displays the chessboard with all the legal knight's moves */void print(int a[]){ for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) printf("%d\t",a[j*N+i]); printf("\n"); }} /* checks its neighbouring squares *//* If the knight ends on a square that is one knight's move from the beginning square, then tour is closed */bool neighbour(int x, int y, int xx, int yy){ for (int i = 0; i < N; ++i) if (((x+cx[i]) == xx)&&((y + cy[i]) == yy)) return true; return false;} /* Generates the legal moves using warnsdorff's heuristics. Returns false if not possible */bool findClosedTour(){ // Filling up the chessboard matrix with -1's int a[N*N]; for (int i = 0; i< N*N; ++i) a[i] = -1; // Random initial position int sx = rand()%N; int sy = rand()%N; // Current points are same as initial points int x = sx, y = sy; a[y*N+x] = 1; // Mark first move. // Keep picking next points using // Warnsdorff's heuristic for (int i = 0; i < N*N-1; ++i) if (nextMove(a, &x, &y) == 0) return false; // Check if tour is closed (Can end // at starting point) if (!neighbour(x, y, sx, sy)) return false; print(a); return true;} // Driver codeint main(){ // To make sure that different random // initial positions are picked. srand(time(NULL)); // While we don't get a solution while (!findClosedTour()) { ; } return 0;}
// Java program to for Knight's tour problem using// Warnsdorff's algorithmimport java.util.concurrent.ThreadLocalRandom; class GFG{ public static final int N = 8; // Move pattern on basis of the change of // x coordinates and y coordinates respectively public static final int cx[] = {1, 1, 2, 2, -1, -1, -2, -2}; public static final int cy[] = {2, -2, 1, -1, 2, -2, 1, -1}; // function restricts the knight to remain within // the 8x8 chessboard boolean limits(int x, int y) { return ((x >= 0 && y >= 0) && (x < N && y < N)); } /* Checks whether a square is valid and empty or not */ boolean isempty(int a[], int x, int y) { return (limits(x, y)) && (a[y * N + x] < 0); } /* Returns the number of empty squares adjacent to (x, y) */ int getDegree(int a[], int x, int y) { int count = 0; for (int i = 0; i < N; ++i) if (isempty(a, (x + cx[i]), (y + cy[i]))) count++; return count; } // Picks next point using Warnsdorff's heuristic. // Returns false if it is not possible to pick // next point. Cell nextMove(int a[], Cell cell) { int min_deg_idx = -1, c, min_deg = (N + 1), nx, ny; // Try all N adjacent of (*x, *y) starting // from a random adjacent. Find the adjacent // with minimum degree. int start = ThreadLocalRandom.current().nextInt(1000) % N; for (int count = 0; count < N; ++count) { int i = (start + count) % N; nx = cell.x + cx[i]; ny = cell.y + cy[i]; if ((isempty(a, nx, ny)) && (c = getDegree(a, nx, ny)) < min_deg) { min_deg_idx = i; min_deg = c; } } // IF we could not find a next cell if (min_deg_idx == -1) return null; // Store coordinates of next point nx = cell.x + cx[min_deg_idx]; ny = cell.y + cy[min_deg_idx]; // Mark next move a[ny * N + nx] = a[(cell.y) * N + (cell.x)] + 1; // Update next point cell.x = nx; cell.y = ny; return cell; } /* displays the chessboard with all the legal knight's moves */ void print(int a[]) { for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) System.out.printf("%d\t", a[j * N + i]); System.out.printf("\n"); } } /* checks its neighbouring squares */ /* If the knight ends on a square that is one knight's move from the beginning square, then tour is closed */ boolean neighbour(int x, int y, int xx, int yy) { for (int i = 0; i < N; ++i) if (((x + cx[i]) == xx) && ((y + cy[i]) == yy)) return true; return false; } /* Generates the legal moves using warnsdorff's heuristics. Returns false if not possible */ boolean findClosedTour() { // Filling up the chessboard matrix with -1's int a[] = new int[N * N]; for (int i = 0; i < N * N; ++i) a[i] = -1; // initial position int sx = 3; int sy = 2; // Current points are same as initial points Cell cell = new Cell(sx, sy); a[cell.y * N + cell.x] = 1; // Mark first move. // Keep picking next points using // Warnsdorff's heuristic Cell ret = null; for (int i = 0; i < N * N - 1; ++i) { ret = nextMove(a, cell); if (ret == null) return false; } // Check if tour is closed (Can end // at starting point) if (!neighbour(ret.x, ret.y, sx, sy)) return false; print(a); return true; } // Driver Code public static void main(String[] args) { // While we don't get a solution while (!new GFG().findClosedTour()) { ; } }} class Cell{ int x; int y; public Cell(int x, int y) { this.x = x; this.y = y; }} // This code is contributed by SaeedZarinfam
//C# program for Knight’s tour //problem using Warnsdorff’salgorithmusing System;using System.Collections;using System.Collections.Generic; public class GFG{ public static int N = 8; // Move pattern on basis of the change of // x coordinates and y coordinates respectively public int[] cx = new int[] {1, 1, 2, 2, -1, -1, -2, -2}; public int[] cy = new int[] {2, -2, 1, -1, 2, -2, 1, -1}; // function restricts the knight to remain within // the 8x8 chessboard bool limits(int x, int y) { return ((x >= 0 && y >= 0) && (x < N && y < N)); } /* Checks whether a square is valid and empty or not */ bool isempty(int[] a, int x, int y) { return ((limits(x, y)) && (a[y * N + x] < 0)); } /* Returns the number of empty squares adjacent to (x, y) */ int getDegree(int[] a, int x, int y) { int count = 0; for (int i = 0; i < N; ++i) if (isempty(a, (x + cx[i]), (y + cy[i]))) count++; return count; } // Picks next point using Warnsdorff's heuristic. // Returns false if it is not possible to pick // next point. Cell nextMove(int[] a, Cell cell) { int min_deg_idx = -1, c, min_deg = (N + 1), nx, ny; // Try all N adjacent of (*x, *y) starting // from a random adjacent. Find the adjacent // with minimum degree. Random random = new Random(); int start=random.Next(0, 1000); for (int count = 0; count < N; ++count) { int i = (start + count) % N; nx = cell.x + cx[i]; ny = cell.y + cy[i]; if ((isempty(a, nx, ny)) && (c = getDegree(a, nx, ny)) < min_deg) { min_deg_idx = i; min_deg = c; } } // IF we could not find a next cell if (min_deg_idx == -1) return null; // Store coordinates of next point nx = cell.x + cx[min_deg_idx]; ny = cell.y + cy[min_deg_idx]; // Mark next move a[ny * N + nx] = a[(cell.y) * N + (cell.x)] + 1; // Update next point cell.x = nx; cell.y = ny; return cell; } /* displays the chessboard with all the legal knight's moves */ void print(int[] a) { for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) Console.Write(a[j * N + i]+"\t"); Console.Write("\n"); } } /* checks its neighbouring squares */ /* If the knight ends on a square that is one knight's move from the beginning square, then tour is closed */ bool neighbour(int x, int y, int xx, int yy) { for (int i = 0; i < N; ++i) if (((x + cx[i]) == xx) && ((y + cy[i]) == yy)) return true; return false; } /* Generates the legal moves using warnsdorff's heuristics. Returns false if not possible */ bool findClosedTour() { // Filling up the chessboard matrix with -1's int[] a = new int[N * N]; for (int i = 0; i < N * N; ++i) a[i] = -1; // initial position int sx = 3; int sy = 2; // Current points are same as initial points Cell cell = new Cell(sx, sy); a[cell.y * N + cell.x] = 1; // Mark first move. // Keep picking next points using // Warnsdorff's heuristic Cell ret = null; for (int i = 0; i < N * N - 1; ++i) { ret = nextMove(a, cell); if (ret == null) return false; } // Check if tour is closed (Can end // at starting point) if (!neighbour(ret.x, ret.y, sx, sy)) return false; print(a); return true; } static public void Main (){ // While we don't get a solution while (!new GFG().findClosedTour()) { ; } }} class Cell{ public int x; public int y; public Cell(int x, int y) { this.x = x; this.y = y; }} //This code is contributed by shruti456rawal
Output:
59 14 63 32 1 16 19 34
62 31 60 15 56 33 2 17
13 58 55 64 49 18 35 20
30 61 42 57 54 51 40 3
43 12 53 50 41 48 21 36
26 29 44 47 52 39 4 7
11 46 27 24 9 6 37 22
28 25 10 45 38 23 8 5
The Hamiltonian path problem is NP-hard in general. In practice, Warnsdorff’s heuristic successfully finds a solution in linear time.
Do you know? “On an 8 × 8 board, there are exactly 26,534,728,821,064 directed closed tours (i.e. two tours along the same path that travel in opposite directions are counted separately, as are rotations and reflections). The number of undirected closed tours is half this number, since every tour can be traced in reverse!”
This article is contributed by Uddalak Bhaduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SaeedZarinfam
rajeev0719singh
anikakapoor
varshagumber28
simmytarika5
shruti456rawal
chessboard-problems
Backtracking
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Print all paths from a given source to a destination
Generate all the binary strings of N bits
Print all permutations of a string in Java
Find if there is a path of more than k length from a source
Recursive program to generate power set
Find Maximum number possible by doing at-most K swaps
Remove Invalid Parentheses
Difference between Backtracking and Branch-N-Bound technique
Find all distinct subsets of a given set using BitMasking Approach
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 203,
"s": 54,
"text": "Problem : A knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once. "
},
{
"code": null,
"e": 383,
"s": 203,
"text": "Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight. "
},
{
"code": null,
"e": 525,
"s": 383,
"text": "We have discussed Backtracking Algorithm for solution of Knight’s tour. In this post Warnsdorff’s heuristic is discussed. Warnsdorff’s Rule: "
},
{
"code": null,
"e": 699,
"s": 525,
"text": "We can start from any initial position of the knight on the board.We always move to an adjacent, unvisited square with minimal degree (minimum number of unvisited adjacent)."
},
{
"code": null,
"e": 766,
"s": 699,
"text": "We can start from any initial position of the knight on the board."
},
{
"code": null,
"e": 874,
"s": 766,
"text": "We always move to an adjacent, unvisited square with minimal degree (minimum number of unvisited adjacent)."
},
{
"code": null,
"e": 939,
"s": 874,
"text": "This algorithm may also more generally be applied to any graph. "
},
{
"code": null,
"e": 959,
"s": 939,
"text": "Some definitions: "
},
{
"code": null,
"e": 1082,
"s": 959,
"text": "A position Q is accessible from a position P if P can move to Q by a single Knight’s move, and Q has not yet been visited."
},
{
"code": null,
"e": 1162,
"s": 1082,
"text": "The accessibility of a position P is the number of positions accessible from P."
},
{
"code": null,
"e": 1175,
"s": 1162,
"text": "Algorithm: "
},
{
"code": null,
"e": 1599,
"s": 1175,
"text": "Set P to be a random initial position on the boardMark the board at P with the move number “1”Do following for each move number from 2 to the number of squares on the board: let S be the set of positions accessible from P.Set P to be the position in S with minimum accessibilityMark the board at P with the current move numberReturn the marked board — each square will be marked with the move number on which it is visited."
},
{
"code": null,
"e": 1650,
"s": 1599,
"text": "Set P to be a random initial position on the board"
},
{
"code": null,
"e": 1695,
"s": 1650,
"text": "Mark the board at P with the move number “1”"
},
{
"code": null,
"e": 1928,
"s": 1695,
"text": "Do following for each move number from 2 to the number of squares on the board: let S be the set of positions accessible from P.Set P to be the position in S with minimum accessibilityMark the board at P with the current move number"
},
{
"code": null,
"e": 1977,
"s": 1928,
"text": "let S be the set of positions accessible from P."
},
{
"code": null,
"e": 2034,
"s": 1977,
"text": "Set P to be the position in S with minimum accessibility"
},
{
"code": null,
"e": 2083,
"s": 2034,
"text": "Mark the board at P with the current move number"
},
{
"code": null,
"e": 2181,
"s": 2083,
"text": "Return the marked board — each square will be marked with the move number on which it is visited."
},
{
"code": null,
"e": 2227,
"s": 2181,
"text": "Below is implementation of above algorithm. "
},
{
"code": null,
"e": 2231,
"s": 2227,
"text": "C++"
},
{
"code": null,
"e": 2236,
"s": 2231,
"text": "Java"
},
{
"code": null,
"e": 2239,
"s": 2236,
"text": "C#"
},
{
"code": "// C++ program to for Knight's tour problem using// Warnsdorff's algorithm#include <bits/stdc++.h>#define N 8 // Move pattern on basis of the change of// x coordinates and y coordinates respectivelystatic int cx[N] = {1,1,2,2,-1,-1,-2,-2};static int cy[N] = {2,-2,1,-1,2,-2,1,-1}; // function restricts the knight to remain within// the 8x8 chessboardbool limits(int x, int y){ return ((x >= 0 && y >= 0) && (x < N && y < N));} /* Checks whether a square is valid and empty or not */bool isempty(int a[], int x, int y){ return (limits(x, y)) && (a[y*N+x] < 0);} /* Returns the number of empty squares adjacent to (x, y) */int getDegree(int a[], int x, int y){ int count = 0; for (int i = 0; i < N; ++i) if (isempty(a, (x + cx[i]), (y + cy[i]))) count++; return count;} // Picks next point using Warnsdorff's heuristic.// Returns false if it is not possible to pick// next point.bool nextMove(int a[], int *x, int *y){ int min_deg_idx = -1, c, min_deg = (N+1), nx, ny; // Try all N adjacent of (*x, *y) starting // from a random adjacent. Find the adjacent // with minimum degree. int start = rand()%N; for (int count = 0; count < N; ++count) { int i = (start + count)%N; nx = *x + cx[i]; ny = *y + cy[i]; if ((isempty(a, nx, ny)) && (c = getDegree(a, nx, ny)) < min_deg) { min_deg_idx = i; min_deg = c; } } // IF we could not find a next cell if (min_deg_idx == -1) return false; // Store coordinates of next point nx = *x + cx[min_deg_idx]; ny = *y + cy[min_deg_idx]; // Mark next move a[ny*N + nx] = a[(*y)*N + (*x)]+1; // Update next point *x = nx; *y = ny; return true;} /* displays the chessboard with all the legal knight's moves */void print(int a[]){ for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) printf(\"%d\\t\",a[j*N+i]); printf(\"\\n\"); }} /* checks its neighbouring squares *//* If the knight ends on a square that is one knight's move from the beginning square, then tour is closed */bool neighbour(int x, int y, int xx, int yy){ for (int i = 0; i < N; ++i) if (((x+cx[i]) == xx)&&((y + cy[i]) == yy)) return true; return false;} /* Generates the legal moves using warnsdorff's heuristics. Returns false if not possible */bool findClosedTour(){ // Filling up the chessboard matrix with -1's int a[N*N]; for (int i = 0; i< N*N; ++i) a[i] = -1; // Random initial position int sx = rand()%N; int sy = rand()%N; // Current points are same as initial points int x = sx, y = sy; a[y*N+x] = 1; // Mark first move. // Keep picking next points using // Warnsdorff's heuristic for (int i = 0; i < N*N-1; ++i) if (nextMove(a, &x, &y) == 0) return false; // Check if tour is closed (Can end // at starting point) if (!neighbour(x, y, sx, sy)) return false; print(a); return true;} // Driver codeint main(){ // To make sure that different random // initial positions are picked. srand(time(NULL)); // While we don't get a solution while (!findClosedTour()) { ; } return 0;}",
"e": 5483,
"s": 2239,
"text": null
},
{
"code": "// Java program to for Knight's tour problem using// Warnsdorff's algorithmimport java.util.concurrent.ThreadLocalRandom; class GFG{ public static final int N = 8; // Move pattern on basis of the change of // x coordinates and y coordinates respectively public static final int cx[] = {1, 1, 2, 2, -1, -1, -2, -2}; public static final int cy[] = {2, -2, 1, -1, 2, -2, 1, -1}; // function restricts the knight to remain within // the 8x8 chessboard boolean limits(int x, int y) { return ((x >= 0 && y >= 0) && (x < N && y < N)); } /* Checks whether a square is valid and empty or not */ boolean isempty(int a[], int x, int y) { return (limits(x, y)) && (a[y * N + x] < 0); } /* Returns the number of empty squares adjacent to (x, y) */ int getDegree(int a[], int x, int y) { int count = 0; for (int i = 0; i < N; ++i) if (isempty(a, (x + cx[i]), (y + cy[i]))) count++; return count; } // Picks next point using Warnsdorff's heuristic. // Returns false if it is not possible to pick // next point. Cell nextMove(int a[], Cell cell) { int min_deg_idx = -1, c, min_deg = (N + 1), nx, ny; // Try all N adjacent of (*x, *y) starting // from a random adjacent. Find the adjacent // with minimum degree. int start = ThreadLocalRandom.current().nextInt(1000) % N; for (int count = 0; count < N; ++count) { int i = (start + count) % N; nx = cell.x + cx[i]; ny = cell.y + cy[i]; if ((isempty(a, nx, ny)) && (c = getDegree(a, nx, ny)) < min_deg) { min_deg_idx = i; min_deg = c; } } // IF we could not find a next cell if (min_deg_idx == -1) return null; // Store coordinates of next point nx = cell.x + cx[min_deg_idx]; ny = cell.y + cy[min_deg_idx]; // Mark next move a[ny * N + nx] = a[(cell.y) * N + (cell.x)] + 1; // Update next point cell.x = nx; cell.y = ny; return cell; } /* displays the chessboard with all the legal knight's moves */ void print(int a[]) { for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) System.out.printf(\"%d\\t\", a[j * N + i]); System.out.printf(\"\\n\"); } } /* checks its neighbouring squares */ /* If the knight ends on a square that is one knight's move from the beginning square, then tour is closed */ boolean neighbour(int x, int y, int xx, int yy) { for (int i = 0; i < N; ++i) if (((x + cx[i]) == xx) && ((y + cy[i]) == yy)) return true; return false; } /* Generates the legal moves using warnsdorff's heuristics. Returns false if not possible */ boolean findClosedTour() { // Filling up the chessboard matrix with -1's int a[] = new int[N * N]; for (int i = 0; i < N * N; ++i) a[i] = -1; // initial position int sx = 3; int sy = 2; // Current points are same as initial points Cell cell = new Cell(sx, sy); a[cell.y * N + cell.x] = 1; // Mark first move. // Keep picking next points using // Warnsdorff's heuristic Cell ret = null; for (int i = 0; i < N * N - 1; ++i) { ret = nextMove(a, cell); if (ret == null) return false; } // Check if tour is closed (Can end // at starting point) if (!neighbour(ret.x, ret.y, sx, sy)) return false; print(a); return true; } // Driver Code public static void main(String[] args) { // While we don't get a solution while (!new GFG().findClosedTour()) { ; } }} class Cell{ int x; int y; public Cell(int x, int y) { this.x = x; this.y = y; }} // This code is contributed by SaeedZarinfam",
"e": 9678,
"s": 5483,
"text": null
},
{
"code": "//C# program for Knight’s tour //problem using Warnsdorff’salgorithmusing System;using System.Collections;using System.Collections.Generic; public class GFG{ public static int N = 8; // Move pattern on basis of the change of // x coordinates and y coordinates respectively public int[] cx = new int[] {1, 1, 2, 2, -1, -1, -2, -2}; public int[] cy = new int[] {2, -2, 1, -1, 2, -2, 1, -1}; // function restricts the knight to remain within // the 8x8 chessboard bool limits(int x, int y) { return ((x >= 0 && y >= 0) && (x < N && y < N)); } /* Checks whether a square is valid and empty or not */ bool isempty(int[] a, int x, int y) { return ((limits(x, y)) && (a[y * N + x] < 0)); } /* Returns the number of empty squares adjacent to (x, y) */ int getDegree(int[] a, int x, int y) { int count = 0; for (int i = 0; i < N; ++i) if (isempty(a, (x + cx[i]), (y + cy[i]))) count++; return count; } // Picks next point using Warnsdorff's heuristic. // Returns false if it is not possible to pick // next point. Cell nextMove(int[] a, Cell cell) { int min_deg_idx = -1, c, min_deg = (N + 1), nx, ny; // Try all N adjacent of (*x, *y) starting // from a random adjacent. Find the adjacent // with minimum degree. Random random = new Random(); int start=random.Next(0, 1000); for (int count = 0; count < N; ++count) { int i = (start + count) % N; nx = cell.x + cx[i]; ny = cell.y + cy[i]; if ((isempty(a, nx, ny)) && (c = getDegree(a, nx, ny)) < min_deg) { min_deg_idx = i; min_deg = c; } } // IF we could not find a next cell if (min_deg_idx == -1) return null; // Store coordinates of next point nx = cell.x + cx[min_deg_idx]; ny = cell.y + cy[min_deg_idx]; // Mark next move a[ny * N + nx] = a[(cell.y) * N + (cell.x)] + 1; // Update next point cell.x = nx; cell.y = ny; return cell; } /* displays the chessboard with all the legal knight's moves */ void print(int[] a) { for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) Console.Write(a[j * N + i]+\"\\t\"); Console.Write(\"\\n\"); } } /* checks its neighbouring squares */ /* If the knight ends on a square that is one knight's move from the beginning square, then tour is closed */ bool neighbour(int x, int y, int xx, int yy) { for (int i = 0; i < N; ++i) if (((x + cx[i]) == xx) && ((y + cy[i]) == yy)) return true; return false; } /* Generates the legal moves using warnsdorff's heuristics. Returns false if not possible */ bool findClosedTour() { // Filling up the chessboard matrix with -1's int[] a = new int[N * N]; for (int i = 0; i < N * N; ++i) a[i] = -1; // initial position int sx = 3; int sy = 2; // Current points are same as initial points Cell cell = new Cell(sx, sy); a[cell.y * N + cell.x] = 1; // Mark first move. // Keep picking next points using // Warnsdorff's heuristic Cell ret = null; for (int i = 0; i < N * N - 1; ++i) { ret = nextMove(a, cell); if (ret == null) return false; } // Check if tour is closed (Can end // at starting point) if (!neighbour(ret.x, ret.y, sx, sy)) return false; print(a); return true; } static public void Main (){ // While we don't get a solution while (!new GFG().findClosedTour()) { ; } }} class Cell{ public int x; public int y; public Cell(int x, int y) { this.x = x; this.y = y; }} //This code is contributed by shruti456rawal",
"e": 13876,
"s": 9678,
"text": null
},
{
"code": null,
"e": 13885,
"s": 13876,
"text": "Output: "
},
{
"code": null,
"e": 14268,
"s": 13885,
"text": "59 14 63 32 1 16 19 34 \n62 31 60 15 56 33 2 17 \n13 58 55 64 49 18 35 20 \n30 61 42 57 54 51 40 3 \n43 12 53 50 41 48 21 36 \n26 29 44 47 52 39 4 7 \n11 46 27 24 9 6 37 22 \n28 25 10 45 38 23 8 5 "
},
{
"code": null,
"e": 14402,
"s": 14268,
"text": "The Hamiltonian path problem is NP-hard in general. In practice, Warnsdorff’s heuristic successfully finds a solution in linear time."
},
{
"code": null,
"e": 14727,
"s": 14402,
"text": "Do you know? “On an 8 × 8 board, there are exactly 26,534,728,821,064 directed closed tours (i.e. two tours along the same path that travel in opposite directions are counted separately, as are rotations and reflections). The number of undirected closed tours is half this number, since every tour can be traced in reverse!”"
},
{
"code": null,
"e": 15151,
"s": 14727,
"text": "This article is contributed by Uddalak Bhaduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 15165,
"s": 15151,
"text": "SaeedZarinfam"
},
{
"code": null,
"e": 15181,
"s": 15165,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 15193,
"s": 15181,
"text": "anikakapoor"
},
{
"code": null,
"e": 15208,
"s": 15193,
"text": "varshagumber28"
},
{
"code": null,
"e": 15221,
"s": 15208,
"text": "simmytarika5"
},
{
"code": null,
"e": 15236,
"s": 15221,
"text": "shruti456rawal"
},
{
"code": null,
"e": 15256,
"s": 15236,
"text": "chessboard-problems"
},
{
"code": null,
"e": 15269,
"s": 15256,
"text": "Backtracking"
},
{
"code": null,
"e": 15282,
"s": 15269,
"text": "Backtracking"
},
{
"code": null,
"e": 15380,
"s": 15282,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15465,
"s": 15380,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 15518,
"s": 15465,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 15560,
"s": 15518,
"text": "Generate all the binary strings of N bits"
},
{
"code": null,
"e": 15603,
"s": 15560,
"text": "Print all permutations of a string in Java"
},
{
"code": null,
"e": 15663,
"s": 15603,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 15703,
"s": 15663,
"text": "Recursive program to generate power set"
},
{
"code": null,
"e": 15757,
"s": 15703,
"text": "Find Maximum number possible by doing at-most K swaps"
},
{
"code": null,
"e": 15784,
"s": 15757,
"text": "Remove Invalid Parentheses"
},
{
"code": null,
"e": 15845,
"s": 15784,
"text": "Difference between Backtracking and Branch-N-Bound technique"
}
] |
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
|
22 Aug, 2019
What is a Corner?A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness).
Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper ‘Good Features to Track‘. Here the basic intuition is that corners can be detected by looking for significant change in all direction.
We consider a small window on the image then scan the whole image, looking for corners.
Shifting this small window in any direction would result in a large change in appearance, if that particular window happens to be located on a corner.
Flat regions will have no change in any direction.
If there’s an edge, then there will be no major change along the edge direction.
For a window(W) located at (X, Y) with pixel intensity I(X, Y), formula for Shi-Tomasi Corner Detection is –
f(X, Y) = Σ (I(Xk, Yk) - I(Xk + ΔX, Yk + ΔY))2 where (Xk, Yk) ε W
According to the formula:If we’re scanning the image with a window just as we would with a kernel and we notice that there is an area where there’s a major change no matter in what direction we actually scan, then we have a good intuition that there’s probably a corner there.Calculation of f(X, Y) will be really slow. Hence, we use Taylor expansion to simplify the scoring function, R.
R = min(λ1, λ2)
where λ1, λ2 are eigenvalues of resultant matrix
Using goodFeaturesToTrack() function –
Syntax : cv2.goodFeaturesToTrack(gray_img, maxc, Q, minD)
Parameters :gray_img – Grayscale image with integral valuesmaxc – Maximum number of corners we want(give negative value to get all the corners)Q – Quality level parameter(preferred value=0.01)maxD – Maximum distance(preferred value=10)
# Python program to illustrate # corner detection with # Shi-Tomasi Detection Method # organizing imports import cv2import numpy as npimport matplotlib.pyplot as plt%matplotlib inline # path to input image specified and # image is loaded with imread commandimg = cv2.imread('chess.png') # convert image to grayscalegray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Shi-Tomasi corner detection function# We are detecting only 100 best corners here# You can change the number to get desired result.corners = cv2.goodFeaturesToTrack(gray_img, 100, 0.01, 10) # convert corners values to integer# So that we will be able to draw circles on themcorners = np.int0(corners) # draw red color circles on all cornersfor i in corners: x, y = i.ravel() cv2.circle(img, (x, y), 3, (255, 0, 0), -1) # resulting imageplt.imshow(img) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()
Input :
Output :
hachiman_20
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Aug, 2019"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "What is a Corner?A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness)."
},
{
"code": null,
"e": 372,
"s": 158,
"text": "Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper ‘Good Features to Track‘. Here the basic intuition is that corners can be detected by looking for significant change in all direction."
},
{
"code": null,
"e": 460,
"s": 372,
"text": "We consider a small window on the image then scan the whole image, looking for corners."
},
{
"code": null,
"e": 611,
"s": 460,
"text": "Shifting this small window in any direction would result in a large change in appearance, if that particular window happens to be located on a corner."
},
{
"code": null,
"e": 662,
"s": 611,
"text": "Flat regions will have no change in any direction."
},
{
"code": null,
"e": 743,
"s": 662,
"text": "If there’s an edge, then there will be no major change along the edge direction."
},
{
"code": null,
"e": 852,
"s": 743,
"text": "For a window(W) located at (X, Y) with pixel intensity I(X, Y), formula for Shi-Tomasi Corner Detection is –"
},
{
"code": null,
"e": 919,
"s": 852,
"text": "f(X, Y) = Σ (I(Xk, Yk) - I(Xk + ΔX, Yk + ΔY))2 where (Xk, Yk) ε W"
},
{
"code": null,
"e": 1307,
"s": 919,
"text": "According to the formula:If we’re scanning the image with a window just as we would with a kernel and we notice that there is an area where there’s a major change no matter in what direction we actually scan, then we have a good intuition that there’s probably a corner there.Calculation of f(X, Y) will be really slow. Hence, we use Taylor expansion to simplify the scoring function, R."
},
{
"code": null,
"e": 1372,
"s": 1307,
"text": "R = min(λ1, λ2)\nwhere λ1, λ2 are eigenvalues of resultant matrix"
},
{
"code": null,
"e": 1411,
"s": 1372,
"text": "Using goodFeaturesToTrack() function –"
},
{
"code": null,
"e": 1469,
"s": 1411,
"text": "Syntax : cv2.goodFeaturesToTrack(gray_img, maxc, Q, minD)"
},
{
"code": null,
"e": 1705,
"s": 1469,
"text": "Parameters :gray_img – Grayscale image with integral valuesmaxc – Maximum number of corners we want(give negative value to get all the corners)Q – Quality level parameter(preferred value=0.01)maxD – Maximum distance(preferred value=10)"
},
{
"code": "# Python program to illustrate # corner detection with # Shi-Tomasi Detection Method # organizing imports import cv2import numpy as npimport matplotlib.pyplot as plt%matplotlib inline # path to input image specified and # image is loaded with imread commandimg = cv2.imread('chess.png') # convert image to grayscalegray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Shi-Tomasi corner detection function# We are detecting only 100 best corners here# You can change the number to get desired result.corners = cv2.goodFeaturesToTrack(gray_img, 100, 0.01, 10) # convert corners values to integer# So that we will be able to draw circles on themcorners = np.int0(corners) # draw red color circles on all cornersfor i in corners: x, y = i.ravel() cv2.circle(img, (x, y), 3, (255, 0, 0), -1) # resulting imageplt.imshow(img) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()",
"e": 2643,
"s": 1705,
"text": null
},
{
"code": null,
"e": 2651,
"s": 2643,
"text": "Input :"
},
{
"code": null,
"e": 2660,
"s": 2651,
"text": "Output :"
},
{
"code": null,
"e": 2672,
"s": 2660,
"text": "hachiman_20"
},
{
"code": null,
"e": 2689,
"s": 2672,
"text": "Image-Processing"
},
{
"code": null,
"e": 2696,
"s": 2689,
"text": "OpenCV"
},
{
"code": null,
"e": 2703,
"s": 2696,
"text": "Python"
}
] |
Python | Numpy numpy.ndarray.__add__()
|
06 Mar, 2019
With the help of Numpy numpy.ndarray.__add__(), we can add a particular value that is provided as a parameter in the ndarray.__add__() method. Value will be added to each and every element in a numpy array.
Syntax: ndarray.__add__($self, value, /)
Return: self+value
Example #1 :In this example we can see that each and every element in an array is added with the value given as a parameter in method ndarray.__add__(). Remember one thing it wouldn’t work for double type values.
# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__add__() methodprint(gfg.__add__(5))
[ 6 7 8 9 10]
Example #2 :
# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([[1, 2, 3, 4, 5], [6, 5, 4, 3, 2]]) # applying ndarray.__add__() methodprint(gfg.__add__(5))
[[ 6 7 8 9 10]
[11 10 9 8 7]]
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Mar, 2019"
},
{
"code": null,
"e": 235,
"s": 28,
"text": "With the help of Numpy numpy.ndarray.__add__(), we can add a particular value that is provided as a parameter in the ndarray.__add__() method. Value will be added to each and every element in a numpy array."
},
{
"code": null,
"e": 276,
"s": 235,
"text": "Syntax: ndarray.__add__($self, value, /)"
},
{
"code": null,
"e": 295,
"s": 276,
"text": "Return: self+value"
},
{
"code": null,
"e": 508,
"s": 295,
"text": "Example #1 :In this example we can see that each and every element in an array is added with the value given as a parameter in method ndarray.__add__(). Remember one thing it wouldn’t work for double type values."
},
{
"code": "# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__add__() methodprint(gfg.__add__(5))",
"e": 685,
"s": 508,
"text": null
},
{
"code": null,
"e": 704,
"s": 685,
"text": "[ 6 7 8 9 10]\n"
},
{
"code": null,
"e": 717,
"s": 704,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([[1, 2, 3, 4, 5], [6, 5, 4, 3, 2]]) # applying ndarray.__add__() methodprint(gfg.__add__(5))",
"e": 928,
"s": 717,
"text": null
},
{
"code": null,
"e": 968,
"s": 928,
"text": "[[ 6 7 8 9 10]\n [11 10 9 8 7]]\n"
},
{
"code": null,
"e": 989,
"s": 968,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 1002,
"s": 989,
"text": "Python-numpy"
},
{
"code": null,
"e": 1009,
"s": 1002,
"text": "Python"
},
{
"code": null,
"e": 1107,
"s": 1009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1125,
"s": 1107,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1167,
"s": 1125,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1202,
"s": 1167,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1228,
"s": 1202,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1260,
"s": 1228,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1289,
"s": 1260,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1316,
"s": 1289,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1337,
"s": 1316,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1373,
"s": 1337,
"text": "Convert integer to string in Python"
}
] |
Write HashMap to a Text File in Java
|
28 Dec, 2020
The HashMap class in Java implements the Serializable interface so that its objects can be written or serialized to a file using the ObjectOutputStream. However, the output file it produces is not in the human-readable format and may contain junk characters.
Serialization: It is a process of writing an Object into a file along with its attributes and content. It internally converts the object into a stream of bytes.
De-Serialization: It is a process of reading the Object and its properties from a file along with the Object’s content.
If we want to write a HashMap object to a plain text file, we need a simple and understandable code to write on the HashMap and then insert the Map into the Text File. We can write the code in the form of key-Value Pair of a map Object to a File and each line File will contain the Key-Value Pair
Approach
In the below class we are storing the HashMap content in a hashmap.ser serialized file.
Once when we run the below code it would produce a hashmap.ser file. This file would be used in the next class for de-serialization.
The hashmap.ser serialised file can be Stored to any Location with describing it’s Location Like Below
So we need the Location to write the HashMap in it.
So for that need to Provide the External Location to Store the HashMap
final static String outputFilePath = "F:/Serialisation/write.txt";
Create the HashMap of String Key and String Value Pair
HashMap<String, String> map = new HashMap<String, String>();
Create the File Object:
File file = new File(outputFilePath);
Using the file object we will write the HashMap input using the function BufferedWriter(File_Path)
bf = new BufferedWriter( new FileWriter(file));
and then at last close the File
bf.close();
Writing to File
Java
// Java program to write HashMap to a file import java.io.*;import java.util.*; class GFG { final static String outputFilePath = "F:/Serialisation/write.txt"; public static void main(String[] args) { // create new HashMap HashMap<String, String> map = new HashMap<String, String>(); // key-value pairs map.put("rohit", "one"); map.put("Sam", "two"); map.put("jainie", "three"); // new file object File file = new File(outputFilePath); BufferedWriter bf = null; try { // create new BufferedWriter for the output file bf = new BufferedWriter(new FileWriter(file)); // iterate map entries for (Map.Entry<String, String> entry : map.entrySet()) { // put key and value separated by a colon bf.write(entry.getKey() + ":" + entry.getValue()); // new line bf.newLine(); } bf.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { // always close the writer bf.close(); } catch (Exception e) { } } }}
Output:
Java-HashMap
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 287,
"s": 28,
"text": "The HashMap class in Java implements the Serializable interface so that its objects can be written or serialized to a file using the ObjectOutputStream. However, the output file it produces is not in the human-readable format and may contain junk characters."
},
{
"code": null,
"e": 448,
"s": 287,
"text": "Serialization: It is a process of writing an Object into a file along with its attributes and content. It internally converts the object into a stream of bytes."
},
{
"code": null,
"e": 568,
"s": 448,
"text": "De-Serialization: It is a process of reading the Object and its properties from a file along with the Object’s content."
},
{
"code": null,
"e": 865,
"s": 568,
"text": "If we want to write a HashMap object to a plain text file, we need a simple and understandable code to write on the HashMap and then insert the Map into the Text File. We can write the code in the form of key-Value Pair of a map Object to a File and each line File will contain the Key-Value Pair"
},
{
"code": null,
"e": 874,
"s": 865,
"text": "Approach"
},
{
"code": null,
"e": 962,
"s": 874,
"text": "In the below class we are storing the HashMap content in a hashmap.ser serialized file."
},
{
"code": null,
"e": 1095,
"s": 962,
"text": "Once when we run the below code it would produce a hashmap.ser file. This file would be used in the next class for de-serialization."
},
{
"code": null,
"e": 1198,
"s": 1095,
"text": "The hashmap.ser serialised file can be Stored to any Location with describing it’s Location Like Below"
},
{
"code": null,
"e": 1250,
"s": 1198,
"text": "So we need the Location to write the HashMap in it."
},
{
"code": null,
"e": 1322,
"s": 1250,
"text": "So for that need to Provide the External Location to Store the HashMap "
},
{
"code": null,
"e": 1389,
"s": 1322,
"text": "final static String outputFilePath = \"F:/Serialisation/write.txt\";"
},
{
"code": null,
"e": 1444,
"s": 1389,
"text": "Create the HashMap of String Key and String Value Pair"
},
{
"code": null,
"e": 1505,
"s": 1444,
"text": "HashMap<String, String> map = new HashMap<String, String>();"
},
{
"code": null,
"e": 1529,
"s": 1505,
"text": "Create the File Object:"
},
{
"code": null,
"e": 1567,
"s": 1529,
"text": "File file = new File(outputFilePath);"
},
{
"code": null,
"e": 1666,
"s": 1567,
"text": "Using the file object we will write the HashMap input using the function BufferedWriter(File_Path)"
},
{
"code": null,
"e": 1715,
"s": 1666,
"text": " bf = new BufferedWriter( new FileWriter(file));"
},
{
"code": null,
"e": 1748,
"s": 1715,
"text": "and then at last close the File "
},
{
"code": null,
"e": 1761,
"s": 1748,
"text": " bf.close();"
},
{
"code": null,
"e": 1778,
"s": 1761,
"text": "Writing to File "
},
{
"code": null,
"e": 1783,
"s": 1778,
"text": "Java"
},
{
"code": "// Java program to write HashMap to a file import java.io.*;import java.util.*; class GFG { final static String outputFilePath = \"F:/Serialisation/write.txt\"; public static void main(String[] args) { // create new HashMap HashMap<String, String> map = new HashMap<String, String>(); // key-value pairs map.put(\"rohit\", \"one\"); map.put(\"Sam\", \"two\"); map.put(\"jainie\", \"three\"); // new file object File file = new File(outputFilePath); BufferedWriter bf = null; try { // create new BufferedWriter for the output file bf = new BufferedWriter(new FileWriter(file)); // iterate map entries for (Map.Entry<String, String> entry : map.entrySet()) { // put key and value separated by a colon bf.write(entry.getKey() + \":\" + entry.getValue()); // new line bf.newLine(); } bf.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { // always close the writer bf.close(); } catch (Exception e) { } } }}",
"e": 3110,
"s": 1783,
"text": null
},
{
"code": null,
"e": 3118,
"s": 3110,
"text": "Output:"
},
{
"code": null,
"e": 3131,
"s": 3118,
"text": "Java-HashMap"
},
{
"code": null,
"e": 3138,
"s": 3131,
"text": "Picked"
},
{
"code": null,
"e": 3162,
"s": 3138,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3167,
"s": 3162,
"text": "Java"
},
{
"code": null,
"e": 3181,
"s": 3167,
"text": "Java Programs"
},
{
"code": null,
"e": 3200,
"s": 3181,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3205,
"s": 3200,
"text": "Java"
}
] |
N Queen Problem using Branch And Bound
|
04 Jul, 2022
The N queens puzzle is the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal.
Backtracking Algorithm for N-Queen is already discussed here. In backtracking solution we backtrack when we hit a dead end. In Branch and Bound solution, after building a partial solution, we figure out that there is no point going any deeper as we are going to hit a dead end.
Let’s begin by describing backtracking solution. “The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes, then we backtrack and return false.”
For the 1st Queen, there are total 8 possibilities as we can place 1st Queen in any row of first column. Let’s place Queen 1 on row 3.After placing 1st Queen, there are 7 possibilities left for the 2nd Queen. But wait, we don’t really have 7 possibilities. We cannot place Queen 2 on rows 2, 3 or 4 as those cells are under attack from Queen 1. So, Queen 2 has only 8 – 3 = 5 valid positions left.After picking a position for Queen 2, Queen 3 has even fewer options as most of the cells in its column are under attack from the first 2 Queens.
For the 1st Queen, there are total 8 possibilities as we can place 1st Queen in any row of first column. Let’s place Queen 1 on row 3.
After placing 1st Queen, there are 7 possibilities left for the 2nd Queen. But wait, we don’t really have 7 possibilities. We cannot place Queen 2 on rows 2, 3 or 4 as those cells are under attack from Queen 1. So, Queen 2 has only 8 – 3 = 5 valid positions left.
After picking a position for Queen 2, Queen 3 has even fewer options as most of the cells in its column are under attack from the first 2 Queens.
We need to figure out an efficient way of keeping track of which cells are under attack. In previous solution we kept an 8-by-8 Boolean matrix and update it each time we placed a queen, but that required linear time to update as we need to check for safe cells.Basically, we have to ensure 4 things: 1. No two queens share a column. 2. No two queens share a row. 3. No two queens share a top-right to left-bottom diagonal. 4. No two queens share a top-left to bottom-right diagonal.
Number 1 is automatic because of the way we store the solution. For number 2, 3 and 4, we can perform updates in O(1) time. The idea is to keep three Boolean arrays that tell us which rows and which diagonals are occupied.
Lets do some pre-processing first. Let’s create two N x N matrix one for / diagonal and other one for \ diagonal. Let’s call them slashCode and backslashCode respectively. The trick is to fill them in such a way that two queens sharing a same /diagonal will have the same value in matrix slashCode, and if they share same \diagonal, they will have the same value in backslashCode matrix.For an N x N matrix, fill slashCode and backslashCode matrix using below formula –slashCode[row][col] = row + col backslashCode[row][col] = row – col + (N-1)
Using above formula will result in below matrices
The ‘N – 1’ in the backslash code is there to ensure that the codes are never negative because we will be using the codes as indices in an array.Now before we place queen i on row j, we first check whether row j is used (use an array to store row info). Then we check whether slash code ( j + i ) or backslash code ( j – i + 7 ) are used (keep two arrays that will tell us which diagonals are occupied). If yes, then we have to try a different location for queen i. If not, then we mark the row and the two diagonals as used and recurse on queen i + 1. After the recursive call returns and before we try another position for queen i, we need to reset the row, slash code and backslash code as unused again, like in the code from the previous notes.
Below is the implementation of above idea –
This code Takes the Dynamic Input:
C++
C
Java
Python3
Javascript
#include<bits/stdc++.h>using namespace std;int N; // function for printing the solutionvoid printSol(vector<vector<int>>board){ for(int i = 0;i<N;i++){ for(int j = 0;j<N;j++){ cout<<board[i][j]<<" "; } cout<<"\n"; }} /* Optimized isSafe functionisSafe function to check if current row contins or current left diagonal or current right diagonal contains any queen or not if yes return false else return true*/ bool isSafe(int row ,int col ,vector<bool>rows , vector<bool>left_digonals ,vector<bool>Right_digonals){ if(rows[row] == true || left_digonals[row+col] == true || Right_digonals[col-row+N-1] == true){ return false; } return true;} // Recursive function to solve N-queen Problembool solve(vector<vector<int>>& board ,int col ,vector<bool>rows , vector<bool>left_digonals ,vector<bool>Right_digonals){ // base Case : If all Queens are placed if(col>=N){ return true; } /* Consider this Column and move in all rows one by one */ for(int i = 0;i<N;i++) { if(isSafe(i,col,rows,left_digonals,Right_digonals) == true) { rows[i] = true; left_digonals[i+col] = true; Right_digonals[col-i+N-1] = true; board[i][col] = 1; // placing the Queen in board[i][col] /* recur to place rest of the queens */ if(solve(board,col+1,rows,left_digonals,Right_digonals) == true){ return true; } // Backtracking rows[i] = false; left_digonals[i+col] = false; Right_digonals[col-i+N-1] = false; board[i][col] = 0; // removing the Queen from board[i][col] } } return false;} int main(){ // Taking input from the user cout<<"Enter the no of rows for the square Board : "; cin>>N; // board of size N*N vector<vector<int>>board(N,vector<int>(N,0)); // array to tell which rows are occupied vector<bool>rows(N,false); // arrays to tell which diagonals are occupied vector<bool>left_digonals(2*N-1,false); vector<bool>Right_digonals(2*N-1,false); bool ans = solve(board , 0, rows,left_digonals,Right_digonals); if(ans == true){ // printing the solution Board printSol(board); } else{ cout<<"Solution Does not Exist\n"; }} // This Code is Contributed by Parshant Rajput
/* C++ program to solve N Queen Problem using Branch and Bound */#include<stdio.h>#include<string.h>#include<stdbool.h>#define N 8 /* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%2d ", board[i][j]); printf("\n"); }} /* A Optimized function to check if a queen canbe placed on board[row][col] */bool isSafe(int row, int col, int slashCode[N][N], int backslashCode[N][N], bool rowLookup[], bool slashCodeLookup[], bool backslashCodeLookup[] ){ if (slashCodeLookup[slashCode[row][col]] || backslashCodeLookup[backslashCode[row][col]] || rowLookup[row]) return false; return true;} /* A recursive utility functionto solve N Queen problem */bool solveNQueensUtil(int board[N][N], int col, int slashCode[N][N], int backslashCode[N][N], bool rowLookup[N], bool slashCodeLookup[], bool backslashCodeLookup[] ){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ if ( isSafe(i, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) ) { /* Place this queen in board[i][col] */ board[i][col] = 1; rowLookup[i] = true; slashCodeLookup[slashCode[i][col]] = true; backslashCodeLookup[backslashCode[i][col]] = true; /* recur to place rest of the queens */ if ( solveNQueensUtil(board, col + 1, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) ) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then backtrack */ /* Remove queen from board[i][col] */ board[i][col] = 0; rowLookup[i] = false; slashCodeLookup[slashCode[i][col]] = false; backslashCodeLookup[backslashCode[i][col]] = false; } } /* If queen can not be place in any row in this column col then return false */ return false;} /* This function solves the N Queen problem usingBranch and Bound. It mainly uses solveNQueensUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/bool solveNQueens(){ int board[N][N]; memset(board, 0, sizeof board); // helper matrices int slashCode[N][N]; int backslashCode[N][N]; // arrays to tell us which rows are occupied bool rowLookup[N] = {false}; //keep two arrays to tell us // which diagonals are occupied bool slashCodeLookup[2*N - 1] = {false}; bool backslashCodeLookup[2*N - 1] = {false}; // initialize helper matrices for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) { slashCode[r] = r + c, backslashCode[r] = r - c + 7; } if (solveNQueensUtil(board, 0, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) == false ) { printf("Solution does not exist"); return false; } // solution found printSolution(board); return true;} // Driver program to test above functionint main(){ solveNQueens(); return 0;}
// Java program to solve N Queen Problem// using Branch and Boundimport java.io.*;import java.util.Arrays; class GFG{ static int N = 8; // A utility function to print solutionstatic void printSolution(int board[][]){ int N = board.length; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) System.out.printf("%2d ", board[i][j]); System.out.printf("\n"); }} // A Optimized function to check if a queen// can be placed on board[row][col]static boolean isSafe(int row, int col, int slashCode[][], int backslashCode[][], boolean rowLookup[], boolean slashCodeLookup[], boolean backslashCodeLookup[]){ if (slashCodeLookup[slashCode[row][col]] || backslashCodeLookup[backslashCode[row][col]] || rowLookup[row]) return false; return true;} // A recursive utility function to// solve N Queen problemstatic boolean solveNQueensUtil( int board[][], int col, int slashCode[][], int backslashCode[][], boolean rowLookup[], boolean slashCodeLookup[], boolean backslashCodeLookup[]){ // Base case: If all queens are placed // then return true int N = board.length; if (col >= N) return true; // Consider this column and try placing // this queen in all rows one by one for(int i = 0; i < N; i++) { // Check if queen can be placed on board[i][col] if (isSafe(i, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)) { // Place this queen in board[i][col] board[i][col] = 1; rowLookup[i] = true; slashCodeLookup[slashCode[i][col]] = true; backslashCodeLookup[backslashCode[i][col]] = true; // recur to place rest of the queens if (solveNQueensUtil( board, col + 1, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)) return true; // If placing queen in board[i][col] doesn't // lead to a solution, then backtrack // Remove queen from board[i][col] board[i][col] = 0; rowLookup[i] = false; slashCodeLookup[slashCode[i][col]] = false; backslashCodeLookup[backslashCode[i][col]] = false; } } // If queen can not be place in any row // in this column col then return false return false;} /* * This function solves the N Queen problem using Branch * and Bound. It mainly uses solveNQueensUtil() to solve * the problem. It returns false if queens cannot be * placed, otherwise return true and prints placement of * queens in the form of 1s. Please note that there may * be more than one solutions, this function prints one * of the feasible solutions. */static boolean solveNQueens(){ int board[][] = new int[N][N]; // Helper matrices int slashCode[][] = new int[N][N]; int backslashCode[][] = new int[N][N]; // Arrays to tell us which rows are occupied boolean[] rowLookup = new boolean[N]; // Keep two arrays to tell us // which diagonals are occupied boolean slashCodeLookup[] = new boolean[2 * N - 1]; boolean backslashCodeLookup[] = new boolean[2 * N - 1]; // Initialize helper matrices for(int r = 0; r < N; r++) for(int c = 0; c < N; c++) { slashCode[r] = r + c; backslashCode[r] = r - c + 7; } if (solveNQueensUtil(board, 0, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) == false) { System.out.printf("Solution does not exist"); return false; } // Solution found printSolution(board); return true;} // Driver codepublic static void main(String[] args){ solveNQueens();}} // This code is contributed by sujitmeshram
""" Python3 program to solve N Queen Problemusing Branch or Bound """ N = 8 """ A utility function to print solution """def printSolution(board): for i in range(N): for j in range(N): print(board[i][j], end = " ") print() """ A Optimized function to check ifa queen can be placed on board[row][col] """def isSafe(row, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup): if (slashCodeLookup[slashCode[row][col]] or backslashCodeLookup[backslashCode[row][col]] or rowLookup[row]): return False return True """ A recursive utility function to solve N Queen problem """def solveNQueensUtil(board, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup): """ base case: If all queens are placed then return True """ if(col >= N): return True for i in range(N): if(isSafe(i, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)): """ Place this queen in board[i][col] """ board[i][col] = 1 rowLookup[i] = True slashCodeLookup[slashCode[i][col]] = True backslashCodeLookup[backslashCode[i][col]] = True """ recur to place rest of the queens """ if(solveNQueensUtil(board, col + 1, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)): return True """ If placing queen in board[i][col] doesn't lead to a solution,then backtrack """ """ Remove queen from board[i][col] """ board[i][col] = 0 rowLookup[i] = False slashCodeLookup[slashCode[i][col]] = False backslashCodeLookup[backslashCode[i][col]] = False """ If queen can not be place in any row in this column col then return False """ return False """ This function solves the N Queen problem usingBranch or Bound. It mainly uses solveNQueensUtil()tosolve the problem. It returns False if queenscannot be placed,otherwise return True orprints placement of queens in the form of 1s.Please note that there may be more than onesolutions,this function prints one of thefeasible solutions."""def solveNQueens(): board = [[0 for i in range(N)] for j in range(N)] # helper matrices slashCode = [[0 for i in range(N)] for j in range(N)] backslashCode = [[0 for i in range(N)] for j in range(N)] # arrays to tell us which rows are occupied rowLookup = [False] * N # keep two arrays to tell us # which diagonals are occupied x = 2 * N - 1 slashCodeLookup = [False] * x backslashCodeLookup = [False] * x # initialize helper matrices for rr in range(N): for cc in range(N): slashCode[rr][cc] = rr + cc backslashCode[rr][cc] = rr - cc + 7 if(solveNQueensUtil(board, 0, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) == False): print("Solution does not exist") return False # solution found printSolution(board) return True # Driver CdesolveNQueens() # This code is contributed by SHUBHAMSINGH10
<script> // JavaScript program to solve N Queen Problem// using Branch and Bound let N = 8; // A utility function to print solutionfunction printSolution(board){ let N = board.length; for(let i = 0; i < N; i++) { for(let j = 0; j < N; j++) document.write(board[i][j]+" "); document.write("<br>"); }} // A Optimized function to check if a queen// can be placed on board[row][col]function isSafe(row,col,slashCode,backslashCode,rowLookup,slashCodeLookup,backslashCodeLookup){ if (slashCodeLookup[slashCode[row][col]] || backslashCodeLookup[backslashCode[row][col]] || rowLookup[row]) return false; return true;} // A recursive utility function to// solve N Queen problemfunction solveNQueensUtil(board,col,slashCode,backslashCode,rowLookup,slashCodeLookup,backslashCodeLookup){ // Base case: If all queens are placed // then return true //let N = board.length; if (col >= N) return true; // Consider this column and try placing // this queen in all rows one by one for(let i = 0; i < N; i++) { // Check if queen can be placed on board[i][col] if (isSafe(i, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)) { // Place this queen in board[i][col] board[i][col] = 1; rowLookup[i] = true; slashCodeLookup[slashCode[i][col]] = true; backslashCodeLookup[backslashCode[i][col]] = true; // recur to place rest of the queens if (solveNQueensUtil( board, col + 1, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)) return true; // If placing queen in board[i][col] doesn't // lead to a solution, then backtrack // Remove queen from board[i][col] board[i][col] = 0; rowLookup[i] = false; slashCodeLookup[slashCode[i][col]] = false; backslashCodeLookup[backslashCode[i][col]] = false; } } // If queen can not be place in any row // in this column col then return false return false;} /* * This function solves the N Queen problem using Branch * and Bound. It mainly uses solveNQueensUtil() to solve * the problem. It returns false if queens cannot be * placed, otherwise return true and prints placement of * queens in the form of 1s. Please note that there may * be more than one solutions, this function prints one * of the feasible solutions. */function solveNQueens(){ let board = new Array(N); // Helper matrices let slashCode = new Array(N); let backslashCode = new Array(N); for(let i=0;i<N;i++) { board[i]=new Array(N); slashCode[i]=new Array(N); backslashCode[i]=new Array(N); for(let j=0;j<N;j++) { board[i][j]=0; slashCode[i][j]=0; backslashCode[i][j]=0; } } // Arrays to tell us which rows are occupied let rowLookup = new Array(N); for(let i=0;i<N;i++) rowLookup[i]=false; // Keep two arrays to tell us // which diagonals are occupied let slashCodeLookup = new Array(2 * N - 1); let backslashCodeLookup = new Array(2 * N - 1); for(let i=0;i<2*N-1;i++) { slashCodeLookup[i]=false; backslashCodeLookup[i]=false; } // Initialize helper matrices for(let r = 0; r < N; r++) for(let c = 0; c < N; c++) { slashCode[r] = r + c; backslashCode[r] = r - c + 7; } if (solveNQueensUtil(board, 0, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) == false) { document.write("Solution does not exist"); return false; } // Solution found printSolution(board); return true;} // Driver codesolveNQueens(); // This code is contributed by avanitrachhadiya2155 </script>
Input:
Enter the no of rows for the square Board : 8
Output :
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
References : https://en.wikipedia.org/wiki/Eight_queens_puzzle www.cs.cornell.edu/~wdtseng/icpc/notes/bt2.pdfThis article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Akanksha_Rai
SHUBHAMSINGH10
mahdimurshed
sujitmeshram
arorakashish0911
avanitrachhadiya2155
shivanisinghss2110
simmytarika5
parshantrajput
chessboard-problems
Branch and Bound
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
0/1 Knapsack using Least Cost Branch and Bound
Travelling Salesman Problem (TSP) using Reduced Matrix Method
Classification of Algorithms with Examples
Generate Binary Strings of length N using Branch and Bound
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Calculator using Classes in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 263,
"s": 52,
"text": "The N queens puzzle is the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal."
},
{
"code": null,
"e": 542,
"s": 263,
"text": "Backtracking Algorithm for N-Queen is already discussed here. In backtracking solution we backtrack when we hit a dead end. In Branch and Bound solution, after building a partial solution, we figure out that there is no point going any deeper as we are going to hit a dead end. "
},
{
"code": null,
"e": 976,
"s": 542,
"text": "Let’s begin by describing backtracking solution. “The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes, then we backtrack and return false.”"
},
{
"code": null,
"e": 1519,
"s": 976,
"text": "For the 1st Queen, there are total 8 possibilities as we can place 1st Queen in any row of first column. Let’s place Queen 1 on row 3.After placing 1st Queen, there are 7 possibilities left for the 2nd Queen. But wait, we don’t really have 7 possibilities. We cannot place Queen 2 on rows 2, 3 or 4 as those cells are under attack from Queen 1. So, Queen 2 has only 8 – 3 = 5 valid positions left.After picking a position for Queen 2, Queen 3 has even fewer options as most of the cells in its column are under attack from the first 2 Queens."
},
{
"code": null,
"e": 1654,
"s": 1519,
"text": "For the 1st Queen, there are total 8 possibilities as we can place 1st Queen in any row of first column. Let’s place Queen 1 on row 3."
},
{
"code": null,
"e": 1918,
"s": 1654,
"text": "After placing 1st Queen, there are 7 possibilities left for the 2nd Queen. But wait, we don’t really have 7 possibilities. We cannot place Queen 2 on rows 2, 3 or 4 as those cells are under attack from Queen 1. So, Queen 2 has only 8 – 3 = 5 valid positions left."
},
{
"code": null,
"e": 2064,
"s": 1918,
"text": "After picking a position for Queen 2, Queen 3 has even fewer options as most of the cells in its column are under attack from the first 2 Queens."
},
{
"code": null,
"e": 2549,
"s": 2064,
"text": "We need to figure out an efficient way of keeping track of which cells are under attack. In previous solution we kept an 8-by-8 Boolean matrix and update it each time we placed a queen, but that required linear time to update as we need to check for safe cells.Basically, we have to ensure 4 things: 1. No two queens share a column. 2. No two queens share a row. 3. No two queens share a top-right to left-bottom diagonal. 4. No two queens share a top-left to bottom-right diagonal."
},
{
"code": null,
"e": 2772,
"s": 2549,
"text": "Number 1 is automatic because of the way we store the solution. For number 2, 3 and 4, we can perform updates in O(1) time. The idea is to keep three Boolean arrays that tell us which rows and which diagonals are occupied."
},
{
"code": null,
"e": 3319,
"s": 2772,
"text": "Lets do some pre-processing first. Let’s create two N x N matrix one for / diagonal and other one for \\ diagonal. Let’s call them slashCode and backslashCode respectively. The trick is to fill them in such a way that two queens sharing a same /diagonal will have the same value in matrix slashCode, and if they share same \\diagonal, they will have the same value in backslashCode matrix.For an N x N matrix, fill slashCode and backslashCode matrix using below formula –slashCode[row][col] = row + col backslashCode[row][col] = row – col + (N-1)"
},
{
"code": null,
"e": 3371,
"s": 3319,
"text": "Using above formula will result in below matrices "
},
{
"code": null,
"e": 4122,
"s": 3373,
"text": "The ‘N – 1’ in the backslash code is there to ensure that the codes are never negative because we will be using the codes as indices in an array.Now before we place queen i on row j, we first check whether row j is used (use an array to store row info). Then we check whether slash code ( j + i ) or backslash code ( j – i + 7 ) are used (keep two arrays that will tell us which diagonals are occupied). If yes, then we have to try a different location for queen i. If not, then we mark the row and the two diagonals as used and recurse on queen i + 1. After the recursive call returns and before we try another position for queen i, we need to reset the row, slash code and backslash code as unused again, like in the code from the previous notes."
},
{
"code": null,
"e": 4168,
"s": 4122,
"text": "Below is the implementation of above idea – "
},
{
"code": null,
"e": 4203,
"s": 4168,
"text": "This code Takes the Dynamic Input:"
},
{
"code": null,
"e": 4207,
"s": 4203,
"text": "C++"
},
{
"code": null,
"e": 4209,
"s": 4207,
"text": "C"
},
{
"code": null,
"e": 4214,
"s": 4209,
"text": "Java"
},
{
"code": null,
"e": 4222,
"s": 4214,
"text": "Python3"
},
{
"code": null,
"e": 4233,
"s": 4222,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std;int N; // function for printing the solutionvoid printSol(vector<vector<int>>board){ for(int i = 0;i<N;i++){ for(int j = 0;j<N;j++){ cout<<board[i][j]<<\" \"; } cout<<\"\\n\"; }} /* Optimized isSafe functionisSafe function to check if current row contins or current left diagonal or current right diagonal contains any queen or not if yes return false else return true*/ bool isSafe(int row ,int col ,vector<bool>rows , vector<bool>left_digonals ,vector<bool>Right_digonals){ if(rows[row] == true || left_digonals[row+col] == true || Right_digonals[col-row+N-1] == true){ return false; } return true;} // Recursive function to solve N-queen Problembool solve(vector<vector<int>>& board ,int col ,vector<bool>rows , vector<bool>left_digonals ,vector<bool>Right_digonals){ // base Case : If all Queens are placed if(col>=N){ return true; } /* Consider this Column and move in all rows one by one */ for(int i = 0;i<N;i++) { if(isSafe(i,col,rows,left_digonals,Right_digonals) == true) { rows[i] = true; left_digonals[i+col] = true; Right_digonals[col-i+N-1] = true; board[i][col] = 1; // placing the Queen in board[i][col] /* recur to place rest of the queens */ if(solve(board,col+1,rows,left_digonals,Right_digonals) == true){ return true; } // Backtracking rows[i] = false; left_digonals[i+col] = false; Right_digonals[col-i+N-1] = false; board[i][col] = 0; // removing the Queen from board[i][col] } } return false;} int main(){ // Taking input from the user cout<<\"Enter the no of rows for the square Board : \"; cin>>N; // board of size N*N vector<vector<int>>board(N,vector<int>(N,0)); // array to tell which rows are occupied vector<bool>rows(N,false); // arrays to tell which diagonals are occupied vector<bool>left_digonals(2*N-1,false); vector<bool>Right_digonals(2*N-1,false); bool ans = solve(board , 0, rows,left_digonals,Right_digonals); if(ans == true){ // printing the solution Board printSol(board); } else{ cout<<\"Solution Does not Exist\\n\"; }} // This Code is Contributed by Parshant Rajput",
"e": 6749,
"s": 4233,
"text": null
},
{
"code": "/* C++ program to solve N Queen Problem using Branch and Bound */#include<stdio.h>#include<string.h>#include<stdbool.h>#define N 8 /* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\"%2d \", board[i][j]); printf(\"\\n\"); }} /* A Optimized function to check if a queen canbe placed on board[row][col] */bool isSafe(int row, int col, int slashCode[N][N], int backslashCode[N][N], bool rowLookup[], bool slashCodeLookup[], bool backslashCodeLookup[] ){ if (slashCodeLookup[slashCode[row][col]] || backslashCodeLookup[backslashCode[row][col]] || rowLookup[row]) return false; return true;} /* A recursive utility functionto solve N Queen problem */bool solveNQueensUtil(int board[N][N], int col, int slashCode[N][N], int backslashCode[N][N], bool rowLookup[N], bool slashCodeLookup[], bool backslashCodeLookup[] ){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ if ( isSafe(i, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) ) { /* Place this queen in board[i][col] */ board[i][col] = 1; rowLookup[i] = true; slashCodeLookup[slashCode[i][col]] = true; backslashCodeLookup[backslashCode[i][col]] = true; /* recur to place rest of the queens */ if ( solveNQueensUtil(board, col + 1, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) ) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then backtrack */ /* Remove queen from board[i][col] */ board[i][col] = 0; rowLookup[i] = false; slashCodeLookup[slashCode[i][col]] = false; backslashCodeLookup[backslashCode[i][col]] = false; } } /* If queen can not be place in any row in this column col then return false */ return false;} /* This function solves the N Queen problem usingBranch and Bound. It mainly uses solveNQueensUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/bool solveNQueens(){ int board[N][N]; memset(board, 0, sizeof board); // helper matrices int slashCode[N][N]; int backslashCode[N][N]; // arrays to tell us which rows are occupied bool rowLookup[N] = {false}; //keep two arrays to tell us // which diagonals are occupied bool slashCodeLookup[2*N - 1] = {false}; bool backslashCodeLookup[2*N - 1] = {false}; // initialize helper matrices for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) { slashCode[r] = r + c, backslashCode[r] = r - c + 7; } if (solveNQueensUtil(board, 0, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) == false ) { printf(\"Solution does not exist\"); return false; } // solution found printSolution(board); return true;} // Driver program to test above functionint main(){ solveNQueens(); return 0;}",
"e": 10529,
"s": 6749,
"text": null
},
{
"code": "// Java program to solve N Queen Problem// using Branch and Boundimport java.io.*;import java.util.Arrays; class GFG{ static int N = 8; // A utility function to print solutionstatic void printSolution(int board[][]){ int N = board.length; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) System.out.printf(\"%2d \", board[i][j]); System.out.printf(\"\\n\"); }} // A Optimized function to check if a queen// can be placed on board[row][col]static boolean isSafe(int row, int col, int slashCode[][], int backslashCode[][], boolean rowLookup[], boolean slashCodeLookup[], boolean backslashCodeLookup[]){ if (slashCodeLookup[slashCode[row][col]] || backslashCodeLookup[backslashCode[row][col]] || rowLookup[row]) return false; return true;} // A recursive utility function to// solve N Queen problemstatic boolean solveNQueensUtil( int board[][], int col, int slashCode[][], int backslashCode[][], boolean rowLookup[], boolean slashCodeLookup[], boolean backslashCodeLookup[]){ // Base case: If all queens are placed // then return true int N = board.length; if (col >= N) return true; // Consider this column and try placing // this queen in all rows one by one for(int i = 0; i < N; i++) { // Check if queen can be placed on board[i][col] if (isSafe(i, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)) { // Place this queen in board[i][col] board[i][col] = 1; rowLookup[i] = true; slashCodeLookup[slashCode[i][col]] = true; backslashCodeLookup[backslashCode[i][col]] = true; // recur to place rest of the queens if (solveNQueensUtil( board, col + 1, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)) return true; // If placing queen in board[i][col] doesn't // lead to a solution, then backtrack // Remove queen from board[i][col] board[i][col] = 0; rowLookup[i] = false; slashCodeLookup[slashCode[i][col]] = false; backslashCodeLookup[backslashCode[i][col]] = false; } } // If queen can not be place in any row // in this column col then return false return false;} /* * This function solves the N Queen problem using Branch * and Bound. It mainly uses solveNQueensUtil() to solve * the problem. It returns false if queens cannot be * placed, otherwise return true and prints placement of * queens in the form of 1s. Please note that there may * be more than one solutions, this function prints one * of the feasible solutions. */static boolean solveNQueens(){ int board[][] = new int[N][N]; // Helper matrices int slashCode[][] = new int[N][N]; int backslashCode[][] = new int[N][N]; // Arrays to tell us which rows are occupied boolean[] rowLookup = new boolean[N]; // Keep two arrays to tell us // which diagonals are occupied boolean slashCodeLookup[] = new boolean[2 * N - 1]; boolean backslashCodeLookup[] = new boolean[2 * N - 1]; // Initialize helper matrices for(int r = 0; r < N; r++) for(int c = 0; c < N; c++) { slashCode[r] = r + c; backslashCode[r] = r - c + 7; } if (solveNQueensUtil(board, 0, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) == false) { System.out.printf(\"Solution does not exist\"); return false; } // Solution found printSolution(board); return true;} // Driver codepublic static void main(String[] args){ solveNQueens();}} // This code is contributed by sujitmeshram",
"e": 14591,
"s": 10529,
"text": null
},
{
"code": "\"\"\" Python3 program to solve N Queen Problemusing Branch or Bound \"\"\" N = 8 \"\"\" A utility function to print solution \"\"\"def printSolution(board): for i in range(N): for j in range(N): print(board[i][j], end = \" \") print() \"\"\" A Optimized function to check ifa queen can be placed on board[row][col] \"\"\"def isSafe(row, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup): if (slashCodeLookup[slashCode[row][col]] or backslashCodeLookup[backslashCode[row][col]] or rowLookup[row]): return False return True \"\"\" A recursive utility function to solve N Queen problem \"\"\"def solveNQueensUtil(board, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup): \"\"\" base case: If all queens are placed then return True \"\"\" if(col >= N): return True for i in range(N): if(isSafe(i, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)): \"\"\" Place this queen in board[i][col] \"\"\" board[i][col] = 1 rowLookup[i] = True slashCodeLookup[slashCode[i][col]] = True backslashCodeLookup[backslashCode[i][col]] = True \"\"\" recur to place rest of the queens \"\"\" if(solveNQueensUtil(board, col + 1, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)): return True \"\"\" If placing queen in board[i][col] doesn't lead to a solution,then backtrack \"\"\" \"\"\" Remove queen from board[i][col] \"\"\" board[i][col] = 0 rowLookup[i] = False slashCodeLookup[slashCode[i][col]] = False backslashCodeLookup[backslashCode[i][col]] = False \"\"\" If queen can not be place in any row in this column col then return False \"\"\" return False \"\"\" This function solves the N Queen problem usingBranch or Bound. It mainly uses solveNQueensUtil()tosolve the problem. It returns False if queenscannot be placed,otherwise return True orprints placement of queens in the form of 1s.Please note that there may be more than onesolutions,this function prints one of thefeasible solutions.\"\"\"def solveNQueens(): board = [[0 for i in range(N)] for j in range(N)] # helper matrices slashCode = [[0 for i in range(N)] for j in range(N)] backslashCode = [[0 for i in range(N)] for j in range(N)] # arrays to tell us which rows are occupied rowLookup = [False] * N # keep two arrays to tell us # which diagonals are occupied x = 2 * N - 1 slashCodeLookup = [False] * x backslashCodeLookup = [False] * x # initialize helper matrices for rr in range(N): for cc in range(N): slashCode[rr][cc] = rr + cc backslashCode[rr][cc] = rr - cc + 7 if(solveNQueensUtil(board, 0, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) == False): print(\"Solution does not exist\") return False # solution found printSolution(board) return True # Driver CdesolveNQueens() # This code is contributed by SHUBHAMSINGH10",
"e": 18140,
"s": 14591,
"text": null
},
{
"code": "<script> // JavaScript program to solve N Queen Problem// using Branch and Bound let N = 8; // A utility function to print solutionfunction printSolution(board){ let N = board.length; for(let i = 0; i < N; i++) { for(let j = 0; j < N; j++) document.write(board[i][j]+\" \"); document.write(\"<br>\"); }} // A Optimized function to check if a queen// can be placed on board[row][col]function isSafe(row,col,slashCode,backslashCode,rowLookup,slashCodeLookup,backslashCodeLookup){ if (slashCodeLookup[slashCode[row][col]] || backslashCodeLookup[backslashCode[row][col]] || rowLookup[row]) return false; return true;} // A recursive utility function to// solve N Queen problemfunction solveNQueensUtil(board,col,slashCode,backslashCode,rowLookup,slashCodeLookup,backslashCodeLookup){ // Base case: If all queens are placed // then return true //let N = board.length; if (col >= N) return true; // Consider this column and try placing // this queen in all rows one by one for(let i = 0; i < N; i++) { // Check if queen can be placed on board[i][col] if (isSafe(i, col, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)) { // Place this queen in board[i][col] board[i][col] = 1; rowLookup[i] = true; slashCodeLookup[slashCode[i][col]] = true; backslashCodeLookup[backslashCode[i][col]] = true; // recur to place rest of the queens if (solveNQueensUtil( board, col + 1, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup)) return true; // If placing queen in board[i][col] doesn't // lead to a solution, then backtrack // Remove queen from board[i][col] board[i][col] = 0; rowLookup[i] = false; slashCodeLookup[slashCode[i][col]] = false; backslashCodeLookup[backslashCode[i][col]] = false; } } // If queen can not be place in any row // in this column col then return false return false;} /* * This function solves the N Queen problem using Branch * and Bound. It mainly uses solveNQueensUtil() to solve * the problem. It returns false if queens cannot be * placed, otherwise return true and prints placement of * queens in the form of 1s. Please note that there may * be more than one solutions, this function prints one * of the feasible solutions. */function solveNQueens(){ let board = new Array(N); // Helper matrices let slashCode = new Array(N); let backslashCode = new Array(N); for(let i=0;i<N;i++) { board[i]=new Array(N); slashCode[i]=new Array(N); backslashCode[i]=new Array(N); for(let j=0;j<N;j++) { board[i][j]=0; slashCode[i][j]=0; backslashCode[i][j]=0; } } // Arrays to tell us which rows are occupied let rowLookup = new Array(N); for(let i=0;i<N;i++) rowLookup[i]=false; // Keep two arrays to tell us // which diagonals are occupied let slashCodeLookup = new Array(2 * N - 1); let backslashCodeLookup = new Array(2 * N - 1); for(let i=0;i<2*N-1;i++) { slashCodeLookup[i]=false; backslashCodeLookup[i]=false; } // Initialize helper matrices for(let r = 0; r < N; r++) for(let c = 0; c < N; c++) { slashCode[r] = r + c; backslashCode[r] = r - c + 7; } if (solveNQueensUtil(board, 0, slashCode, backslashCode, rowLookup, slashCodeLookup, backslashCodeLookup) == false) { document.write(\"Solution does not exist\"); return false; } // Solution found printSolution(board); return true;} // Driver codesolveNQueens(); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 22273,
"s": 18140,
"text": null
},
{
"code": null,
"e": 22280,
"s": 22273,
"text": "Input:"
},
{
"code": null,
"e": 22326,
"s": 22280,
"text": "Enter the no of rows for the square Board : 8"
},
{
"code": null,
"e": 22336,
"s": 22326,
"text": "Output : "
},
{
"code": null,
"e": 22535,
"s": 22336,
"text": " 1 0 0 0 0 0 0 0 \n 0 0 0 0 0 0 1 0 \n 0 0 0 0 1 0 0 0 \n 0 0 0 0 0 0 0 1 \n 0 1 0 0 0 0 0 0 \n 0 0 0 1 0 0 0 0 \n 0 0 0 0 0 1 0 0 \n 0 0 1 0 0 0 0 0"
},
{
"code": null,
"e": 23033,
"s": 22535,
"text": "References : https://en.wikipedia.org/wiki/Eight_queens_puzzle www.cs.cornell.edu/~wdtseng/icpc/notes/bt2.pdfThis article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 23046,
"s": 23033,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 23061,
"s": 23046,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 23074,
"s": 23061,
"text": "mahdimurshed"
},
{
"code": null,
"e": 23087,
"s": 23074,
"text": "sujitmeshram"
},
{
"code": null,
"e": 23104,
"s": 23087,
"text": "arorakashish0911"
},
{
"code": null,
"e": 23125,
"s": 23104,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 23144,
"s": 23125,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 23157,
"s": 23144,
"text": "simmytarika5"
},
{
"code": null,
"e": 23172,
"s": 23157,
"text": "parshantrajput"
},
{
"code": null,
"e": 23192,
"s": 23172,
"text": "chessboard-problems"
},
{
"code": null,
"e": 23209,
"s": 23192,
"text": "Branch and Bound"
},
{
"code": null,
"e": 23307,
"s": 23209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 23335,
"s": 23307,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 23382,
"s": 23335,
"text": "0/1 Knapsack using Least Cost Branch and Bound"
},
{
"code": null,
"e": 23444,
"s": 23382,
"text": "Travelling Salesman Problem (TSP) using Reduced Matrix Method"
},
{
"code": null,
"e": 23487,
"s": 23444,
"text": "Classification of Algorithms with Examples"
},
{
"code": null,
"e": 23546,
"s": 23487,
"text": "Generate Binary Strings of length N using Branch and Bound"
},
{
"code": null,
"e": 23616,
"s": 23546,
"text": "Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!"
},
{
"code": null,
"e": 23642,
"s": 23616,
"text": "Spring Boot - Annotations"
},
{
"code": null,
"e": 23691,
"s": 23642,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 23716,
"s": 23691,
"text": "DSA Sheet by Love Babbar"
}
] |
PHP Pagination | Set 1
|
20 Mar, 2018
PHP is mostly used to store and show data from a database according to the user’s requirements. For example, let us think that we have organized a competition and now have the challenge to show the leaderboard. Our event was very successful and had a participation of over Ten Thousand. Now if we have to show the whole list on one page, the page will be very long so it may not be the best of ways to show a list. What we can do is to distribute the whole list in a number of pages. This method of distributing a single list in a number of pages is known as Pagination. Let us now look at the Advantages and Disadvantages of Pagination.
Disadvantages of Pagination
Let us think of an event where external viewers are significantly low, thus if you publish a leaderboard it is possible that the few users participating will like to keep track of the leaderboard but not the whole leaderboard. A user will tend to see its own rank and the performance of the top rank holder. Thus if we distribute the leaderboard in several pages then we must provide a special way so that the user may navigate to the page where its username is present in the rank list. This seems a bit too much to add in many cases and thus Pagination can be ignored in such cases.
Pagination is pure overhead i.e. Pagination is an additional feature that can be implemented in a cost of extraneous Markup, Styling as well as logic. Thus having a small dataset containing hundreds of records it’s often ignored to use Pagination.
Advantages of Pagination
In one of the disadvantages we got to know that Pagination itself is an overhead, but Pagination can also save us from loading a lot of information at once. For example, let us think of a gallery web-page that should show a big list of images, Now showing thousands of pictures in a single page will require thousands of HTTP requests which will make the page highly unresponsive whereas using Pagination we can show a limited amount of images in a page thus limiting the HTTP requests and moreover creating a more efficient page.
It is always better to use Pagination for medium to large-scale projects because Pagination not only makes the webpage work faster and efficiently but also appears to be much more precise and professional.
Implementing Pagination
Now in order to implement pagination, we first need a big data-set to which we will apply the pagination. For the simplicity of this mini-project, we will use Bootstrap and minimal explicit styling. Seeing the success of the previous competition ProGeek Cup 1.0, we will consider making the leader-board of ProGeek Cup 2.0, so let us start by creating the markup first.We will try to keep the whole page as simple as possible containing a Title, a brief description, and the leader-board table itself.
The Markup
Before starting with the fetch and show cycle of PHP let us first set up the basic interface of the table. After creating a folder in the “WWW” folder/ “htdocs” folder and creating an “index.php” file, I used the following markup to get a basic table interface as shown below.
<!DOCTYPE html><html> <head> <title>ProGeeks Cup 2.0</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/ css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div> <h1>ProGeeks Cup 2.0</h1> <p>This page is just for demonstration of Basic Pagination using PHP. </p> <table class="table table-striped table-condensed table-bordered"> <thead> <tr> <th width="10%">Rank</th> <th>Name</th> <th>College</th> <th>Score</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> </body></html>
Refer to the following article for more detailed description of using table in Bootstrap. Now that we have managed to develop the basic markup we must then get ready with our data.
The Data
If we want to use pagination we must have quite a good amount of data to distribute among pages. Now you may search for sample datasets or create your own. Now for simplicity, I used the following python script to create a fake rank list to be shown on the webpage. By using the random library the data generated is less obvious and using CSV format it can be directly imported into MySQL.
import csv, randomfirstNames = ["Anuran", "Bappa", "Deep", "Dhanraj", "Harsh", "Sabyasachi", "Saptarshi", "Sayan", "Shubham", "Sampriti", "Susmita", "Pronab", "Vaskar", "Sanjeeb", "Anirudh"]lastNames = ["Pandit", "Das", "Bhattacharjee", "Rathi", "Agarwal", "Mishra", "Garg", "Pal", "Khan", "Ganguly", "Dutta", "Mukherjee", "Lodhi", "Malhotra", "Gupta"]collegeNames = ["IIT Delhi", "IIT Kharagpur", "BIT Mesra", "JIT", "Jadavpur University", "IIT Roorkee", "KGEC", "SMIT", "EIEM", "CGEC", "JGEC", "IISC Bangalore", "IIIT Allahabad", "IIT Kanpur", "IIT BHU"]dataTemplate = [['Rank', 'Name', 'College', 'Score']] Rank, maxScore = 1, 3000for x in xrange(1500): i = random.randint(0, 14) j = random.randint(0, 14) k = random.randint(0, 14) entry = [str(Rank), firstNames[i]+" "+lastNames[j], collegeNames[k], str(maxScore)] dataTemplate.append(entry) maxScore-= random.randint(1, 3) Rank+= 1 targetFile = open('pagination.csv', 'w')with targetFile: writer = csv.writer(targetFile) writer.writerows(dataTemplate) print "Done"
In the code above we have taken three lists of first names, last names, and college names. Our motive is to make a fake rank list. We will iterate for 1500 times, each time we will generate three random indices to get a random first name a random last name and a college. We will also generate a fourth random integer that will denote the difference in the score from the previous rank holder’s. Now that we have the CSV file we will go to “phpmyadmin” and import the file to create a new table. The following is the figure explaining the whole procedure and the result.
Now that we have set up our Database as well as done our mark up, we basically have our backbone ready and only need to jump into the PHP part itself. Judging the length of this article, it will be better if we start off in the next article that will be totally focused on implementing a basic pagination system.
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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 ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2018"
},
{
"code": null,
"e": 666,
"s": 28,
"text": "PHP is mostly used to store and show data from a database according to the user’s requirements. For example, let us think that we have organized a competition and now have the challenge to show the leaderboard. Our event was very successful and had a participation of over Ten Thousand. Now if we have to show the whole list on one page, the page will be very long so it may not be the best of ways to show a list. What we can do is to distribute the whole list in a number of pages. This method of distributing a single list in a number of pages is known as Pagination. Let us now look at the Advantages and Disadvantages of Pagination."
},
{
"code": null,
"e": 694,
"s": 666,
"text": "Disadvantages of Pagination"
},
{
"code": null,
"e": 1279,
"s": 694,
"text": "Let us think of an event where external viewers are significantly low, thus if you publish a leaderboard it is possible that the few users participating will like to keep track of the leaderboard but not the whole leaderboard. A user will tend to see its own rank and the performance of the top rank holder. Thus if we distribute the leaderboard in several pages then we must provide a special way so that the user may navigate to the page where its username is present in the rank list. This seems a bit too much to add in many cases and thus Pagination can be ignored in such cases."
},
{
"code": null,
"e": 1527,
"s": 1279,
"text": "Pagination is pure overhead i.e. Pagination is an additional feature that can be implemented in a cost of extraneous Markup, Styling as well as logic. Thus having a small dataset containing hundreds of records it’s often ignored to use Pagination."
},
{
"code": null,
"e": 1552,
"s": 1527,
"text": "Advantages of Pagination"
},
{
"code": null,
"e": 2083,
"s": 1552,
"text": "In one of the disadvantages we got to know that Pagination itself is an overhead, but Pagination can also save us from loading a lot of information at once. For example, let us think of a gallery web-page that should show a big list of images, Now showing thousands of pictures in a single page will require thousands of HTTP requests which will make the page highly unresponsive whereas using Pagination we can show a limited amount of images in a page thus limiting the HTTP requests and moreover creating a more efficient page."
},
{
"code": null,
"e": 2289,
"s": 2083,
"text": "It is always better to use Pagination for medium to large-scale projects because Pagination not only makes the webpage work faster and efficiently but also appears to be much more precise and professional."
},
{
"code": null,
"e": 2313,
"s": 2289,
"text": "Implementing Pagination"
},
{
"code": null,
"e": 2815,
"s": 2313,
"text": "Now in order to implement pagination, we first need a big data-set to which we will apply the pagination. For the simplicity of this mini-project, we will use Bootstrap and minimal explicit styling. Seeing the success of the previous competition ProGeek Cup 1.0, we will consider making the leader-board of ProGeek Cup 2.0, so let us start by creating the markup first.We will try to keep the whole page as simple as possible containing a Title, a brief description, and the leader-board table itself."
},
{
"code": null,
"e": 2826,
"s": 2815,
"text": "The Markup"
},
{
"code": null,
"e": 3103,
"s": 2826,
"text": "Before starting with the fetch and show cycle of PHP let us first set up the basic interface of the table. After creating a folder in the “WWW” folder/ “htdocs” folder and creating an “index.php” file, I used the following markup to get a basic table interface as shown below."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ProGeeks Cup 2.0</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/ css/bootstrap.min.css\"> </head> <body> <div class=\"container\"> <br> <div> <h1>ProGeeks Cup 2.0</h1> <p>This page is just for demonstration of Basic Pagination using PHP. </p> <table class=\"table table-striped table-condensed table-bordered\"> <thead> <tr> <th width=\"10%\">Rank</th> <th>Name</th> <th>College</th> <th>Score</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> </body></html>",
"e": 3908,
"s": 3103,
"text": null
},
{
"code": null,
"e": 4089,
"s": 3908,
"text": "Refer to the following article for more detailed description of using table in Bootstrap. Now that we have managed to develop the basic markup we must then get ready with our data."
},
{
"code": null,
"e": 4098,
"s": 4089,
"text": "The Data"
},
{
"code": null,
"e": 4488,
"s": 4098,
"text": "If we want to use pagination we must have quite a good amount of data to distribute among pages. Now you may search for sample datasets or create your own. Now for simplicity, I used the following python script to create a fake rank list to be shown on the webpage. By using the random library the data generated is less obvious and using CSV format it can be directly imported into MySQL."
},
{
"code": "import csv, randomfirstNames = [\"Anuran\", \"Bappa\", \"Deep\", \"Dhanraj\", \"Harsh\", \"Sabyasachi\", \"Saptarshi\", \"Sayan\", \"Shubham\", \"Sampriti\", \"Susmita\", \"Pronab\", \"Vaskar\", \"Sanjeeb\", \"Anirudh\"]lastNames = [\"Pandit\", \"Das\", \"Bhattacharjee\", \"Rathi\", \"Agarwal\", \"Mishra\", \"Garg\", \"Pal\", \"Khan\", \"Ganguly\", \"Dutta\", \"Mukherjee\", \"Lodhi\", \"Malhotra\", \"Gupta\"]collegeNames = [\"IIT Delhi\", \"IIT Kharagpur\", \"BIT Mesra\", \"JIT\", \"Jadavpur University\", \"IIT Roorkee\", \"KGEC\", \"SMIT\", \"EIEM\", \"CGEC\", \"JGEC\", \"IISC Bangalore\", \"IIIT Allahabad\", \"IIT Kanpur\", \"IIT BHU\"]dataTemplate = [['Rank', 'Name', 'College', 'Score']] Rank, maxScore = 1, 3000for x in xrange(1500): i = random.randint(0, 14) j = random.randint(0, 14) k = random.randint(0, 14) entry = [str(Rank), firstNames[i]+\" \"+lastNames[j], collegeNames[k], str(maxScore)] dataTemplate.append(entry) maxScore-= random.randint(1, 3) Rank+= 1 targetFile = open('pagination.csv', 'w')with targetFile: writer = csv.writer(targetFile) writer.writerows(dataTemplate) print \"Done\" ",
"e": 5711,
"s": 4488,
"text": null
},
{
"code": null,
"e": 6282,
"s": 5711,
"text": "In the code above we have taken three lists of first names, last names, and college names. Our motive is to make a fake rank list. We will iterate for 1500 times, each time we will generate three random indices to get a random first name a random last name and a college. We will also generate a fourth random integer that will denote the difference in the score from the previous rank holder’s. Now that we have the CSV file we will go to “phpmyadmin” and import the file to create a new table. The following is the figure explaining the whole procedure and the result."
},
{
"code": null,
"e": 6595,
"s": 6282,
"text": "Now that we have set up our Database as well as done our mark up, we basically have our backbone ready and only need to jump into the PHP part itself. Judging the length of this article, it will be better if we start off in the next article that will be totally focused on implementing a basic pagination system."
},
{
"code": null,
"e": 6599,
"s": 6595,
"text": "PHP"
},
{
"code": null,
"e": 6616,
"s": 6599,
"text": "Web Technologies"
},
{
"code": null,
"e": 6620,
"s": 6616,
"text": "PHP"
},
{
"code": null,
"e": 6718,
"s": 6620,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6768,
"s": 6718,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 6808,
"s": 6768,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 6869,
"s": 6808,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 6919,
"s": 6869,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 6964,
"s": 6919,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 6997,
"s": 6964,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 7058,
"s": 6997,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7108,
"s": 7058,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7151,
"s": 7108,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to invert case for all letters in a string in Python?
|
String class has a method called swapcase() for swapping case of all letters. You can use it as follows:
>>> 'Hello World 123'.swapcase()
'hELLO wORLD 123'
>>> 'Make America Great Again'.swapcase()
'mAKE aMERICA gREAT aGAIN'
|
[
{
"code": null,
"e": 1292,
"s": 1187,
"text": "String class has a method called swapcase() for swapping case of all letters. You can use it as follows:"
},
{
"code": null,
"e": 1412,
"s": 1292,
"text": ">>> 'Hello World 123'.swapcase()\n'hELLO wORLD 123'\n>>> 'Make America Great Again'.swapcase()\n'mAKE aMERICA gREAT aGAIN'"
}
] |
turtle.pos() method in Python
|
01 Aug, 2020
The Turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to find the turtle’s current location (x, y), as a Vec2D-vector. This method has the Aliases: pos | position.
Syntax: turtle.pos() or turtle.position()
Return: turtle’s current location in terms of (x, y) coordinate
This function does not require any argument and returns the current position of the turtle in the format (x,y) where x and y represent the 2D vector. The default value is (0.0, 0.0).
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import turtle packageimport turtle # print the default # position i.e; (0.0, 0.0)print(turtle.pos()) # forward turtle by 150 pixelsturtle.forward(150) # print current position # i.e; (150.0, 0.0)print(turtle.pos()) # forward turtle by 150 pixels# after taking turn right# by 90 degreesturtle.right(90)turtle.forward(150) # print position (after next move)# i.e; (150.0, -150.0)print(turtle.pos())
Output:
(0.0, 0.0)
(150.0, 0.0)
(150.0, -150.0)
Example 2:
Python3
# import turtle packageimport turtle # print position (by default)# i.e; (0.0, 0.0)print(turtle.pos()) # turtle move forward # by 40 pixelsturtle.forward(40) # print position (after move)# i.e; (150.0, 0.0)print(turtle.position()) # turtle move forward by 40 pixels# after taking right turn # by 45 degreesturtle.right(45)turtle.forward(40) # print position# (after next move) print(turtle.pos()) # turtle move forward by 80 # pixels after taking left# turn by 90 degreesturtle.left(90)turtle.forward(80) # print position# (after next move) print(turtle.pos()) # turtle move forward # by 40 pixels after taking # right turn by 90 degreesturtle.right(90)turtle.forward(40) # print position (after next move) print(turtle.position()) # turtle move forward by # 40 pixels after taking # left turn by 45 degreesturtle.left(45)turtle.forward(40) # print position # (after final move) print(turtle.pos())
Output :
(0.0, 0.0)
(40.0, 0.0)
(68.2842712475, -28.2842712475)
(124.852813742, 28.2842712475)
(153.13708499, 0.0)
(193.13708499, 0.0)
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The Turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 375,
"s": 245,
"text": "This method is used to find the turtle’s current location (x, y), as a Vec2D-vector. This method has the Aliases: pos | position."
},
{
"code": null,
"e": 418,
"s": 375,
"text": "Syntax: turtle.pos() or turtle.position()"
},
{
"code": null,
"e": 482,
"s": 418,
"text": "Return: turtle’s current location in terms of (x, y) coordinate"
},
{
"code": null,
"e": 665,
"s": 482,
"text": "This function does not require any argument and returns the current position of the turtle in the format (x,y) where x and y represent the 2D vector. The default value is (0.0, 0.0)."
},
{
"code": null,
"e": 734,
"s": 665,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 746,
"s": 734,
"text": "Example 1 :"
},
{
"code": null,
"e": 754,
"s": 746,
"text": "Python3"
},
{
"code": "# import turtle packageimport turtle # print the default # position i.e; (0.0, 0.0)print(turtle.pos()) # forward turtle by 150 pixelsturtle.forward(150) # print current position # i.e; (150.0, 0.0)print(turtle.pos()) # forward turtle by 150 pixels# after taking turn right# by 90 degreesturtle.right(90)turtle.forward(150) # print position (after next move)# i.e; (150.0, -150.0)print(turtle.pos())",
"e": 1159,
"s": 754,
"text": null
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Output:"
},
{
"code": null,
"e": 1208,
"s": 1167,
"text": "(0.0, 0.0)\n(150.0, 0.0)\n(150.0, -150.0)\n"
},
{
"code": null,
"e": 1219,
"s": 1208,
"text": "Example 2:"
},
{
"code": null,
"e": 1227,
"s": 1219,
"text": "Python3"
},
{
"code": "# import turtle packageimport turtle # print position (by default)# i.e; (0.0, 0.0)print(turtle.pos()) # turtle move forward # by 40 pixelsturtle.forward(40) # print position (after move)# i.e; (150.0, 0.0)print(turtle.position()) # turtle move forward by 40 pixels# after taking right turn # by 45 degreesturtle.right(45)turtle.forward(40) # print position# (after next move) print(turtle.pos()) # turtle move forward by 80 # pixels after taking left# turn by 90 degreesturtle.left(90)turtle.forward(80) # print position# (after next move) print(turtle.pos()) # turtle move forward # by 40 pixels after taking # right turn by 90 degreesturtle.right(90)turtle.forward(40) # print position (after next move) print(turtle.position()) # turtle move forward by # 40 pixels after taking # left turn by 45 degreesturtle.left(45)turtle.forward(40) # print position # (after final move) print(turtle.pos())",
"e": 2138,
"s": 1227,
"text": null
},
{
"code": null,
"e": 2147,
"s": 2138,
"text": "Output :"
},
{
"code": null,
"e": 2274,
"s": 2147,
"text": "(0.0, 0.0)\n(40.0, 0.0)\n(68.2842712475, -28.2842712475)\n(124.852813742, 28.2842712475)\n(153.13708499, 0.0)\n(193.13708499, 0.0)\n"
},
{
"code": null,
"e": 2288,
"s": 2274,
"text": "Python-turtle"
},
{
"code": null,
"e": 2295,
"s": 2288,
"text": "Python"
}
] |
Count number of ways to divide a number in 4 parts
|
12 Aug, 2021
Given a positive integer n, find number of ways to divide n in four parts or represent n as sum of four positive integers. Here n varies from 0 to 5000.Examples :
Input: n = 5
Output: 1
There is only one way (1, 1, 1, 2)
Input: n = 6
Output: 2
There are two ways (1, 1, 1, 3) and
(1, 1, 2, 2)
Input: n = 8
Output: 5
There are five ways (2, 2, 2, 2), (1, 1, 1, 5),
(1, 1, 3, 3), (1, 1, 2, 4) and (1, 2, 2, 3)
Method 1 (Simple Solution) Run four nested loops to generate all possible different quadruplet. Below is C++ implementation of the simple algorithm. Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// A Simple C++ program to count number of ways to// represent a number n as sum of four.#include<bits/stdc++.h>using namespace std; // Returns count of waysint countWays(int n){ int counter = 0; // Initialize result // Generate all possible quadruplet and increment // counter when sum of a quadruplet is equal to n for (int i = 1; i < n; i++) for (int j = i; j < n; j++) for (int k = j; k < n; k++) for (int l = k; l < n; l++) if (i + j + k + l == n) counter++; return counter;} // Driver programint main(){ int n = 8; cout << countWays(n); return 0;}
// A Simple Java program to count number of ways to// represent a number n as sum of four. import java.io.*; class GFG { // Returns count of waysstatic int countWays(int n){ int counter = 0; // Initialize result // Generate all possible quadruplet and increment // counter when sum of a quadruplet is equal to n for (int i = 1; i < n; i++) for (int j = i; j < n; j++) for (int k = j; k < n; k++) for (int l = k; l < n; l++) if (i + j + k + l == n) counter++; return counter;} // Driver program public static void main (String[] args) { int n = 8; System.out.println (countWays(n)); }}
# A Simple python3 program to count# number of ways to represent a number# n as sum of four. # Returns count of waysdef countWays(n): counter = 0 # Initialize result # Generate all possible quadruplet # and increment counter when sum of # a quadruplet is equal to n for i in range(1, n): for j in range(i, n): for k in range(j, n): for l in range(k, n): if (i + j + k + l == n): counter += 1 return counter # Driver Codeif __name__ == "__main__": n = 8 print (countWays(n)) # This code is contributed by ita_c
// A Simple C# program to count number// of ways to represent a number n as// sum of four.using System; class GFG{ // Returns count of waysstatic int countWays(int n){ int counter = 0; // Initialize result // Generate all possible quadruplet // and increment counter when sum of // a quadruplet is equal to n for (int i = 1; i < n; i++) for (int j = i; j < n; j++) for (int k = j; k < n; k++) for (int l = k; l < n; l++) if (i + j + k + l == n) counter++; return counter;} // Driver Codestatic public void Main (){ int n = 8; Console.WriteLine(countWays(n));}} // This code is contributed by Sachin
<?php// A Simple PHP program to count// number of ways to represent// a number n as sum of four. // Returns count of waysfunction countWays($n){ // Initialize result $counter = 0; // Generate all possible quadruplet // and increment counter when sum // of a quadruplet is equal to n for ($i = 1; $i < $n; $i++) for ( $j = $i; $j < $n; $j++) for ($k = $j; $k < $n; $k++) for ( $l = $k; $l < $n; $l++) if ($i + $j + $k + $l == $n) $counter++; return $counter;} // Driver Code$n = 8;echo countWays($n); // This code is contributed by m_kit?>
<script> // A Simple Javascript program to count number of ways to// represent a number n as sum of four. // Returns count of ways function countWays(n) { let counter = 0; // Initialize result // Generate all possible quadruplet and increment // counter when sum of a quadruplet is equal to n for (let i = 1; i < n; i++) for (let j = i; j < n; j++) for (let k = j; k < n; k++) for (let l = k; l < n; l++) if (i + j + k + l == n) counter++; return counter; } let n = 8; document.write(countWays(n)); // This code is contributed by rag2127 </script>
Output :
5
Time complexity of above solution is O(n4)Method 2 (Uses Dynamic Programming) The idea is based on below recursive solution.
countWays(n, parts, nextPart) = ∑countWays(n, parts, i)
nextPart <= i Input number
parts --> Count of parts of n. Initially parts = 4
nextPart --> Starting point for next part to be tried
We try for all values from nextPart to n.
We initially call the function as countWays(n, 4, 1)
Below is Dynamic Programming based on solution of above idea.
C++
Java
Python3
C#
PHP
Javascript
// A Dynamic Programming based solution to count number// of ways to represent n as sum of four numbers#include<bits/stdc++.h>using namespace std;int dp[5001][5001][5]; // "parts" is number of parts left, n is the value left// "nextPart" is starting point from where we start trying// for next part.int countWaysUtil(int n, int parts, int nextPart){ // Base cases if (parts == 0 && n == 0) return 1; if (n <= 0 || parts <= 0) return 0; // If this subproblem is already solved if (dp[n][nextPart][parts] != -1) return dp[n][nextPart][parts]; int ans = 0; // Initialize result // Count number of ways for remaining number n-i // remaining parts "parts-1", and for all part // varying from 'nextPart' to 'n' for (int i = nextPart; i <= n; i++) ans += countWaysUtil(n-i, parts-1, i); // Store computed answer in table and return // result return (dp[n][nextPart][parts] = ans);} // This function mainly initializes dp table and// calls countWaysUtil()int countWays(int n){ memset(dp, -1, sizeof(dp)); return countWaysUtil(n, 4, 1);} // Driver programint main(){ int n = 8; cout << countWays(n) << endl; return 0;}
// A Dynamic Programming based solution to count number// of ways to represent n as sum of four numbersclass GFG{ static int dp[][][] = new int[5001][5001][5]; // "parts" is number of parts left, n is the value left// "nextPart" is starting point from where we start trying// for next part.static int countWaysUtil(int n, int parts, int nextPart){ // Base cases if (parts == 0 && n == 0) return 1; if (n <= 0 || parts <= 0) return 0; // If this subproblem is already solved if (dp[n][nextPart][parts] != -1) return dp[n][nextPart][parts]; int ans = 0; // Initialize result // Count number of ways for remaining number n-i // remaining parts "parts-1", and for all part // varying from 'nextPart' to 'n' for (int i = nextPart; i <= n; i++) ans += countWaysUtil(n-i, parts-1, i); // Store computed answer in table and return // result return (dp[n][nextPart][parts] = ans);} // This function mainly initializes dp table and// calls countWaysUtil()static int countWays(int n){ for(int i = 0; i < 5001; i++) { for(int j = 0; j < 5001; j++) { for(int l = 0; l < 5; l++) dp[i][j][l] = -1; } } return countWaysUtil(n, 4, 1);} // Driver programpublic static void main(String[] args){ int n = 8; System.out.println(countWays(n));}} /* This code contributed by PrinciRaj1992 */
# A Dynamic Programming based solution# to count number of ways to represent# n as sum of four numbers dp = [[[-1 for i in range(5)] for i in range(501)] for i in range(501)] # "parts" is number of parts left, n is# the value left "nextPart" is starting# point from where we start trying# for next part.def countWaysUtil(n, parts, nextPart): # Base cases if (parts == 0 and n == 0): return 1 if (n <= 0 or parts <= 0): return 0 # If this subproblem is already solved if (dp[n][nextPart][parts] != -1): return dp[n][nextPart][parts] ans = 0 # Initialize result # Count number of ways for remaining # number n-i remaining parts "parts-1", # and for all part varying from # 'nextPart' to 'n' for i in range(nextPart, n + 1): ans += countWaysUtil(n - i, parts - 1, i) # Store computed answer in table # and return result dp[n][nextPart][parts] = ans return (ans) # This function mainly initializes dp# table and calls countWaysUtil()def countWays(n): return countWaysUtil(n, 4, 1) # Driver Coden = 8print(countWays(n)) # This code is contributed# by sahishelangia
// A Dynamic Programming based solution to count number// of ways to represent n as sum of four numbersusing System; class GFG{ static int [,,]dp = new int[5001, 5001, 5]; // "parts" is number of parts left, n is the value left// "nextPart" is starting point from where we start trying// for next part.static int countWaysUtil(int n, int parts, int nextPart){ // Base cases if (parts == 0 && n == 0) return 1; if (n <= 0 || parts <= 0) return 0; // If this subproblem is already solved if (dp[n,nextPart,parts] != -1) return dp[n,nextPart,parts]; int ans = 0; // Initialize result // Count number of ways for remaining number n-i // remaining parts "parts-1", and for all part // varying from 'nextPart' to 'n' for (int i = nextPart; i <= n; i++) ans += countWaysUtil(n - i, parts - 1, i); // Store computed answer in table and return // result return (dp[n,nextPart,parts] = ans);} // This function mainly initializes dp table and// calls countWaysUtil()static int countWays(int n){ for(int i = 0; i < 5001; i++) { for(int j = 0; j < 5001; j++) { for(int l = 0; l < 5; l++) dp[i, j, l] = -1; } } return countWaysUtil(n, 4, 1);} // Driver codepublic static void Main(String[] args){ int n = 8; Console.WriteLine(countWays(n));}} // This code contributed by Rajput-Ji
<?php// A Dynamic Programming based solution to// count number of ways to represent n as// sum of four numbers$dp = array_fill(0, 501, array_fill(0, 501, array_fill(0, 5, -1))); // "parts" is number of parts left, n is// the value left "nextPart" is starting// point from where we start trying// for next part.function countWaysUtil($n, $parts, $nextPart){ global $dp; // Base cases if ($parts == 0 && $n == 0) return 1; if ($n <= 0 || $parts <= 0) return 0; // If this subproblem is already solved if ($dp[$n][$nextPart][$parts] != -1) return $dp[$n][$nextPart][$parts]; $ans = 0; // Initialize result // Count number of ways for remaining // number n-i remaining parts "parts-1", // and for all part varying from // 'nextPart' to 'n' for ($i = $nextPart; $i <= $n; $i++) $ans += countWaysUtil($n - $i, $parts - 1, $i); // Store computed answer in table // and return result return ($dp[$n][$nextPart][$parts] = $ans);} // This function mainly initializes dp// table and calls countWaysUtil()function countWays($n){ return countWaysUtil($n, 4, 1);} // Driver Code$n = 8;echo countWays($n); // This code is contributed by chandan_jnu?>
<script>// A Dynamic Programming based solution to count number// of ways to represent n as sum of four numbers let dp = new Array(5001); for(let i = 0; i < 5001; i++) { dp[i] = new Array(5001); for(let j = 0; j < 5001; j++) { dp[i][j] = new Array(5); } } // "parts" is number of parts left, n is the value left // "nextPart" is starting point from where we start trying // for next part. function countWaysUtil(n,parts,nextPart) { // Base cases if (parts == 0 && n == 0) return 1; if (n <= 0 || parts <= 0) return 0; // If this subproblem is already solved if (dp[n][nextPart][parts] != -1) return dp[n][nextPart][parts]; let ans = 0; // Initialize result // Count number of ways for remaining number n-i // remaining parts "parts-1", and for all part // varying from 'nextPart' to 'n' for (let i = nextPart; i <= n; i++) ans += countWaysUtil(n - i, parts - 1, i); // Store computed answer in table and return // result return (dp[n][nextPart][parts] = ans); } // This function mainly initializes dp table and // calls countWaysUtil() function countWays(n) { for(let i = 0; i < 5001; i++) { for(let j = 0; j < 5001; j++) { for(let l = 0; l < 5; l++) dp[i][j][l] = -1; } } return countWaysUtil(n, 4, 1); } // Driver program let n = 8; document.write(countWays(n)); // This code is contributed by avanitrachhadiya2155</script>
Output :
5
Time Complexity: O(n3). There are Θ(n2) entries, every entry is filled only once and filling an entry takes O(n) time.Auxiliary Space: O(n2)
Method 3 (A O(n2 Log n) Solution) We can use the solution discussed in this post to find all quadruplets.Thanks to Gaurav Ahirwar for suggesting above solutions.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
Sach_Code
ukasp
sahilshelangia
Chandan_Kumar
princiraj1992
Rajput-Ji
rag2127
avanitrachhadiya2155
pankajsharmagfg
Algorithms
Mathematical
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 219,
"s": 54,
"text": "Given a positive integer n, find number of ways to divide n in four parts or represent n as sum of four positive integers. Here n varies from 0 to 5000.Examples : "
},
{
"code": null,
"e": 473,
"s": 219,
"text": "Input: n = 5\nOutput: 1\nThere is only one way (1, 1, 1, 2)\n\nInput: n = 6\nOutput: 2\nThere are two ways (1, 1, 1, 3) and \n(1, 1, 2, 2)\n\nInput: n = 8\nOutput: 5\nThere are five ways (2, 2, 2, 2), (1, 1, 1, 5),\n(1, 1, 3, 3), (1, 1, 2, 4) and (1, 2, 2, 3)"
},
{
"code": null,
"e": 673,
"s": 475,
"text": "Method 1 (Simple Solution) Run four nested loops to generate all possible different quadruplet. Below is C++ implementation of the simple algorithm. Below is the implementation of above approach: "
},
{
"code": null,
"e": 677,
"s": 673,
"text": "C++"
},
{
"code": null,
"e": 682,
"s": 677,
"text": "Java"
},
{
"code": null,
"e": 690,
"s": 682,
"text": "Python3"
},
{
"code": null,
"e": 693,
"s": 690,
"text": "C#"
},
{
"code": null,
"e": 697,
"s": 693,
"text": "PHP"
},
{
"code": null,
"e": 708,
"s": 697,
"text": "Javascript"
},
{
"code": "// A Simple C++ program to count number of ways to// represent a number n as sum of four.#include<bits/stdc++.h>using namespace std; // Returns count of waysint countWays(int n){ int counter = 0; // Initialize result // Generate all possible quadruplet and increment // counter when sum of a quadruplet is equal to n for (int i = 1; i < n; i++) for (int j = i; j < n; j++) for (int k = j; k < n; k++) for (int l = k; l < n; l++) if (i + j + k + l == n) counter++; return counter;} // Driver programint main(){ int n = 8; cout << countWays(n); return 0;}",
"e": 1358,
"s": 708,
"text": null
},
{
"code": "// A Simple Java program to count number of ways to// represent a number n as sum of four. import java.io.*; class GFG { // Returns count of waysstatic int countWays(int n){ int counter = 0; // Initialize result // Generate all possible quadruplet and increment // counter when sum of a quadruplet is equal to n for (int i = 1; i < n; i++) for (int j = i; j < n; j++) for (int k = j; k < n; k++) for (int l = k; l < n; l++) if (i + j + k + l == n) counter++; return counter;} // Driver program public static void main (String[] args) { int n = 8; System.out.println (countWays(n)); }}",
"e": 2060,
"s": 1358,
"text": null
},
{
"code": "# A Simple python3 program to count# number of ways to represent a number# n as sum of four. # Returns count of waysdef countWays(n): counter = 0 # Initialize result # Generate all possible quadruplet # and increment counter when sum of # a quadruplet is equal to n for i in range(1, n): for j in range(i, n): for k in range(j, n): for l in range(k, n): if (i + j + k + l == n): counter += 1 return counter # Driver Codeif __name__ == \"__main__\": n = 8 print (countWays(n)) # This code is contributed by ita_c",
"e": 2672,
"s": 2060,
"text": null
},
{
"code": "// A Simple C# program to count number// of ways to represent a number n as// sum of four.using System; class GFG{ // Returns count of waysstatic int countWays(int n){ int counter = 0; // Initialize result // Generate all possible quadruplet // and increment counter when sum of // a quadruplet is equal to n for (int i = 1; i < n; i++) for (int j = i; j < n; j++) for (int k = j; k < n; k++) for (int l = k; l < n; l++) if (i + j + k + l == n) counter++; return counter;} // Driver Codestatic public void Main (){ int n = 8; Console.WriteLine(countWays(n));}} // This code is contributed by Sachin",
"e": 3375,
"s": 2672,
"text": null
},
{
"code": "<?php// A Simple PHP program to count// number of ways to represent// a number n as sum of four. // Returns count of waysfunction countWays($n){ // Initialize result $counter = 0; // Generate all possible quadruplet // and increment counter when sum // of a quadruplet is equal to n for ($i = 1; $i < $n; $i++) for ( $j = $i; $j < $n; $j++) for ($k = $j; $k < $n; $k++) for ( $l = $k; $l < $n; $l++) if ($i + $j + $k + $l == $n) $counter++; return $counter;} // Driver Code$n = 8;echo countWays($n); // This code is contributed by m_kit?>",
"e": 4011,
"s": 3375,
"text": null
},
{
"code": "<script> // A Simple Javascript program to count number of ways to// represent a number n as sum of four. // Returns count of ways function countWays(n) { let counter = 0; // Initialize result // Generate all possible quadruplet and increment // counter when sum of a quadruplet is equal to n for (let i = 1; i < n; i++) for (let j = i; j < n; j++) for (let k = j; k < n; k++) for (let l = k; l < n; l++) if (i + j + k + l == n) counter++; return counter; } let n = 8; document.write(countWays(n)); // This code is contributed by rag2127 </script>",
"e": 4728,
"s": 4011,
"text": null
},
{
"code": null,
"e": 4739,
"s": 4728,
"text": "Output : "
},
{
"code": null,
"e": 4741,
"s": 4739,
"text": "5"
},
{
"code": null,
"e": 4867,
"s": 4741,
"text": "Time complexity of above solution is O(n4)Method 2 (Uses Dynamic Programming) The idea is based on below recursive solution. "
},
{
"code": null,
"e": 5196,
"s": 4867,
"text": "countWays(n, parts, nextPart) = ∑countWays(n, parts, i)\n nextPart <= i Input number\nparts --> Count of parts of n. Initially parts = 4\nnextPart --> Starting point for next part to be tried\n We try for all values from nextPart to n.\n\nWe initially call the function as countWays(n, 4, 1)\n "
},
{
"code": null,
"e": 5259,
"s": 5196,
"text": "Below is Dynamic Programming based on solution of above idea. "
},
{
"code": null,
"e": 5263,
"s": 5259,
"text": "C++"
},
{
"code": null,
"e": 5268,
"s": 5263,
"text": "Java"
},
{
"code": null,
"e": 5276,
"s": 5268,
"text": "Python3"
},
{
"code": null,
"e": 5279,
"s": 5276,
"text": "C#"
},
{
"code": null,
"e": 5283,
"s": 5279,
"text": "PHP"
},
{
"code": null,
"e": 5294,
"s": 5283,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based solution to count number// of ways to represent n as sum of four numbers#include<bits/stdc++.h>using namespace std;int dp[5001][5001][5]; // \"parts\" is number of parts left, n is the value left// \"nextPart\" is starting point from where we start trying// for next part.int countWaysUtil(int n, int parts, int nextPart){ // Base cases if (parts == 0 && n == 0) return 1; if (n <= 0 || parts <= 0) return 0; // If this subproblem is already solved if (dp[n][nextPart][parts] != -1) return dp[n][nextPart][parts]; int ans = 0; // Initialize result // Count number of ways for remaining number n-i // remaining parts \"parts-1\", and for all part // varying from 'nextPart' to 'n' for (int i = nextPart; i <= n; i++) ans += countWaysUtil(n-i, parts-1, i); // Store computed answer in table and return // result return (dp[n][nextPart][parts] = ans);} // This function mainly initializes dp table and// calls countWaysUtil()int countWays(int n){ memset(dp, -1, sizeof(dp)); return countWaysUtil(n, 4, 1);} // Driver programint main(){ int n = 8; cout << countWays(n) << endl; return 0;}",
"e": 6472,
"s": 5294,
"text": null
},
{
"code": "// A Dynamic Programming based solution to count number// of ways to represent n as sum of four numbersclass GFG{ static int dp[][][] = new int[5001][5001][5]; // \"parts\" is number of parts left, n is the value left// \"nextPart\" is starting point from where we start trying// for next part.static int countWaysUtil(int n, int parts, int nextPart){ // Base cases if (parts == 0 && n == 0) return 1; if (n <= 0 || parts <= 0) return 0; // If this subproblem is already solved if (dp[n][nextPart][parts] != -1) return dp[n][nextPart][parts]; int ans = 0; // Initialize result // Count number of ways for remaining number n-i // remaining parts \"parts-1\", and for all part // varying from 'nextPart' to 'n' for (int i = nextPart; i <= n; i++) ans += countWaysUtil(n-i, parts-1, i); // Store computed answer in table and return // result return (dp[n][nextPart][parts] = ans);} // This function mainly initializes dp table and// calls countWaysUtil()static int countWays(int n){ for(int i = 0; i < 5001; i++) { for(int j = 0; j < 5001; j++) { for(int l = 0; l < 5; l++) dp[i][j][l] = -1; } } return countWaysUtil(n, 4, 1);} // Driver programpublic static void main(String[] args){ int n = 8; System.out.println(countWays(n));}} /* This code contributed by PrinciRaj1992 */",
"e": 7854,
"s": 6472,
"text": null
},
{
"code": "# A Dynamic Programming based solution# to count number of ways to represent# n as sum of four numbers dp = [[[-1 for i in range(5)] for i in range(501)] for i in range(501)] # \"parts\" is number of parts left, n is# the value left \"nextPart\" is starting# point from where we start trying# for next part.def countWaysUtil(n, parts, nextPart): # Base cases if (parts == 0 and n == 0): return 1 if (n <= 0 or parts <= 0): return 0 # If this subproblem is already solved if (dp[n][nextPart][parts] != -1): return dp[n][nextPart][parts] ans = 0 # Initialize result # Count number of ways for remaining # number n-i remaining parts \"parts-1\", # and for all part varying from # 'nextPart' to 'n' for i in range(nextPart, n + 1): ans += countWaysUtil(n - i, parts - 1, i) # Store computed answer in table # and return result dp[n][nextPart][parts] = ans return (ans) # This function mainly initializes dp# table and calls countWaysUtil()def countWays(n): return countWaysUtil(n, 4, 1) # Driver Coden = 8print(countWays(n)) # This code is contributed# by sahishelangia",
"e": 9019,
"s": 7854,
"text": null
},
{
"code": "// A Dynamic Programming based solution to count number// of ways to represent n as sum of four numbersusing System; class GFG{ static int [,,]dp = new int[5001, 5001, 5]; // \"parts\" is number of parts left, n is the value left// \"nextPart\" is starting point from where we start trying// for next part.static int countWaysUtil(int n, int parts, int nextPart){ // Base cases if (parts == 0 && n == 0) return 1; if (n <= 0 || parts <= 0) return 0; // If this subproblem is already solved if (dp[n,nextPart,parts] != -1) return dp[n,nextPart,parts]; int ans = 0; // Initialize result // Count number of ways for remaining number n-i // remaining parts \"parts-1\", and for all part // varying from 'nextPart' to 'n' for (int i = nextPart; i <= n; i++) ans += countWaysUtil(n - i, parts - 1, i); // Store computed answer in table and return // result return (dp[n,nextPart,parts] = ans);} // This function mainly initializes dp table and// calls countWaysUtil()static int countWays(int n){ for(int i = 0; i < 5001; i++) { for(int j = 0; j < 5001; j++) { for(int l = 0; l < 5; l++) dp[i, j, l] = -1; } } return countWaysUtil(n, 4, 1);} // Driver codepublic static void Main(String[] args){ int n = 8; Console.WriteLine(countWays(n));}} // This code contributed by Rajput-Ji",
"e": 10404,
"s": 9019,
"text": null
},
{
"code": "<?php// A Dynamic Programming based solution to// count number of ways to represent n as// sum of four numbers$dp = array_fill(0, 501, array_fill(0, 501, array_fill(0, 5, -1))); // \"parts\" is number of parts left, n is// the value left \"nextPart\" is starting// point from where we start trying// for next part.function countWaysUtil($n, $parts, $nextPart){ global $dp; // Base cases if ($parts == 0 && $n == 0) return 1; if ($n <= 0 || $parts <= 0) return 0; // If this subproblem is already solved if ($dp[$n][$nextPart][$parts] != -1) return $dp[$n][$nextPart][$parts]; $ans = 0; // Initialize result // Count number of ways for remaining // number n-i remaining parts \"parts-1\", // and for all part varying from // 'nextPart' to 'n' for ($i = $nextPart; $i <= $n; $i++) $ans += countWaysUtil($n - $i, $parts - 1, $i); // Store computed answer in table // and return result return ($dp[$n][$nextPart][$parts] = $ans);} // This function mainly initializes dp// table and calls countWaysUtil()function countWays($n){ return countWaysUtil($n, 4, 1);} // Driver Code$n = 8;echo countWays($n); // This code is contributed by chandan_jnu?>",
"e": 11646,
"s": 10404,
"text": null
},
{
"code": "<script>// A Dynamic Programming based solution to count number// of ways to represent n as sum of four numbers let dp = new Array(5001); for(let i = 0; i < 5001; i++) { dp[i] = new Array(5001); for(let j = 0; j < 5001; j++) { dp[i][j] = new Array(5); } } // \"parts\" is number of parts left, n is the value left // \"nextPart\" is starting point from where we start trying // for next part. function countWaysUtil(n,parts,nextPart) { // Base cases if (parts == 0 && n == 0) return 1; if (n <= 0 || parts <= 0) return 0; // If this subproblem is already solved if (dp[n][nextPart][parts] != -1) return dp[n][nextPart][parts]; let ans = 0; // Initialize result // Count number of ways for remaining number n-i // remaining parts \"parts-1\", and for all part // varying from 'nextPart' to 'n' for (let i = nextPart; i <= n; i++) ans += countWaysUtil(n - i, parts - 1, i); // Store computed answer in table and return // result return (dp[n][nextPart][parts] = ans); } // This function mainly initializes dp table and // calls countWaysUtil() function countWays(n) { for(let i = 0; i < 5001; i++) { for(let j = 0; j < 5001; j++) { for(let l = 0; l < 5; l++) dp[i][j][l] = -1; } } return countWaysUtil(n, 4, 1); } // Driver program let n = 8; document.write(countWays(n)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 13352,
"s": 11646,
"text": null
},
{
"code": null,
"e": 13363,
"s": 13352,
"text": "Output : "
},
{
"code": null,
"e": 13365,
"s": 13363,
"text": "5"
},
{
"code": null,
"e": 13507,
"s": 13365,
"text": "Time Complexity: O(n3). There are Θ(n2) entries, every entry is filled only once and filling an entry takes O(n) time.Auxiliary Space: O(n2) "
},
{
"code": null,
"e": 13793,
"s": 13507,
"text": "Method 3 (A O(n2 Log n) Solution) We can use the solution discussed in this post to find all quadruplets.Thanks to Gaurav Ahirwar for suggesting above solutions.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 13799,
"s": 13793,
"text": "jit_t"
},
{
"code": null,
"e": 13809,
"s": 13799,
"text": "Sach_Code"
},
{
"code": null,
"e": 13815,
"s": 13809,
"text": "ukasp"
},
{
"code": null,
"e": 13830,
"s": 13815,
"text": "sahilshelangia"
},
{
"code": null,
"e": 13844,
"s": 13830,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 13858,
"s": 13844,
"text": "princiraj1992"
},
{
"code": null,
"e": 13868,
"s": 13858,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13876,
"s": 13868,
"text": "rag2127"
},
{
"code": null,
"e": 13897,
"s": 13876,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 13913,
"s": 13897,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 13924,
"s": 13913,
"text": "Algorithms"
},
{
"code": null,
"e": 13937,
"s": 13924,
"text": "Mathematical"
},
{
"code": null,
"e": 13950,
"s": 13937,
"text": "Mathematical"
},
{
"code": null,
"e": 13961,
"s": 13950,
"text": "Algorithms"
}
] |
Read/Write Class Objects from/to File in C++
|
06 Oct, 2020
Given a file “Input.txt” in which every line has values same as instance variables of a class. Read the values into the class’s object and do necessary operations.Theory :
The data transfer is usually done using '>>'
and <<' operators. But if you have
a class with 4 data members and want
to write all 4 data members from its
object directly to a file or vice-versa,
we can do that using following syntax :
To write object's data members in a file :
// Here file_obj is an object of ofstream
file_obj.write((char *) & class_obj, sizeof(class_obj));
To read file's data members into an object :
// Here file_obj is an object of ifstream
file_obj.read((char *) & class_obj, sizeof(class_obj));
Examples:
Input :
Input.txt :
Michael 19 1806
Kemp 24 2114
Terry 21 2400
Operation : Print the name of the highest
rated programmer.
Output :
Terry
C++
// C++ program to demonstrate read/write of class// objects in C++.#include <iostream>#include <fstream>using namespace std; // Class to define the propertiesclass Contestant {public: // Instance variables string Name; int Age, Ratings; // Function declaration of input() to input info int input(); // Function declaration of output_highest_rated() to // extract info from file Data Base int output_highest_rated();}; // Function definition of input() to input infoint Contestant::input(){ // Object to write in file ofstream file_obj; // Opening file in append mode file_obj.open("Input.txt", ios::app); // Object of class contestant to input data in file Contestant obj; // Feeding appropriate data in variables string str = "Michael"; int age = 18, ratings = 2500; // Assigning data into object obj.Name = str; obj.Age = age; obj.Ratings = ratings; // Writing the object's data in file file_obj.write((char*)&obj, sizeof(obj)); // Feeding appropriate data in variables str = "Terry"; age = 21; ratings = 3200; // Assigning data into object obj.Name = str; obj.Age = age; obj.Ratings = ratings; // Writing the object's data in file file_obj.write((char*)&obj, sizeof(obj)); return 0;} // Function definition of output_highest_rated() to// extract info from file Data Baseint Contestant::output_highest_rated(){ // Object to read from file ifstream file_obj; // Opening file in input mode file_obj.open("Input.txt", ios::in); // Object of class contestant to input data in file Contestant obj; // Reading from file into object "obj" file_obj.read((char*)&obj, sizeof(obj)); // max to store maximum ratings int max = 0; // Highest_rated stores the name of highest rated contestant string Highest_rated; // Checking till we have the feed while (!file_obj.eof()) { // Assigning max ratings if (obj.Ratings > max) { max = obj.Ratings; Highest_rated = obj.Name; } // Checking further file_obj.read((char*)&obj, sizeof(obj)); } // Output is the highest rated contestant cout << Highest_rated; return 0;} // Driver codeint main(){ // Creating object of the class Contestant object; // Inputting the data object.input(); // Extracting the max rated contestant object.output_highest_rated(); return 0;}
Output:
Terry
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
zytekaron
cpp-class
cpp-input-output
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Virtual Function in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Oct, 2020"
},
{
"code": null,
"e": 227,
"s": 54,
"text": "Given a file “Input.txt” in which every line has values same as instance variables of a class. Read the values into the class’s object and do necessary operations.Theory : "
},
{
"code": null,
"e": 752,
"s": 227,
"text": "The data transfer is usually done using '>>'\nand <<' operators. But if you have\na class with 4 data members and want \nto write all 4 data members from its\nobject directly to a file or vice-versa, \nwe can do that using following syntax :\n\nTo write object's data members in a file :\n// Here file_obj is an object of ofstream\nfile_obj.write((char *) & class_obj, sizeof(class_obj));\n\nTo read file's data members into an object :\n// Here file_obj is an object of ifstream\nfile_obj.read((char *) & class_obj, sizeof(class_obj));\n"
},
{
"code": null,
"e": 763,
"s": 752,
"text": "Examples: "
},
{
"code": null,
"e": 918,
"s": 763,
"text": "Input : \nInput.txt :\nMichael 19 1806\nKemp 24 2114\nTerry 21 2400\nOperation : Print the name of the highest \n rated programmer.\n\nOutput : \nTerry\n"
},
{
"code": null,
"e": 922,
"s": 918,
"text": "C++"
},
{
"code": "// C++ program to demonstrate read/write of class// objects in C++.#include <iostream>#include <fstream>using namespace std; // Class to define the propertiesclass Contestant {public: // Instance variables string Name; int Age, Ratings; // Function declaration of input() to input info int input(); // Function declaration of output_highest_rated() to // extract info from file Data Base int output_highest_rated();}; // Function definition of input() to input infoint Contestant::input(){ // Object to write in file ofstream file_obj; // Opening file in append mode file_obj.open(\"Input.txt\", ios::app); // Object of class contestant to input data in file Contestant obj; // Feeding appropriate data in variables string str = \"Michael\"; int age = 18, ratings = 2500; // Assigning data into object obj.Name = str; obj.Age = age; obj.Ratings = ratings; // Writing the object's data in file file_obj.write((char*)&obj, sizeof(obj)); // Feeding appropriate data in variables str = \"Terry\"; age = 21; ratings = 3200; // Assigning data into object obj.Name = str; obj.Age = age; obj.Ratings = ratings; // Writing the object's data in file file_obj.write((char*)&obj, sizeof(obj)); return 0;} // Function definition of output_highest_rated() to// extract info from file Data Baseint Contestant::output_highest_rated(){ // Object to read from file ifstream file_obj; // Opening file in input mode file_obj.open(\"Input.txt\", ios::in); // Object of class contestant to input data in file Contestant obj; // Reading from file into object \"obj\" file_obj.read((char*)&obj, sizeof(obj)); // max to store maximum ratings int max = 0; // Highest_rated stores the name of highest rated contestant string Highest_rated; // Checking till we have the feed while (!file_obj.eof()) { // Assigning max ratings if (obj.Ratings > max) { max = obj.Ratings; Highest_rated = obj.Name; } // Checking further file_obj.read((char*)&obj, sizeof(obj)); } // Output is the highest rated contestant cout << Highest_rated; return 0;} // Driver codeint main(){ // Creating object of the class Contestant object; // Inputting the data object.input(); // Extracting the max rated contestant object.output_highest_rated(); return 0;}",
"e": 3373,
"s": 922,
"text": null
},
{
"code": null,
"e": 3382,
"s": 3373,
"text": "Output: "
},
{
"code": null,
"e": 3389,
"s": 3382,
"text": "Terry\n"
},
{
"code": null,
"e": 3817,
"s": 3389,
"text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3827,
"s": 3817,
"text": "zytekaron"
},
{
"code": null,
"e": 3837,
"s": 3827,
"text": "cpp-class"
},
{
"code": null,
"e": 3854,
"s": 3837,
"text": "cpp-input-output"
},
{
"code": null,
"e": 3858,
"s": 3854,
"text": "C++"
},
{
"code": null,
"e": 3862,
"s": 3858,
"text": "CPP"
},
{
"code": null,
"e": 3960,
"s": 3862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3978,
"s": 3960,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 4024,
"s": 3978,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 4047,
"s": 4024,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 4074,
"s": 4047,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 4108,
"s": 4074,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 4125,
"s": 4108,
"text": "Substring in C++"
},
{
"code": null,
"e": 4150,
"s": 4125,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 4174,
"s": 4150,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 4214,
"s": 4174,
"text": "2D Vector In C++ With User Defined Size"
}
] |
DATEADD() Function in SQL Server
|
18 Jan, 2021
DATEADD() function :This function in SQL Server is used to sum up a time or a date interval to a specified date, then returns the modified date.
Features :
This function is used to sum up a time or a date interval to a date specified.
This function comes under Date Functions.
This function accepts three parameters namely interval, number and date.
This function can also include time in the interval section.
Syntax :
DATEADD(interval, number, date)
Parameter :This method accepts three parameters as given below as follows.
interval –It is the specified time or date interval which is to be added. Moreover, the values of the interval can be as given below.year, yyyy, yy = Year, which is the specified year to be added.
quarter, qq, q = Quarter, which is the specified quarter to be added.
month, mm, m = month, which is the specified month to be added.
dayofyear, dy, y = Day of the year, which is the specified day of the year to be added.
day, dd, d = Day, which is the specified day to be added.
week, ww, wk = Week, which is the specified week to be added.
weekday, dw, w = Weekday, which is the specified week day to be added.
hour, hh = hour, which is the specified hour to be added.
minute, mi, n = Minute, which is the specified minute to be added.
second, ss, s = Second, which is the specified second to be added.
millisecond, ms = Millisecond, which is the specified millisecond to be added.
year, yyyy, yy = Year, which is the specified year to be added.
quarter, qq, q = Quarter, which is the specified quarter to be added.
month, mm, m = month, which is the specified month to be added.
dayofyear, dy, y = Day of the year, which is the specified day of the year to be added.
day, dd, d = Day, which is the specified day to be added.
week, ww, wk = Week, which is the specified week to be added.
weekday, dw, w = Weekday, which is the specified week day to be added.
hour, hh = hour, which is the specified hour to be added.
minute, mi, n = Minute, which is the specified minute to be added.
second, ss, s = Second, which is the specified second to be added.
millisecond, ms = Millisecond, which is the specified millisecond to be added.
number –It is the number of interval which is to be added to the date specified. It can be positive, in order to get the dates of the future or it can be negative also, in order to get the dates in the past.
date –It is the specified date which is to be altered.
Returns :It returns a modified date after adding a date or time interval to the stated date.
Example-1 :Using DATEADD() function and adding the year part of the date for getting the modified date.
SELECT DATEADD(year, 2, '2019/01/05');
Output :
2021-01-05 00:00:00.000
Example-2 :Using DATEADD() function and adding the month part of the date for getting the modified date.
SELECT DATEADD(month, 11, '2019/01/05');
Output :
2019-12-05 00:00:00.000
Example-3 :Using DATEADD() function and subtracting the month part of the date for getting the modified date.
SELECT DATEADD(month, -1, '2019/01/05');
Output :
2018-12-05 00:00:00.000
Example-4 :Using DATEADD() function and adding the day part of the date for getting the modified date.
SELECT DATEADD(day, 32, '2015/04/14');
Output :
2015-05-16 00:00:00.000
Example-5 :Using DATEADD() function and adding the minute part of the date for getting the modified date.
SELECT DATEADD(minute, 6, '2015/04/14 09:55');
Output :
2015-04-14 10:01:00.000
Example-6 :Using DATEADD() function and adding the hour part of the date using a variable for getting the modified date.
DECLARE @number INT;
SET @number = 8;
SELECT
DATEADD(hh, @number, '2021/01/02 08:50');
Output :
2021-01-02 16:50:00.000
Example-7 :Using DATEADD() function and adding the second part of the date using variables for getting the modified date.
DECLARE @number INT;
DECLARE @date VARCHAR(50);
SET @number = 08;
SET @date = '2011/11/22 07:59:56';
SELECT
DATEADD(ss, @number, @date);
Output :
2011-11-22 08:00:04.000
Application :This function is used to find the modified date after adding a date or time interval to the stated date.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "DATEADD() function :This function in SQL Server is used to sum up a time or a date interval to a specified date, then returns the modified date."
},
{
"code": null,
"e": 184,
"s": 173,
"text": "Features :"
},
{
"code": null,
"e": 263,
"s": 184,
"text": "This function is used to sum up a time or a date interval to a date specified."
},
{
"code": null,
"e": 305,
"s": 263,
"text": "This function comes under Date Functions."
},
{
"code": null,
"e": 378,
"s": 305,
"text": "This function accepts three parameters namely interval, number and date."
},
{
"code": null,
"e": 439,
"s": 378,
"text": "This function can also include time in the interval section."
},
{
"code": null,
"e": 448,
"s": 439,
"text": "Syntax :"
},
{
"code": null,
"e": 480,
"s": 448,
"text": "DATEADD(interval, number, date)"
},
{
"code": null,
"e": 555,
"s": 480,
"text": "Parameter :This method accepts three parameters as given below as follows."
},
{
"code": null,
"e": 1472,
"s": 555,
"text": "interval –It is the specified time or date interval which is to be added. Moreover, the values of the interval can be as given below.year, yyyy, yy = Year, which is the specified year to be added.\nquarter, qq, q = Quarter, which is the specified quarter to be added.\nmonth, mm, m = month, which is the specified month to be added.\ndayofyear, dy, y = Day of the year, which is the specified day of the year to be added.\nday, dd, d = Day, which is the specified day to be added.\nweek, ww, wk = Week, which is the specified week to be added.\nweekday, dw, w = Weekday, which is the specified week day to be added.\nhour, hh = hour, which is the specified hour to be added.\nminute, mi, n = Minute, which is the specified minute to be added.\nsecond, ss, s = Second, which is the specified second to be added.\nmillisecond, ms = Millisecond, which is the specified millisecond to be added.\n"
},
{
"code": null,
"e": 2256,
"s": 1472,
"text": "year, yyyy, yy = Year, which is the specified year to be added.\nquarter, qq, q = Quarter, which is the specified quarter to be added.\nmonth, mm, m = month, which is the specified month to be added.\ndayofyear, dy, y = Day of the year, which is the specified day of the year to be added.\nday, dd, d = Day, which is the specified day to be added.\nweek, ww, wk = Week, which is the specified week to be added.\nweekday, dw, w = Weekday, which is the specified week day to be added.\nhour, hh = hour, which is the specified hour to be added.\nminute, mi, n = Minute, which is the specified minute to be added.\nsecond, ss, s = Second, which is the specified second to be added.\nmillisecond, ms = Millisecond, which is the specified millisecond to be added.\n"
},
{
"code": null,
"e": 2464,
"s": 2256,
"text": "number –It is the number of interval which is to be added to the date specified. It can be positive, in order to get the dates of the future or it can be negative also, in order to get the dates in the past."
},
{
"code": null,
"e": 2519,
"s": 2464,
"text": "date –It is the specified date which is to be altered."
},
{
"code": null,
"e": 2612,
"s": 2519,
"text": "Returns :It returns a modified date after adding a date or time interval to the stated date."
},
{
"code": null,
"e": 2716,
"s": 2612,
"text": "Example-1 :Using DATEADD() function and adding the year part of the date for getting the modified date."
},
{
"code": null,
"e": 2755,
"s": 2716,
"text": "SELECT DATEADD(year, 2, '2019/01/05');"
},
{
"code": null,
"e": 2764,
"s": 2755,
"text": "Output :"
},
{
"code": null,
"e": 2788,
"s": 2764,
"text": "2021-01-05 00:00:00.000"
},
{
"code": null,
"e": 2893,
"s": 2788,
"text": "Example-2 :Using DATEADD() function and adding the month part of the date for getting the modified date."
},
{
"code": null,
"e": 2935,
"s": 2893,
"text": "SELECT DATEADD(month, 11, '2019/01/05');\n"
},
{
"code": null,
"e": 2944,
"s": 2935,
"text": "Output :"
},
{
"code": null,
"e": 2968,
"s": 2944,
"text": "2019-12-05 00:00:00.000"
},
{
"code": null,
"e": 3078,
"s": 2968,
"text": "Example-3 :Using DATEADD() function and subtracting the month part of the date for getting the modified date."
},
{
"code": null,
"e": 3120,
"s": 3078,
"text": "SELECT DATEADD(month, -1, '2019/01/05');\n"
},
{
"code": null,
"e": 3129,
"s": 3120,
"text": "Output :"
},
{
"code": null,
"e": 3153,
"s": 3129,
"text": "2018-12-05 00:00:00.000"
},
{
"code": null,
"e": 3256,
"s": 3153,
"text": "Example-4 :Using DATEADD() function and adding the day part of the date for getting the modified date."
},
{
"code": null,
"e": 3295,
"s": 3256,
"text": "SELECT DATEADD(day, 32, '2015/04/14');"
},
{
"code": null,
"e": 3304,
"s": 3295,
"text": "Output :"
},
{
"code": null,
"e": 3328,
"s": 3304,
"text": "2015-05-16 00:00:00.000"
},
{
"code": null,
"e": 3434,
"s": 3328,
"text": "Example-5 :Using DATEADD() function and adding the minute part of the date for getting the modified date."
},
{
"code": null,
"e": 3482,
"s": 3434,
"text": "SELECT DATEADD(minute, 6, '2015/04/14 09:55');\n"
},
{
"code": null,
"e": 3491,
"s": 3482,
"text": "Output :"
},
{
"code": null,
"e": 3515,
"s": 3491,
"text": "2015-04-14 10:01:00.000"
},
{
"code": null,
"e": 3636,
"s": 3515,
"text": "Example-6 :Using DATEADD() function and adding the hour part of the date using a variable for getting the modified date."
},
{
"code": null,
"e": 3724,
"s": 3636,
"text": "DECLARE @number INT;\nSET @number = 8;\nSELECT \nDATEADD(hh, @number, '2021/01/02 08:50');"
},
{
"code": null,
"e": 3733,
"s": 3724,
"text": "Output :"
},
{
"code": null,
"e": 3757,
"s": 3733,
"text": "2021-01-02 16:50:00.000"
},
{
"code": null,
"e": 3879,
"s": 3757,
"text": "Example-7 :Using DATEADD() function and adding the second part of the date using variables for getting the modified date."
},
{
"code": null,
"e": 4017,
"s": 3879,
"text": "DECLARE @number INT;\nDECLARE @date VARCHAR(50);\nSET @number = 08;\nSET @date = '2011/11/22 07:59:56';\nSELECT \nDATEADD(ss, @number, @date);"
},
{
"code": null,
"e": 4026,
"s": 4017,
"text": "Output :"
},
{
"code": null,
"e": 4050,
"s": 4026,
"text": "2011-11-22 08:00:04.000"
},
{
"code": null,
"e": 4168,
"s": 4050,
"text": "Application :This function is used to find the modified date after adding a date or time interval to the stated date."
},
{
"code": null,
"e": 4177,
"s": 4168,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 4188,
"s": 4177,
"text": "SQL-Server"
},
{
"code": null,
"e": 4192,
"s": 4188,
"text": "SQL"
},
{
"code": null,
"e": 4196,
"s": 4192,
"text": "SQL"
},
{
"code": null,
"e": 4294,
"s": 4196,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4360,
"s": 4294,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 4384,
"s": 4360,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 4416,
"s": 4384,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 4433,
"s": 4416,
"text": "SQL using Python"
},
{
"code": null,
"e": 4466,
"s": 4433,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 4544,
"s": 4466,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 4574,
"s": 4544,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 4610,
"s": 4574,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 4641,
"s": 4610,
"text": "SQL Query to Compare Two Dates"
}
] |
How to add a column to a MySQL table in Python?
|
It may be sometimes required to add a new column in a existing table. Suppose we have a “Students” table with columns such as Name, Age, Roll no. We want to add a new column “Address” into our existing table.
This can be done by using the ALTER command. The ALTER command is used to modify, drop or update columns in the database. This can also be used to add a new column into the table using ADD clause.
ALTER TABLE table_name
ADD new_column_name column_definition
[FIRST | AFTER exisiting_column]
Here, table_name refers to the name of the table, new_column_name refers to the name of the column to be added, column_definition refers to the datatype of the column.
The FIRST AND AFTER clause are optional.This are used to specify the particular position at which you want to add the new column. The FIRST will insert the new column at the first position. The AFTER existing_column will insert a new column after the existing_column.
By default, the new column is inserted at the end of the table.
import MySQL connector
import MySQL connector
establish connection with the connector using connect()
establish connection with the connector using connect()
create the cursor object using cursor() method
create the cursor object using cursor() method
create a query using the appropriate mysql statements
create a query using the appropriate mysql statements
execute the SQL query using execute() method
execute the SQL query using execute() method
close the connection
close the connection
Suppose, we have a table named “Students”. We want to add a new column named “Address” of type VARCHAR(100) in the table.
import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")
cursor=db.cursor()
query="ALTER TABLE Students ADD Address VARCHAR(100)"
cursor.execute(query)
db.commit()
print("NEW COLUMN ADDED..")
db.close()
The above code adds a new column named “Address” into the table. The column is inserted at the last of the existing columns.
NEW COLUMN ADDED..
|
[
{
"code": null,
"e": 1396,
"s": 1187,
"text": "It may be sometimes required to add a new column in a existing table. Suppose we have a “Students” table with columns such as Name, Age, Roll no. We want to add a new column “Address” into our existing table."
},
{
"code": null,
"e": 1593,
"s": 1396,
"text": "This can be done by using the ALTER command. The ALTER command is used to modify, drop or update columns in the database. This can also be used to add a new column into the table using ADD clause."
},
{
"code": null,
"e": 1687,
"s": 1593,
"text": "ALTER TABLE table_name\nADD new_column_name column_definition\n[FIRST | AFTER exisiting_column]"
},
{
"code": null,
"e": 1855,
"s": 1687,
"text": "Here, table_name refers to the name of the table, new_column_name refers to the name of the column to be added, column_definition refers to the datatype of the column."
},
{
"code": null,
"e": 2123,
"s": 1855,
"text": "The FIRST AND AFTER clause are optional.This are used to specify the particular position at which you want to add the new column. The FIRST will insert the new column at the first position. The AFTER existing_column will insert a new column after the existing_column."
},
{
"code": null,
"e": 2187,
"s": 2123,
"text": "By default, the new column is inserted at the end of the table."
},
{
"code": null,
"e": 2210,
"s": 2187,
"text": "import MySQL connector"
},
{
"code": null,
"e": 2233,
"s": 2210,
"text": "import MySQL connector"
},
{
"code": null,
"e": 2289,
"s": 2233,
"text": "establish connection with the connector using connect()"
},
{
"code": null,
"e": 2345,
"s": 2289,
"text": "establish connection with the connector using connect()"
},
{
"code": null,
"e": 2392,
"s": 2345,
"text": "create the cursor object using cursor() method"
},
{
"code": null,
"e": 2439,
"s": 2392,
"text": "create the cursor object using cursor() method"
},
{
"code": null,
"e": 2493,
"s": 2439,
"text": "create a query using the appropriate mysql statements"
},
{
"code": null,
"e": 2547,
"s": 2493,
"text": "create a query using the appropriate mysql statements"
},
{
"code": null,
"e": 2592,
"s": 2547,
"text": "execute the SQL query using execute() method"
},
{
"code": null,
"e": 2637,
"s": 2592,
"text": "execute the SQL query using execute() method"
},
{
"code": null,
"e": 2658,
"s": 2637,
"text": "close the connection"
},
{
"code": null,
"e": 2679,
"s": 2658,
"text": "close the connection"
},
{
"code": null,
"e": 2801,
"s": 2679,
"text": "Suppose, we have a table named “Students”. We want to add a new column named “Address” of type VARCHAR(100) in the table."
},
{
"code": null,
"e": 3091,
"s": 2801,
"text": "import mysql.connector\ndb=mysql.connector.connect(host=\"your host\", user=\"your username\", password=\"your\npassword\",database=\"database_name\")\n\ncursor=db.cursor()\n\nquery=\"ALTER TABLE Students ADD Address VARCHAR(100)\"\ncursor.execute(query)\ndb.commit()\nprint(\"NEW COLUMN ADDED..\")\n\ndb.close()"
},
{
"code": null,
"e": 3216,
"s": 3091,
"text": "The above code adds a new column named “Address” into the table. The column is inserted at the last of the existing columns."
},
{
"code": null,
"e": 3235,
"s": 3216,
"text": "NEW COLUMN ADDED.."
}
] |
Maven - Web Application
|
This chapter teaches you how to manage a web based project using Maven. Here you will learn how to create/build/deploy and run a web application.
To create a simple java web application, we will use maven-archetype-webapp plugin. So, let's open the command console, go to the C:\MVN directory and execute the following mvn command.
C:\MVN>mvn archetype:generate
-DgroupId = com.companyname.automobile
-DartifactId = trucks
-DarchetypeArtifactId = maven-archetype-webapp
-DinteractiveMode = false
Maven will start processing and will create the complete web based java application project structure as follows −
C:\MVN>mvn archetype:generate -DgroupId=com.companyname.automobile -DartifactId=trucks -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
...
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: package, Value: com.companyname.automobile
[INFO] Parameter: groupId, Value: com.companyname.automobile
[INFO] Parameter: artifactId, Value: trucks
[INFO] Parameter: packageName, Value: com.companyname.automobile
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\trucks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.381 s
[INFO] Finished at: 2021-12-13T19:00:13+05:30
[INFO] ------------------------------------------------------------------------
C:\MVN>
Now go to C:/MVN directory. You'll see a java application project created, named trucks (as specified in artifactId) as specified in the following snapshot. The following directory structure is generally used for web applications −
Maven uses a standard directory layout. Using the above example, we can understand the following key concepts −
trucks
contains src folder and pom.xml.
src/main/webapp
contains index.jsp and WEB-INF folder.
src/main/webapp/WEB-INF
contains web.xml
src/main/resources
it contains images/properties files.
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.automobile</groupId>
<artifactId>trucks</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>trucks Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>trucks</finalName>
</build>
</project>
If you observe, you will find that Maven also created a sample JSP Source file.
Open C:\ > MVN > trucks > src > main > webapp > folder to see index.jsp with the following code −
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
Let's open the command console, go to the C:\MVN\trucks directory and execute the following mvn command.
C:\MVN\trucks>mvn clean package
Maven will start building the project.
C:\MVN\trucks>mvn clean package
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------< com.companyname.automobile:trucks >------------------
[INFO] Building trucks Maven Webapp 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ trucks ---
[INFO] Deleting C:\MVN\trucks\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ trucks ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ trucks ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ trucks ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\trucks\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ trucks ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ trucks ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-war-plugin:2.2:war (default-war) @ trucks ---
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields (file:/C:/Users/intel/.m2/repository/com/thoughtworks/xstream/xstream/1.3.1/xstream-1.3.1.jar) to field java.util.Properties.defaults
WARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
[INFO] Packaging webapp
[INFO] Assembling webapp [trucks] in [C:\MVN\trucks\target\trucks]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\MVN\trucks\src\main\webapp]
[INFO] Webapp assembled in [50 msecs]
[INFO] Building war: C:\MVN\trucks\target\trucks.war
[INFO] WEB-INF\web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.494 s
[INFO] Finished at: 2021-12-13T19:02:15+05:30
[INFO] ------------------------------------------------------------------------
C:\MVN\trucks>
Now copy the trucks.war created in C:\ > MVN > trucks > target > folder to your webserver webapp directory and restart the webserver.
Run the web-application using URL: http://<server-name>:<port-number>/trucks/index.jsp.
Verify the output.
|
[
{
"code": null,
"e": 2340,
"s": 2194,
"text": "This chapter teaches you how to manage a web based project using Maven. Here you will learn how to create/build/deploy and run a web application."
},
{
"code": null,
"e": 2526,
"s": 2340,
"text": "To create a simple java web application, we will use maven-archetype-webapp plugin. So, let's open the command console, go to the C:\\MVN directory and execute the following mvn command."
},
{
"code": null,
"e": 2693,
"s": 2526,
"text": "C:\\MVN>mvn archetype:generate \n-DgroupId = com.companyname.automobile \n-DartifactId = trucks\n-DarchetypeArtifactId = maven-archetype-webapp \n-DinteractiveMode = false"
},
{
"code": null,
"e": 2808,
"s": 2693,
"text": "Maven will start processing and will create the complete web based java application project structure as follows −"
},
{
"code": null,
"e": 4223,
"s": 2808,
"text": "C:\\MVN>mvn archetype:generate -DgroupId=com.companyname.automobile -DartifactId=trucks -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ------------------< org.apache.maven:standalone-pom >-------------------\n[INFO] Building Maven Stub Project (No POM) 1\n[INFO] --------------------------------[ pom ]---------------------------------\n...\n[INFO] ----------------------------------------------------------------------------\n[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0\n[INFO] ----------------------------------------------------------------------------\n[INFO] Parameter: basedir, Value: C:\\MVN\n[INFO] Parameter: package, Value: com.companyname.automobile\n[INFO] Parameter: groupId, Value: com.companyname.automobile\n[INFO] Parameter: artifactId, Value: trucks\n[INFO] Parameter: packageName, Value: com.companyname.automobile\n[INFO] Parameter: version, Value: 1.0-SNAPSHOT\n[INFO] project created from Old (1.x) Archetype in dir: C:\\MVN\\trucks\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 10.381 s\n[INFO] Finished at: 2021-12-13T19:00:13+05:30\n[INFO] ------------------------------------------------------------------------\nC:\\MVN>\n"
},
{
"code": null,
"e": 4455,
"s": 4223,
"text": "Now go to C:/MVN directory. You'll see a java application project created, named trucks (as specified in artifactId) as specified in the following snapshot. The following directory structure is generally used for web applications −"
},
{
"code": null,
"e": 4567,
"s": 4455,
"text": "Maven uses a standard directory layout. Using the above example, we can understand the following key concepts −"
},
{
"code": null,
"e": 4574,
"s": 4567,
"text": "trucks"
},
{
"code": null,
"e": 4607,
"s": 4574,
"text": "contains src folder and pom.xml."
},
{
"code": null,
"e": 4623,
"s": 4607,
"text": "src/main/webapp"
},
{
"code": null,
"e": 4662,
"s": 4623,
"text": "contains index.jsp and WEB-INF folder."
},
{
"code": null,
"e": 4686,
"s": 4662,
"text": "src/main/webapp/WEB-INF"
},
{
"code": null,
"e": 4703,
"s": 4686,
"text": "contains web.xml"
},
{
"code": null,
"e": 4722,
"s": 4703,
"text": "src/main/resources"
},
{
"code": null,
"e": 4759,
"s": 4722,
"text": "it contains images/properties files."
},
{
"code": null,
"e": 5521,
"s": 4759,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/maven-v4_0_0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.automobile</groupId>\n <artifactId>trucks</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>trucks Maven Webapp</name>\n <url>http://maven.apache.org</url>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n <build>\n <finalName>trucks</finalName>\n </build>\n</project>"
},
{
"code": null,
"e": 5601,
"s": 5521,
"text": "If you observe, you will find that Maven also created a sample JSP Source file."
},
{
"code": null,
"e": 5699,
"s": 5601,
"text": "Open C:\\ > MVN > trucks > src > main > webapp > folder to see index.jsp with the following code −"
},
{
"code": null,
"e": 5763,
"s": 5699,
"text": "<html>\n <body>\n <h2>Hello World!</h2>\n </body>\n</html>"
},
{
"code": null,
"e": 5868,
"s": 5763,
"text": "Let's open the command console, go to the C:\\MVN\\trucks directory and execute the following mvn command."
},
{
"code": null,
"e": 5900,
"s": 5868,
"text": "C:\\MVN\\trucks>mvn clean package"
},
{
"code": null,
"e": 5939,
"s": 5900,
"text": "Maven will start building the project."
},
{
"code": null,
"e": 8482,
"s": 5939,
"text": "\nC:\\MVN\\trucks>mvn clean package\n[INFO] Scanning for projects...\n[INFO]\n[INFO] -----------------< com.companyname.automobile:trucks >------------------\n[INFO] Building trucks Maven Webapp 1.0-SNAPSHOT\n[INFO] --------------------------------[ war ]---------------------------------\n[INFO]\n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ trucks ---\n[INFO] Deleting C:\\MVN\\trucks\\target\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ trucks ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] Copying 0 resource\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ trucks ---\n[INFO] No sources to compile\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ trucks ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\trucks\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ trucks ---\n[INFO] No sources to compile\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ trucks ---\n[INFO] No tests to run.\n[INFO]\n[INFO] --- maven-war-plugin:2.2:war (default-war) @ trucks ---\nWARNING: An illegal reflective access operation has occurred\nWARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields (file:/C:/Users/intel/.m2/repository/com/thoughtworks/xstream/xstream/1.3.1/xstream-1.3.1.jar) to field java.util.Properties.defaults\nWARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields\nWARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations\nWARNING: All illegal access operations will be denied in a future release\n[INFO] Packaging webapp\n[INFO] Assembling webapp [trucks] in [C:\\MVN\\trucks\\target\\trucks]\n[INFO] Processing war project\n[INFO] Copying webapp resources [C:\\MVN\\trucks\\src\\main\\webapp]\n[INFO] Webapp assembled in [50 msecs]\n[INFO] Building war: C:\\MVN\\trucks\\target\\trucks.war\n[INFO] WEB-INF\\web.xml already added, skipping\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 2.494 s\n[INFO] Finished at: 2021-12-13T19:02:15+05:30\n[INFO] ------------------------------------------------------------------------\nC:\\MVN\\trucks>\n"
},
{
"code": null,
"e": 8616,
"s": 8482,
"text": "Now copy the trucks.war created in C:\\ > MVN > trucks > target > folder to your webserver webapp directory and restart the webserver."
},
{
"code": null,
"e": 8704,
"s": 8616,
"text": "Run the web-application using URL: http://<server-name>:<port-number>/trucks/index.jsp."
}
] |
Fabric.js Canvas backgroundImage Property
|
30 Jul, 2021
In this article, we are going to see how to set the background image of a Canvas in Fabric.js using the backgroundImage property. The Canvas in Fabric.js is used as a wrapper over the native canvas object provided by HTML. It provides high-level access to the underlying canvas allowing it to have an object model, allow parsing for SVG files, and allowing the canvas to be interacted with in an intuitive manner.
Approach: To make it possible we are going to use a JavaScript library called Fabric.js. After importing the library, we will create the canvas block in the body tag. After this, we will initialize an instance of the canvas object provided by Fabric.js and change the background image of the canvas using the backgroundImage property.
Syntax:
fabric.Canvas(canvasElement, {
backgroundImage: String | Fabric.Image
});
Parameters: This property accepts a single parameter as mentioned above and described below.
backgroundImage: It is a string containing the image URL or a Fabric.Image object that specifies the background image of the Canvas.
The below examples illustrate the use of Fabric.js Canvas backgroundImage property in JavaScript.
Example 1: This example uses a string URL to change the background image of the Canvas.
HTML
<!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <div style="text-align:center;width:500px;"> <h1 style="color:green;"> GeeksforGeeks </h1> <b> Fabric.js | Canvas backgroundImage Property </b> </div> <canvas id="canvas" width="660" height="250" style="border:1px solid #000000"> </canvas> <script> // Initiate a Canvas instance let canvas = new fabric.Canvas("canvas", { // Set the background image // of the Canvas backgroundImage:"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" }); </script></body> </html>
Output:
Example 2: This example uses a Fabric.Image object to change the background image of the Canvas.
HTML
<!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <div style="text-align: center; width:660px;"> <h1 style="color:green;"> GeeksforGeeks </h1> <b> Fabric.js | Canvas backgroundImage Property </b> </div> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" id="my_img" style="display:none"> <canvas id="canvas" width="660" height="250" style="border:1px solid #000000"> </canvas> <script> // Select the image from the document let selectedImage = document.querySelector("#my_img"); // Create a Fabric.Image object let bg_img = new fabric.Image(selectedImage); // Initiate a Canvas instance let canvas = new fabric.Canvas("canvas", { // Set the background image // of the Canvas to the above // Fabric.Image object backgroundImage: bg_img }); </script></body> </html>
Output:
Fabric.js
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 442,
"s": 28,
"text": "In this article, we are going to see how to set the background image of a Canvas in Fabric.js using the backgroundImage property. The Canvas in Fabric.js is used as a wrapper over the native canvas object provided by HTML. It provides high-level access to the underlying canvas allowing it to have an object model, allow parsing for SVG files, and allowing the canvas to be interacted with in an intuitive manner."
},
{
"code": null,
"e": 777,
"s": 442,
"text": "Approach: To make it possible we are going to use a JavaScript library called Fabric.js. After importing the library, we will create the canvas block in the body tag. After this, we will initialize an instance of the canvas object provided by Fabric.js and change the background image of the canvas using the backgroundImage property."
},
{
"code": null,
"e": 785,
"s": 777,
"text": "Syntax:"
},
{
"code": null,
"e": 863,
"s": 785,
"text": "fabric.Canvas(canvasElement, {\n backgroundImage: String | Fabric.Image\n});"
},
{
"code": null,
"e": 956,
"s": 863,
"text": "Parameters: This property accepts a single parameter as mentioned above and described below."
},
{
"code": null,
"e": 1089,
"s": 956,
"text": "backgroundImage: It is a string containing the image URL or a Fabric.Image object that specifies the background image of the Canvas."
},
{
"code": null,
"e": 1189,
"s": 1091,
"text": "The below examples illustrate the use of Fabric.js Canvas backgroundImage property in JavaScript."
},
{
"code": null,
"e": 1277,
"s": 1189,
"text": "Example 1: This example uses a string URL to change the background image of the Canvas."
},
{
"code": null,
"e": 1282,
"s": 1277,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <div style=\"text-align:center;width:500px;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> Fabric.js | Canvas backgroundImage Property </b> </div> <canvas id=\"canvas\" width=\"660\" height=\"250\" style=\"border:1px solid #000000\"> </canvas> <script> // Initiate a Canvas instance let canvas = new fabric.Canvas(\"canvas\", { // Set the background image // of the Canvas backgroundImage:\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" }); </script></body> </html>",
"e": 2096,
"s": 1282,
"text": null
},
{
"code": null,
"e": 2104,
"s": 2096,
"text": "Output:"
},
{
"code": null,
"e": 2201,
"s": 2104,
"text": "Example 2: This example uses a Fabric.Image object to change the background image of the Canvas."
},
{
"code": null,
"e": 2206,
"s": 2201,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <div style=\"text-align: center; width:660px;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> Fabric.js | Canvas backgroundImage Property </b> </div> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" id=\"my_img\" style=\"display:none\"> <canvas id=\"canvas\" width=\"660\" height=\"250\" style=\"border:1px solid #000000\"> </canvas> <script> // Select the image from the document let selectedImage = document.querySelector(\"#my_img\"); // Create a Fabric.Image object let bg_img = new fabric.Image(selectedImage); // Initiate a Canvas instance let canvas = new fabric.Canvas(\"canvas\", { // Set the background image // of the Canvas to the above // Fabric.Image object backgroundImage: bg_img }); </script></body> </html>",
"e": 3358,
"s": 2206,
"text": null
},
{
"code": null,
"e": 3366,
"s": 3358,
"text": "Output:"
},
{
"code": null,
"e": 3376,
"s": 3366,
"text": "Fabric.js"
},
{
"code": null,
"e": 3381,
"s": 3376,
"text": "HTML"
},
{
"code": null,
"e": 3392,
"s": 3381,
"text": "JavaScript"
},
{
"code": null,
"e": 3409,
"s": 3392,
"text": "Web Technologies"
},
{
"code": null,
"e": 3414,
"s": 3409,
"text": "HTML"
}
] |
Java Program to Multiply Corresponding Elements of Two Lists
|
07 Jan, 2021
Multiplying two corresponding elements implies multiplying the first element of the one list with the first element of another list and so on with the second element till the size of the list. Given 2 lists of elements, we have to multiply the corresponding elements of two lists.
This can be done in 2 ways:
Using extra spaceWithout Using extra space
Using extra space
Without Using extra space
Method 1: (Using Extra Space) – You can multiply the corresponding elements and store them in a string using the in-built function Integer.toString and print the string at last.
Java
// Java program to multiply the corresponding elements of// two list. using string in-built function import java.util.Arrays; class GFG { public static void main(String[] args) { int a1[] = { 2, 5, -2, 10 }; int a2[] = { 3, -5, 7, 1 }; String result = ""; for (int i = 0; i < a1.length; i++) { // converting integer to string and // multiplying corresponding element result += Integer.toString(a1[i] * a2[i]) + " "; } System.out.println(result); }}
6 -25 -14 10
Space Complexity: O(n)
Now instead of using string we can also store the output in the new array if we want to use the result later in the program.
Java
// Java program to cmultiply the corresponding elements of// two list. using new array import java.util.Arrays; class GFG { public static void main(String[] args) { int a1[] = { 2, 5, -2, 10 }; int a2[] = { 3, -5, 7, 1 }; int result[] = new int[a1.length]; for (int i = 0; i < a1.length; i++) { // multiplying corresponding element result[i] = a1[i] * a2[i]; } for (int i = 0; i < a1.length; i++) { System.out.print(result[i] + " "); } }}
6 -25 -14 10
Space Complexity: O(n)
Method 2: (Without using extra space)
This is the same as the above-mentioned approach. The only difference is instead of using the extra array we will use any of the 2 arrays used in input to store values of the output or after multiplication.
Java
// Java program to multiply the corresponding elements of// two list. using no extra space import java.util.Arrays; class GFG { public static void main(String[] args) { int a1[] = { 2, 5, -2, 10 }; int a2[] = { 3, -5, 7, 1 }; for (int i = 0; i < a1.length; i++) { // multiplying corresponding element // you can use any array a1[i] = a1[i] * a2[i]; } for (int i = 0; i < a1.length; i++) { System.out.print(a1[i] + " "); } }}
6 -25 -14 10
Space Complexity: O(1) (as we do not use any other auxiliary space)
Note: Time Complexity of all the above codes is O(n).
Java-Collections
java-list
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "Multiplying two corresponding elements implies multiplying the first element of the one list with the first element of another list and so on with the second element till the size of the list. Given 2 lists of elements, we have to multiply the corresponding elements of two lists."
},
{
"code": null,
"e": 337,
"s": 309,
"text": "This can be done in 2 ways:"
},
{
"code": null,
"e": 380,
"s": 337,
"text": "Using extra spaceWithout Using extra space"
},
{
"code": null,
"e": 398,
"s": 380,
"text": "Using extra space"
},
{
"code": null,
"e": 424,
"s": 398,
"text": "Without Using extra space"
},
{
"code": null,
"e": 602,
"s": 424,
"text": "Method 1: (Using Extra Space) – You can multiply the corresponding elements and store them in a string using the in-built function Integer.toString and print the string at last."
},
{
"code": null,
"e": 607,
"s": 602,
"text": "Java"
},
{
"code": "// Java program to multiply the corresponding elements of// two list. using string in-built function import java.util.Arrays; class GFG { public static void main(String[] args) { int a1[] = { 2, 5, -2, 10 }; int a2[] = { 3, -5, 7, 1 }; String result = \"\"; for (int i = 0; i < a1.length; i++) { // converting integer to string and // multiplying corresponding element result += Integer.toString(a1[i] * a2[i]) + \" \"; } System.out.println(result); }}",
"e": 1148,
"s": 607,
"text": null
},
{
"code": null,
"e": 1161,
"s": 1148,
"text": "6 -25 -14 10"
},
{
"code": null,
"e": 1184,
"s": 1161,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 1309,
"s": 1184,
"text": "Now instead of using string we can also store the output in the new array if we want to use the result later in the program."
},
{
"code": null,
"e": 1314,
"s": 1309,
"text": "Java"
},
{
"code": "// Java program to cmultiply the corresponding elements of// two list. using new array import java.util.Arrays; class GFG { public static void main(String[] args) { int a1[] = { 2, 5, -2, 10 }; int a2[] = { 3, -5, 7, 1 }; int result[] = new int[a1.length]; for (int i = 0; i < a1.length; i++) { // multiplying corresponding element result[i] = a1[i] * a2[i]; } for (int i = 0; i < a1.length; i++) { System.out.print(result[i] + \" \"); } }}",
"e": 1867,
"s": 1314,
"text": null
},
{
"code": null,
"e": 1880,
"s": 1867,
"text": "6 -25 -14 10"
},
{
"code": null,
"e": 1903,
"s": 1880,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 1941,
"s": 1903,
"text": "Method 2: (Without using extra space)"
},
{
"code": null,
"e": 2148,
"s": 1941,
"text": "This is the same as the above-mentioned approach. The only difference is instead of using the extra array we will use any of the 2 arrays used in input to store values of the output or after multiplication."
},
{
"code": null,
"e": 2153,
"s": 2148,
"text": "Java"
},
{
"code": "// Java program to multiply the corresponding elements of// two list. using no extra space import java.util.Arrays; class GFG { public static void main(String[] args) { int a1[] = { 2, 5, -2, 10 }; int a2[] = { 3, -5, 7, 1 }; for (int i = 0; i < a1.length; i++) { // multiplying corresponding element // you can use any array a1[i] = a1[i] * a2[i]; } for (int i = 0; i < a1.length; i++) { System.out.print(a1[i] + \" \"); } }}",
"e": 2691,
"s": 2153,
"text": null
},
{
"code": null,
"e": 2704,
"s": 2691,
"text": "6 -25 -14 10"
},
{
"code": null,
"e": 2772,
"s": 2704,
"text": "Space Complexity: O(1) (as we do not use any other auxiliary space)"
},
{
"code": null,
"e": 2826,
"s": 2772,
"text": "Note: Time Complexity of all the above codes is O(n)."
},
{
"code": null,
"e": 2843,
"s": 2826,
"text": "Java-Collections"
},
{
"code": null,
"e": 2853,
"s": 2843,
"text": "java-list"
},
{
"code": null,
"e": 2860,
"s": 2853,
"text": "Picked"
},
{
"code": null,
"e": 2865,
"s": 2860,
"text": "Java"
},
{
"code": null,
"e": 2879,
"s": 2865,
"text": "Java Programs"
},
{
"code": null,
"e": 2884,
"s": 2879,
"text": "Java"
},
{
"code": null,
"e": 2901,
"s": 2884,
"text": "Java-Collections"
},
{
"code": null,
"e": 2999,
"s": 2901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3014,
"s": 2999,
"text": "Stream In Java"
},
{
"code": null,
"e": 3035,
"s": 3014,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3056,
"s": 3035,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3075,
"s": 3056,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3092,
"s": 3075,
"text": "Generics in Java"
},
{
"code": null,
"e": 3118,
"s": 3092,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3152,
"s": 3118,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 3199,
"s": 3152,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 3237,
"s": 3199,
"text": "Factory method design pattern in Java"
}
] |
JavaScript | Nested functions
|
02 Dec, 2021
Here the task is to create nested functions, JavaScript support nested functions. In the examples given below the output returning is combination of the output from the outer as well as inner function(nested function).Approach:
Write one function inside another function.
Make a call to the inner function in the return statement of the outer function.
Call it fun(a)(b) where a is parameter to outer and b is to the inner function.
Finally return the combined output from the nested function.
Example 1: This example using the approach discussed above.
<!DOCTYPE HTML> <html> <head> <title> Nested functions in JavaScript. </title> </head> <body id = "body" style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to call nested function."; function fun1(a) { function fun2(b) { return a + b; } return fun2; } function GFG_Fun() { down.innerHTML = fun1("A Online Computer Science Portal") (" GeeksforGeeks"); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example using the approach discussed above, but here the nested function is created differently than previous one.
<!DOCTYPE HTML> <html> <head> <title> Nested functions in JavaScript. </title> </head> <body id = "body" style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to call nested function."; function fun1(a) { fun = function fun2(b) { return a + b; } return fun; } function GFG_Fun() { down.innerHTML = fun1("This is ")("GeeksforGeeks"); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Supported Browser:
Google Chrome
Edge
Firefox
Opera
Safari
ysachin2314
javascript-functions
JavaScript
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
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
Node.js | fs.writeFileSync() Method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 256,
"s": 28,
"text": "Here the task is to create nested functions, JavaScript support nested functions. In the examples given below the output returning is combination of the output from the outer as well as inner function(nested function).Approach:"
},
{
"code": null,
"e": 300,
"s": 256,
"text": "Write one function inside another function."
},
{
"code": null,
"e": 381,
"s": 300,
"text": "Make a call to the inner function in the return statement of the outer function."
},
{
"code": null,
"e": 461,
"s": 381,
"text": "Call it fun(a)(b) where a is parameter to outer and b is to the inner function."
},
{
"code": null,
"e": 522,
"s": 461,
"text": "Finally return the combined output from the nested function."
},
{
"code": null,
"e": 582,
"s": 522,
"text": "Example 1: This example using the approach discussed above."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Nested functions in JavaScript. </title> </head> <body id = \"body\" style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to call nested function.\"; function fun1(a) { function fun2(b) { return a + b; } return fun2; } function GFG_Fun() { down.innerHTML = fun1(\"A Online Computer Science Portal\") (\" GeeksforGeeks\"); } </script> </body> </html> ",
"e": 1758,
"s": 582,
"text": null
},
{
"code": null,
"e": 1766,
"s": 1758,
"text": "Output:"
},
{
"code": null,
"e": 1797,
"s": 1766,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1827,
"s": 1797,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1958,
"s": 1827,
"text": "Example 2: This example using the approach discussed above, but here the nested function is created differently than previous one."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Nested functions in JavaScript. </title> </head> <body id = \"body\" style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to call nested function.\"; function fun1(a) { fun = function fun2(b) { return a + b; } return fun; } function GFG_Fun() { down.innerHTML = fun1(\"This is \")(\"GeeksforGeeks\"); } </script> </body> </html> ",
"e": 3032,
"s": 1958,
"text": null
},
{
"code": null,
"e": 3040,
"s": 3032,
"text": "Output:"
},
{
"code": null,
"e": 3071,
"s": 3040,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3101,
"s": 3071,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3320,
"s": 3101,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3339,
"s": 3320,
"text": "Supported Browser:"
},
{
"code": null,
"e": 3353,
"s": 3339,
"text": "Google Chrome"
},
{
"code": null,
"e": 3358,
"s": 3353,
"text": "Edge"
},
{
"code": null,
"e": 3366,
"s": 3358,
"text": "Firefox"
},
{
"code": null,
"e": 3372,
"s": 3366,
"text": "Opera"
},
{
"code": null,
"e": 3379,
"s": 3372,
"text": "Safari"
},
{
"code": null,
"e": 3391,
"s": 3379,
"text": "ysachin2314"
},
{
"code": null,
"e": 3412,
"s": 3391,
"text": "javascript-functions"
},
{
"code": null,
"e": 3423,
"s": 3412,
"text": "JavaScript"
},
{
"code": null,
"e": 3521,
"s": 3423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3582,
"s": 3521,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3654,
"s": 3582,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3694,
"s": 3654,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3746,
"s": 3694,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3787,
"s": 3746,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3833,
"s": 3787,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 3875,
"s": 3833,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3929,
"s": 3875,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 3984,
"s": 3929,
"text": "How do you run JavaScript script through the Terminal?"
}
] |
Explain the evaluation of relational algebra expression(DBMS)
|
SQL queries are decomposed into query blocks. One query block contains a single SELECT-FROM-WHERE expression, as well as GROUP BY and HAVING clause (if any). Nested queries are split into separate query blocks.
Consider an example given below −
Select lastname, firstname from employee where salary>(select max(salary) from employee where deptname =CSE ;
C=(select max(salary) from employee where deptname=CSE); // inner block
Select lastname, firstname from employee where salary>c; //outer block
Where C represents the result returned from the inner block.
The relation algebra for the inner block is Ģmax(salary) (σdname=CSE(employee))
The relation algebra for the inner block is Ģmax(salary) (σdname=CSE(employee))
The relation algebra for the outer blocks is Πlastname, firstname(σsalary>c(employee))
The relation algebra for the outer blocks is Πlastname, firstname(σsalary>c(employee))
The query optimizer would then choose an execution or evaluation plan for each block.
Materialized evaluation − Evaluate one operation at a time. Evaluate the expression in a bottom-up manner and stores intermediate results to temporary files.
Store the result of A ⋈ B in a temporary file.
Store the result of C ⋈ D in a temporary file.
Finally, join the results stored in temporary files.
The overall cost=sum of costs of individual operations + cost of writing intermediate results to disk, cost of writing results to results to temporary files and reading them back is quite high.
Pipelined evaluation − Evaluate several operations simultaneously. Result of one operation is passed to the next operation. Evaluate the expression in a bottom-up manner and don’t store intermediate results to temporary files.
Don’t store the result of A ⋈ B in a temporary file. Instead the result is passed directly for projection with C and so on.
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "SQL queries are decomposed into query blocks. One query block contains a single SELECT-FROM-WHERE expression, as well as GROUP BY and HAVING clause (if any). Nested queries are split into separate query blocks."
},
{
"code": null,
"e": 1307,
"s": 1273,
"text": "Consider an example given below −"
},
{
"code": null,
"e": 1560,
"s": 1307,
"text": "Select lastname, firstname from employee where salary>(select max(salary) from employee where deptname =CSE ;\nC=(select max(salary) from employee where deptname=CSE); // inner block\nSelect lastname, firstname from employee where salary>c; //outer block"
},
{
"code": null,
"e": 1621,
"s": 1560,
"text": "Where C represents the result returned from the inner block."
},
{
"code": null,
"e": 1702,
"s": 1621,
"text": "The relation algebra for the inner block is Ģmax(salary) (σdname=CSE(employee))"
},
{
"code": null,
"e": 1783,
"s": 1702,
"text": "The relation algebra for the inner block is Ģmax(salary) (σdname=CSE(employee))"
},
{
"code": null,
"e": 1870,
"s": 1783,
"text": "The relation algebra for the outer blocks is Πlastname, firstname(σsalary>c(employee))"
},
{
"code": null,
"e": 1957,
"s": 1870,
"text": "The relation algebra for the outer blocks is Πlastname, firstname(σsalary>c(employee))"
},
{
"code": null,
"e": 2043,
"s": 1957,
"text": "The query optimizer would then choose an execution or evaluation plan for each block."
},
{
"code": null,
"e": 2201,
"s": 2043,
"text": "Materialized evaluation − Evaluate one operation at a time. Evaluate the expression in a bottom-up manner and stores intermediate results to temporary files."
},
{
"code": null,
"e": 2248,
"s": 2201,
"text": "Store the result of A ⋈ B in a temporary file."
},
{
"code": null,
"e": 2295,
"s": 2248,
"text": "Store the result of C ⋈ D in a temporary file."
},
{
"code": null,
"e": 2348,
"s": 2295,
"text": "Finally, join the results stored in temporary files."
},
{
"code": null,
"e": 2542,
"s": 2348,
"text": "The overall cost=sum of costs of individual operations + cost of writing intermediate results to disk, cost of writing results to results to temporary files and reading them back is quite high."
},
{
"code": null,
"e": 2769,
"s": 2542,
"text": "Pipelined evaluation − Evaluate several operations simultaneously. Result of one operation is passed to the next operation. Evaluate the expression in a bottom-up manner and don’t store intermediate results to temporary files."
},
{
"code": null,
"e": 2893,
"s": 2769,
"text": "Don’t store the result of A ⋈ B in a temporary file. Instead the result is passed directly for projection with C and so on."
}
] |
UpSetR is the Greatest Set Visualization Since the Venn Diagram | by Eliana Grosof | Towards Data Science
|
I firmly believe that UpSetR is the most beautiful, intuitive set intersection visualization of large, complex sets I’ve ever seen.
Venn Diagrams make me smile, but UpSetR makes me feel powerful. UpSetR can visualize data Venn Diagrams can only dream about.
But first, let’s review Venn Diagrams.
Venn Diagrams are ubiquitous in our culture today. They’re easy to read, effective at getting information across, and generally fun to play with. But if you want to visualize more than three categories, what do you do?
Let’s look at a simple example.
Suppose we have a dataset about countries in the world, and we have a little bit of information about each.
A Venn Diagram visualizing the similarities and differences between the different countries might look like this:
This diagram looks pretty, but I’m not able to represent much, and it can start to look disorganized really fast.
What if I wanted to compare another country? Well, I’m out of luck. Do you really want to try to decipher something like this? What about this?
Yeah, I didn’t think so.
UpSet is a very new visualization technique that solves this problem by presenting the information in a table format with bar graphs. You can have as many things in each category as you want, and find the intersections between them easily. UpSetR is an R package that implements it.
Have a dataset from IMDB and see how many movies share the same actors, and who they are? No problem! Want to see if cancer patients have the same set of mutations in their genes, and what they are? UpSetR is here for you!
UpSetR is best for finding patterns within complex datasets with a lot of features. It does this by grouping data points that have many of the same values across different features together. That is, UpSetR finds the largest intersecting sets.
It is best for variables that are already binary (that means two categories), or can be converted into them. It’s important to note that one-hot encoding can turn any categorical feature into a binary feature. In fact, the current implementations only work for binary variables.
I’m in the process of developing a classification model for this Kaggle dataset, and I am trying to understand how the different columns relate to each other.
The dataset contains information about the attitudes of technology companies towards mental health, and the mental health of their employees. The survey data contains answers to everything from whether the employer provides mental health benefits to whether the employee themself has been treated for mental health issues.
At this point, it’s very unclear how each of these features relate to each other, and I’d like to get a sense of what’s going on.
Previously, I’ve cleaned the data a little bit, so I’ll feed it into R now. However, before I create the UpSetR visualization, I want to one-hot encode my data because it’s mostly categorical data.
One-hot encoding
Without getting too in depth, one-hot encoding is a way of turning categorical variables into binary variables by making new columns. For example, our work_interfere column has 3 options: often, sometimes, never. After we one-hot encode our data, we will have 3 columns: work_intefere_often, work_interfere_sometimes, work_interfere_never, each containing a 1 if that value applies and a 0 if not. There’s a lot of great tutorials about it on the internet if you want to learn more.
Here’s the R code:
data = read.csv('survey_data.csv', na.strings="Not Applicable")#install packages (can skip if already installed)install.packages("mltools") install.packages("data.table")install.packages("UpSetR")#one-hot encodelibrary(mltools)library(data.table)newdata <- one_hot(as.data.table(data))#create the visualizationlibrary(UpSetR)upset(newdata, order.by=”freq”, main.bar.color = “#995ee1”, sets.bar.color = “#995ee1”, group.by = ‘degree’)
You can download the survey data here.
You’ll end up with this lovely thing:
How to interpret it
Left side bars
On the left side, there are bars that represent the total size of each set. In the case of Gender_Male, we can see that there are something like 950 survey respondents who identified their gender as Male. These sets are not disjoint — that is, mental_interview_No includes all of the people regardless of Gender who answered “No” to the question “Would you bring up a mental health issue with a potential employer in an interview?”
Top bars
Across the top, we can see the size of each intersecting set. If a black dot is filled in, then that category is included in the set. If the dot is gray, then that category is not in the set. Note that the sets are disjoint, which means that they are non-overlapping. You can see roughly every data point represented uniquely in the bars across the top, unlike the bars on the left.
Example 1: Since all of the dots on the first bar from the left are filled in, that bar represents all 475 of the people who responded Male to the question represented by the Gender variable, “No” to mental_health_interview, obs_consequence, and self_employed, and “Yes” to tech_company.
Example 2: However, the second set from the right represents a single man (Gender_Male) who had not heard of or observed negative consequences for coworkers with mental health conditions in their workplace (obs_consequence) but was self-employed at a tech company and would mention mental health in an interview. We know that the worker was self-employed and would have mentioned mental health in an interview, based on the fact that certain dots were not selected in the visualization and our knowledge of the other possible options.
In this visualization, it’s very important to think about the information that does not appear in the visualization, as in the second example. In some cases, that’s the most interesting part.
Let’s look at the first column from the left (Example 1).
I know that I have about 1200 data points, 988 of whom identify as male.The fact that 475 men said that they would not bring up a mental health issue with a potential employer in an interview mental_health_interview_No, were currently working for a tech company tech_company_Yes, had not heard of or observed negative consequences for coworkers with mental health conditions in their workplace obs_consequence_No, and were not self-employed self_employed_No is significant because it reveals that nearly half of men (48%) and over a third (33%) of all survey-takers responded in this exact same way.
If you add in the 132 people who were not men who also responded the same way to those four questions, as we can see in the second column from the left, then you realize that nearly HALF of the entire dataset answered those four questions exactly the same way (48%).
Interpretation
These results suggest to me that people, perhaps especially men, don’t talk openly about mental health in their workplace. This is an interesting preliminary finding.
Potential Improvements
If I want to improve my analysis, I could turn ordinal variables (variables with a sense of order, like a scale from 1–5, or “none, some, a lot”) into binary variables that preserve some sense of hierarchy by binning them (separating related values into two composite categories). This would allow them to factor more strongly into UpSetR’s analysis because UpSetR would have fewer options to consider.
I adore the UpSetR package and think it’s a beautiful way to do exploratory data analysis. The documentation for it is decent, and there’s a Python version of it available.
If you have any questions or comments, please reach out! I hope you learn to love this visualization as much as I do.
|
[
{
"code": null,
"e": 304,
"s": 172,
"text": "I firmly believe that UpSetR is the most beautiful, intuitive set intersection visualization of large, complex sets I’ve ever seen."
},
{
"code": null,
"e": 430,
"s": 304,
"text": "Venn Diagrams make me smile, but UpSetR makes me feel powerful. UpSetR can visualize data Venn Diagrams can only dream about."
},
{
"code": null,
"e": 469,
"s": 430,
"text": "But first, let’s review Venn Diagrams."
},
{
"code": null,
"e": 688,
"s": 469,
"text": "Venn Diagrams are ubiquitous in our culture today. They’re easy to read, effective at getting information across, and generally fun to play with. But if you want to visualize more than three categories, what do you do?"
},
{
"code": null,
"e": 720,
"s": 688,
"text": "Let’s look at a simple example."
},
{
"code": null,
"e": 828,
"s": 720,
"text": "Suppose we have a dataset about countries in the world, and we have a little bit of information about each."
},
{
"code": null,
"e": 942,
"s": 828,
"text": "A Venn Diagram visualizing the similarities and differences between the different countries might look like this:"
},
{
"code": null,
"e": 1056,
"s": 942,
"text": "This diagram looks pretty, but I’m not able to represent much, and it can start to look disorganized really fast."
},
{
"code": null,
"e": 1200,
"s": 1056,
"text": "What if I wanted to compare another country? Well, I’m out of luck. Do you really want to try to decipher something like this? What about this?"
},
{
"code": null,
"e": 1225,
"s": 1200,
"text": "Yeah, I didn’t think so."
},
{
"code": null,
"e": 1508,
"s": 1225,
"text": "UpSet is a very new visualization technique that solves this problem by presenting the information in a table format with bar graphs. You can have as many things in each category as you want, and find the intersections between them easily. UpSetR is an R package that implements it."
},
{
"code": null,
"e": 1731,
"s": 1508,
"text": "Have a dataset from IMDB and see how many movies share the same actors, and who they are? No problem! Want to see if cancer patients have the same set of mutations in their genes, and what they are? UpSetR is here for you!"
},
{
"code": null,
"e": 1975,
"s": 1731,
"text": "UpSetR is best for finding patterns within complex datasets with a lot of features. It does this by grouping data points that have many of the same values across different features together. That is, UpSetR finds the largest intersecting sets."
},
{
"code": null,
"e": 2254,
"s": 1975,
"text": "It is best for variables that are already binary (that means two categories), or can be converted into them. It’s important to note that one-hot encoding can turn any categorical feature into a binary feature. In fact, the current implementations only work for binary variables."
},
{
"code": null,
"e": 2413,
"s": 2254,
"text": "I’m in the process of developing a classification model for this Kaggle dataset, and I am trying to understand how the different columns relate to each other."
},
{
"code": null,
"e": 2736,
"s": 2413,
"text": "The dataset contains information about the attitudes of technology companies towards mental health, and the mental health of their employees. The survey data contains answers to everything from whether the employer provides mental health benefits to whether the employee themself has been treated for mental health issues."
},
{
"code": null,
"e": 2866,
"s": 2736,
"text": "At this point, it’s very unclear how each of these features relate to each other, and I’d like to get a sense of what’s going on."
},
{
"code": null,
"e": 3064,
"s": 2866,
"text": "Previously, I’ve cleaned the data a little bit, so I’ll feed it into R now. However, before I create the UpSetR visualization, I want to one-hot encode my data because it’s mostly categorical data."
},
{
"code": null,
"e": 3081,
"s": 3064,
"text": "One-hot encoding"
},
{
"code": null,
"e": 3564,
"s": 3081,
"text": "Without getting too in depth, one-hot encoding is a way of turning categorical variables into binary variables by making new columns. For example, our work_interfere column has 3 options: often, sometimes, never. After we one-hot encode our data, we will have 3 columns: work_intefere_often, work_interfere_sometimes, work_interfere_never, each containing a 1 if that value applies and a 0 if not. There’s a lot of great tutorials about it on the internet if you want to learn more."
},
{
"code": null,
"e": 3583,
"s": 3564,
"text": "Here’s the R code:"
},
{
"code": null,
"e": 4018,
"s": 3583,
"text": "data = read.csv('survey_data.csv', na.strings=\"Not Applicable\")#install packages (can skip if already installed)install.packages(\"mltools\") install.packages(\"data.table\")install.packages(\"UpSetR\")#one-hot encodelibrary(mltools)library(data.table)newdata <- one_hot(as.data.table(data))#create the visualizationlibrary(UpSetR)upset(newdata, order.by=”freq”, main.bar.color = “#995ee1”, sets.bar.color = “#995ee1”, group.by = ‘degree’) "
},
{
"code": null,
"e": 4057,
"s": 4018,
"text": "You can download the survey data here."
},
{
"code": null,
"e": 4095,
"s": 4057,
"text": "You’ll end up with this lovely thing:"
},
{
"code": null,
"e": 4115,
"s": 4095,
"text": "How to interpret it"
},
{
"code": null,
"e": 4130,
"s": 4115,
"text": "Left side bars"
},
{
"code": null,
"e": 4562,
"s": 4130,
"text": "On the left side, there are bars that represent the total size of each set. In the case of Gender_Male, we can see that there are something like 950 survey respondents who identified their gender as Male. These sets are not disjoint — that is, mental_interview_No includes all of the people regardless of Gender who answered “No” to the question “Would you bring up a mental health issue with a potential employer in an interview?”"
},
{
"code": null,
"e": 4571,
"s": 4562,
"text": "Top bars"
},
{
"code": null,
"e": 4954,
"s": 4571,
"text": "Across the top, we can see the size of each intersecting set. If a black dot is filled in, then that category is included in the set. If the dot is gray, then that category is not in the set. Note that the sets are disjoint, which means that they are non-overlapping. You can see roughly every data point represented uniquely in the bars across the top, unlike the bars on the left."
},
{
"code": null,
"e": 5242,
"s": 4954,
"text": "Example 1: Since all of the dots on the first bar from the left are filled in, that bar represents all 475 of the people who responded Male to the question represented by the Gender variable, “No” to mental_health_interview, obs_consequence, and self_employed, and “Yes” to tech_company."
},
{
"code": null,
"e": 5777,
"s": 5242,
"text": "Example 2: However, the second set from the right represents a single man (Gender_Male) who had not heard of or observed negative consequences for coworkers with mental health conditions in their workplace (obs_consequence) but was self-employed at a tech company and would mention mental health in an interview. We know that the worker was self-employed and would have mentioned mental health in an interview, based on the fact that certain dots were not selected in the visualization and our knowledge of the other possible options."
},
{
"code": null,
"e": 5969,
"s": 5777,
"text": "In this visualization, it’s very important to think about the information that does not appear in the visualization, as in the second example. In some cases, that’s the most interesting part."
},
{
"code": null,
"e": 6027,
"s": 5969,
"text": "Let’s look at the first column from the left (Example 1)."
},
{
"code": null,
"e": 6627,
"s": 6027,
"text": "I know that I have about 1200 data points, 988 of whom identify as male.The fact that 475 men said that they would not bring up a mental health issue with a potential employer in an interview mental_health_interview_No, were currently working for a tech company tech_company_Yes, had not heard of or observed negative consequences for coworkers with mental health conditions in their workplace obs_consequence_No, and were not self-employed self_employed_No is significant because it reveals that nearly half of men (48%) and over a third (33%) of all survey-takers responded in this exact same way."
},
{
"code": null,
"e": 6894,
"s": 6627,
"text": "If you add in the 132 people who were not men who also responded the same way to those four questions, as we can see in the second column from the left, then you realize that nearly HALF of the entire dataset answered those four questions exactly the same way (48%)."
},
{
"code": null,
"e": 6909,
"s": 6894,
"text": "Interpretation"
},
{
"code": null,
"e": 7076,
"s": 6909,
"text": "These results suggest to me that people, perhaps especially men, don’t talk openly about mental health in their workplace. This is an interesting preliminary finding."
},
{
"code": null,
"e": 7099,
"s": 7076,
"text": "Potential Improvements"
},
{
"code": null,
"e": 7502,
"s": 7099,
"text": "If I want to improve my analysis, I could turn ordinal variables (variables with a sense of order, like a scale from 1–5, or “none, some, a lot”) into binary variables that preserve some sense of hierarchy by binning them (separating related values into two composite categories). This would allow them to factor more strongly into UpSetR’s analysis because UpSetR would have fewer options to consider."
},
{
"code": null,
"e": 7675,
"s": 7502,
"text": "I adore the UpSetR package and think it’s a beautiful way to do exploratory data analysis. The documentation for it is decent, and there’s a Python version of it available."
}
] |
PyTorch [Basics] — Sampling Samplers | by Akshaj Verma | Towards Data Science
|
This notebook takes you through an implementation of random_split, SubsetRandomSampler, and WeightedRandomSampler on Natural Images data using PyTorch.
import numpy as npimport pandas as pdimport seaborn as snsfrom tqdm.notebook import tqdmimport matplotlib.pyplot as pltimport torchimport torchvisionimport torch.nn as nnimport torch.optim as optimimport torch.nn.functional as Ffrom torchvision import transforms, utils, datasetsfrom torch.utils.data import Dataset, DataLoader, random_split, SubsetRandomSampler, WeightedRandomSampler
Set the random seed.
np.random.seed(0)torch.manual_seed(0)
Set Seaborn style.
%matplotlib inlinesns.set_style('darkgrid')
Set the root directory for the dataset.
root_dir = "../../data/computer_vision/image_classification/natural-images/"print("The data lies here =>", root_dir)###################### OUTPUT ######################We're using => cpuThe data lies here => ../../data/computer_vision/image_classification/natural-images/
Crop the images to be of size (224, 224) and convert them to tensors.
image_transforms = { "train": transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor() ])}
Using ImageFolder, we will create our dataset. We'll only use the train folder for this blogpost.
natural_img_dataset = datasets.ImageFolder( root = root_dir, transform = image_transforms["train"] )natural_img_dataset
The .class_to_idx method returns the class-mapping label in the dataset.
natural_img_dataset.class_to_idx###################### OUTPUT ######################{'airplane': 0, 'car': 1, 'cat': 2, 'dog': 3, 'flower': 4, 'fruit': 5, 'motorbike': 6, 'person': 7}
We will create a dictionary called idx2class which is the reverse of class_to_idx method in PyTorch.
idx2class = {v: k for k, v in natural_img_dataset.class_to_idx.items()}idx2class###################### OUTPUT ######################{0: 'airplane', 1: 'car', 2: 'cat', 3: 'dog', 4: 'flower', 5: 'fruit', 6: 'motorbike', 7: 'person'}
To observe the distribution of different classes in a dataset object, we create a function called get_class_distribution(). This function takes a dataset as an input argument and returns a dictionary which contains the count of all classes in the dataset object.
To do this, we first initialize our count_dict where all the class counts are 0.Then we iterate over our dataset object to extract the class labels. The dataset object contains elements in the form of a tuple (x,y). So, we need to extract the item at position 1 from the tuple.Then we use the idx2class to get the class name from the class id.Finally, we update the count in our count_dict by 1 for the relevant class-key.
To do this, we first initialize our count_dict where all the class counts are 0.
Then we iterate over our dataset object to extract the class labels. The dataset object contains elements in the form of a tuple (x,y). So, we need to extract the item at position 1 from the tuple.
Then we use the idx2class to get the class name from the class id.
Finally, we update the count in our count_dict by 1 for the relevant class-key.
def get_class_distribution(dataset_obj): count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()} for element in dataset_obj: y_lbl = element[1] y_lbl = idx2class[y_lbl] count_dict[y_lbl] += 1 return count_dictprint("Distribution of classes: \n", get_class_distribution(natural_img_dataset))###################### OUTPUT ######################Distribution of classes: {'airplane': 727, 'car': 968, 'cat': 885, 'dog': 702, 'flower': 843, 'fruit': 1000, 'motorbike': 788, 'person': 986}
To plot our dictionary, we use the Seaborn library. We first convert our dictionary to a dataframe and then melt it. Finally, we use the function sns.barplot() to construct our plot.
plt.figure(figsize=(15,8))sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(natural_img_dataset)]).melt(), x = "variable", y="value", hue="variable").set_title('Natural Images Class Distribution')
From the above graph, we observe that the classes are imbalanced.
random_split(dataset, lengths) works directly on the dataset. The function expects 2 input arguments. The first argument is the dataset. The second is a tuple of lengths. If we want to split our dataset into 2 parts, we will provide a tuple with 2 numbers. These numbers are the sizes of the corresponding datasets after the split.
Our dataset has 6899 images. If we want to split this into 2 parts (train/test, train/val) of size (6000, 899), we will call random split as random_split(6000, 899).
Let’s split our dataset into train and val sets.
train_dataset, val_dataset = random_split(natural_img_dataset, (6000, 899))
Pass data to the dataloader.
train_loader = DataLoader(dataset=train_dataset, shuffle=True, batch_size=1)val_loader = DataLoader(dataset=val_dataset, shuffle=False, batch_size=1)print("Length of the train_loader:", len(train_loader))print("Length of the val_loader:", len(val_loader))###################### OUTPUT ######################Length of the train_loader: 6000Length of the val_loader: 899
Note that we have used a batch_size = 1. If we increase the batch_size, the number of images would be the same but the length of train/val loaders would change.
Let’s take a look at the distribution of classes in the train and val loaders.
def get_class_distribution_loaders(dataloader_obj, dataset_obj): count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()} for _,j in dataloader_obj: y_idx = j.item() y_lbl = idx2class[y_idx] count_dict[str(y_lbl)] += 1 return count_dict
Let’s construct the plots.
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18,7))sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution_loaders(train_loader, natural_img_dataset)]).melt(), x = "variable", y="value", hue="variable", ax=axes[0]).set_title('Train Set')sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution_loaders(val_loader, natural_img_dataset)]).melt(), x = "variable", y="value", hue="variable", ax=axes[1]).set_title('Val Set')
SubsetRandomSampler(indices) takes as input the indices of data.
We first create our samplers and then we’ll pass it to our dataloaders.
Create a list of indices.Shuffle the indices.Split the indices based on train-val percentage.Create SubsetRandomSampler.
Create a list of indices.
Shuffle the indices.
Split the indices based on train-val percentage.
Create SubsetRandomSampler.
Create a list of indices from 0 to length of dataset.
dataset_size = len(natural_img_dataset)dataset_indices = list(range(dataset_size))
Shuffle the list of indices using np.shuffle.
np.random.shuffle(dataset_indices)
Create the split index. We choose the split index to be 20% (0.2) of the dataset size.
val_split_index = int(np.floor(0.2 * dataset_size))
Slice the lists to obtain 2 lists of indices, one for train and other for test.
0-----------val_split_index------------------------------n.
Train => val_split_index to n
Val => 0 to val_split_index
train_idx, val_idx = dataset_indices[val_split_index:], dataset_indices[:val_split_index]
Finally, create samplers.
train_sampler = SubsetRandomSampler(train_idx)val_sampler = SubsetRandomSampler(val_idx)
Now, we will pass the samplers to our dataloader. Note that shuffle=True cannot be used when you're using the SubsetRandomSampler.
train_loader = DataLoader(dataset=natural_img_dataset, shuffle=False, batch_size=1, sampler=train_sampler)val_loader = DataLoader(dataset=natural_img_dataset, shuffle=False, batch_size=1, sampler=val_sampler)
Now, we’ll plot the class distribution in our dataloaders.
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18,7))sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution_loaders(train_loader, natural_img_dataset)]).melt(), x = "variable", y="value", hue="variable", ax=axes[0]).set_title('Train Set')sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution_loaders(val_loader, natural_img_dataset)]).melt(), x = "variable", y="value", hue="variable", ax=axes[1]).set_title('Val Set')
As we can observe, the number of samples per class in the validation set is proportional to the number in train set.
WeightedRandomSampler is used, unlike random_split and SubsetRandomSampler, to ensure that each batch sees a proportional number of all classes.
Get all the target classes.Get the class weights. Class weights are the reciprocal of the number of items per class.Obtain corresponding weight for each target sample.
Get all the target classes.
Get the class weights. Class weights are the reciprocal of the number of items per class.
Obtain corresponding weight for each target sample.
Obtain the list of target classes and shuffle.
target_list = torch.tensor(natural_img_dataset.targets)
Get the class counts and calculate the weights/class by taking its reciprocal.
class_count = [i for i in get_class_distribution(natural_img_dataset).values()]class_weights = 1./torch.tensor(class_count, dtype=torch.float) class_weights###################### OUTPUT ######################tensor([0.0014, 0.0010, 0.0011, 0.0014, 0.0012, 0.0010, 0.0013, 0.0010])
Assign the weight of each class to all the samples.
class_weights_all = class_weights[target_list]class_weights_all###################### OUTPUT ######################tensor([0.0010, 0.0012, 0.0014, ..., 0.0010, 0.0014, 0.0010])
Pass the weight and number of samples to the WeightedRandomSampler.
weighted_sampler = WeightedRandomSampler( weights=class_weights_all, num_samples=len(class_weights_all), replacement=True)
Pass the sampler to the dataloader.
train_loader = DataLoader(dataset=natural_img_dataset, shuffle=False, batch_size=8, sampler=weighted_sampler)
And this is it. You can now use your dataloader to train your neural network model!
Thank you for reading. Suggestions and constructive criticism are welcome. :)
This blog post is a part of the series — “How to train you Neural Net”. You can find the series here.
You can find me on LinkedIn and Twitter. If you liked this, check out my other blogposts.
|
[
{
"code": null,
"e": 324,
"s": 172,
"text": "This notebook takes you through an implementation of random_split, SubsetRandomSampler, and WeightedRandomSampler on Natural Images data using PyTorch."
},
{
"code": null,
"e": 710,
"s": 324,
"text": "import numpy as npimport pandas as pdimport seaborn as snsfrom tqdm.notebook import tqdmimport matplotlib.pyplot as pltimport torchimport torchvisionimport torch.nn as nnimport torch.optim as optimimport torch.nn.functional as Ffrom torchvision import transforms, utils, datasetsfrom torch.utils.data import Dataset, DataLoader, random_split, SubsetRandomSampler, WeightedRandomSampler"
},
{
"code": null,
"e": 731,
"s": 710,
"text": "Set the random seed."
},
{
"code": null,
"e": 769,
"s": 731,
"text": "np.random.seed(0)torch.manual_seed(0)"
},
{
"code": null,
"e": 788,
"s": 769,
"text": "Set Seaborn style."
},
{
"code": null,
"e": 832,
"s": 788,
"text": "%matplotlib inlinesns.set_style('darkgrid')"
},
{
"code": null,
"e": 872,
"s": 832,
"text": "Set the root directory for the dataset."
},
{
"code": null,
"e": 1144,
"s": 872,
"text": "root_dir = \"../../data/computer_vision/image_classification/natural-images/\"print(\"The data lies here =>\", root_dir)###################### OUTPUT ######################We're using => cpuThe data lies here => ../../data/computer_vision/image_classification/natural-images/"
},
{
"code": null,
"e": 1214,
"s": 1144,
"text": "Crop the images to be of size (224, 224) and convert them to tensors."
},
{
"code": null,
"e": 1342,
"s": 1214,
"text": "image_transforms = { \"train\": transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor() ])}"
},
{
"code": null,
"e": 1440,
"s": 1342,
"text": "Using ImageFolder, we will create our dataset. We'll only use the train folder for this blogpost."
},
{
"code": null,
"e": 1640,
"s": 1440,
"text": "natural_img_dataset = datasets.ImageFolder( root = root_dir, transform = image_transforms[\"train\"] )natural_img_dataset"
},
{
"code": null,
"e": 1713,
"s": 1640,
"text": "The .class_to_idx method returns the class-mapping label in the dataset."
},
{
"code": null,
"e": 1897,
"s": 1713,
"text": "natural_img_dataset.class_to_idx###################### OUTPUT ######################{'airplane': 0, 'car': 1, 'cat': 2, 'dog': 3, 'flower': 4, 'fruit': 5, 'motorbike': 6, 'person': 7}"
},
{
"code": null,
"e": 1998,
"s": 1897,
"text": "We will create a dictionary called idx2class which is the reverse of class_to_idx method in PyTorch."
},
{
"code": null,
"e": 2230,
"s": 1998,
"text": "idx2class = {v: k for k, v in natural_img_dataset.class_to_idx.items()}idx2class###################### OUTPUT ######################{0: 'airplane', 1: 'car', 2: 'cat', 3: 'dog', 4: 'flower', 5: 'fruit', 6: 'motorbike', 7: 'person'}"
},
{
"code": null,
"e": 2493,
"s": 2230,
"text": "To observe the distribution of different classes in a dataset object, we create a function called get_class_distribution(). This function takes a dataset as an input argument and returns a dictionary which contains the count of all classes in the dataset object."
},
{
"code": null,
"e": 2916,
"s": 2493,
"text": "To do this, we first initialize our count_dict where all the class counts are 0.Then we iterate over our dataset object to extract the class labels. The dataset object contains elements in the form of a tuple (x,y). So, we need to extract the item at position 1 from the tuple.Then we use the idx2class to get the class name from the class id.Finally, we update the count in our count_dict by 1 for the relevant class-key."
},
{
"code": null,
"e": 2997,
"s": 2916,
"text": "To do this, we first initialize our count_dict where all the class counts are 0."
},
{
"code": null,
"e": 3195,
"s": 2997,
"text": "Then we iterate over our dataset object to extract the class labels. The dataset object contains elements in the form of a tuple (x,y). So, we need to extract the item at position 1 from the tuple."
},
{
"code": null,
"e": 3262,
"s": 3195,
"text": "Then we use the idx2class to get the class name from the class id."
},
{
"code": null,
"e": 3342,
"s": 3262,
"text": "Finally, we update the count in our count_dict by 1 for the relevant class-key."
},
{
"code": null,
"e": 3880,
"s": 3342,
"text": "def get_class_distribution(dataset_obj): count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()} for element in dataset_obj: y_lbl = element[1] y_lbl = idx2class[y_lbl] count_dict[y_lbl] += 1 return count_dictprint(\"Distribution of classes: \\n\", get_class_distribution(natural_img_dataset))###################### OUTPUT ######################Distribution of classes: {'airplane': 727, 'car': 968, 'cat': 885, 'dog': 702, 'flower': 843, 'fruit': 1000, 'motorbike': 788, 'person': 986}"
},
{
"code": null,
"e": 4063,
"s": 3880,
"text": "To plot our dictionary, we use the Seaborn library. We first convert our dictionary to a dataframe and then melt it. Finally, we use the function sns.barplot() to construct our plot."
},
{
"code": null,
"e": 4276,
"s": 4063,
"text": "plt.figure(figsize=(15,8))sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(natural_img_dataset)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\").set_title('Natural Images Class Distribution')"
},
{
"code": null,
"e": 4342,
"s": 4276,
"text": "From the above graph, we observe that the classes are imbalanced."
},
{
"code": null,
"e": 4674,
"s": 4342,
"text": "random_split(dataset, lengths) works directly on the dataset. The function expects 2 input arguments. The first argument is the dataset. The second is a tuple of lengths. If we want to split our dataset into 2 parts, we will provide a tuple with 2 numbers. These numbers are the sizes of the corresponding datasets after the split."
},
{
"code": null,
"e": 4840,
"s": 4674,
"text": "Our dataset has 6899 images. If we want to split this into 2 parts (train/test, train/val) of size (6000, 899), we will call random split as random_split(6000, 899)."
},
{
"code": null,
"e": 4889,
"s": 4840,
"text": "Let’s split our dataset into train and val sets."
},
{
"code": null,
"e": 4965,
"s": 4889,
"text": "train_dataset, val_dataset = random_split(natural_img_dataset, (6000, 899))"
},
{
"code": null,
"e": 4994,
"s": 4965,
"text": "Pass data to the dataloader."
},
{
"code": null,
"e": 5363,
"s": 4994,
"text": "train_loader = DataLoader(dataset=train_dataset, shuffle=True, batch_size=1)val_loader = DataLoader(dataset=val_dataset, shuffle=False, batch_size=1)print(\"Length of the train_loader:\", len(train_loader))print(\"Length of the val_loader:\", len(val_loader))###################### OUTPUT ######################Length of the train_loader: 6000Length of the val_loader: 899"
},
{
"code": null,
"e": 5524,
"s": 5363,
"text": "Note that we have used a batch_size = 1. If we increase the batch_size, the number of images would be the same but the length of train/val loaders would change."
},
{
"code": null,
"e": 5603,
"s": 5524,
"text": "Let’s take a look at the distribution of classes in the train and val loaders."
},
{
"code": null,
"e": 5892,
"s": 5603,
"text": "def get_class_distribution_loaders(dataloader_obj, dataset_obj): count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()} for _,j in dataloader_obj: y_idx = j.item() y_lbl = idx2class[y_idx] count_dict[str(y_lbl)] += 1 return count_dict"
},
{
"code": null,
"e": 5919,
"s": 5892,
"text": "Let’s construct the plots."
},
{
"code": null,
"e": 6368,
"s": 5919,
"text": "fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18,7))sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution_loaders(train_loader, natural_img_dataset)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[0]).set_title('Train Set')sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution_loaders(val_loader, natural_img_dataset)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[1]).set_title('Val Set')"
},
{
"code": null,
"e": 6433,
"s": 6368,
"text": "SubsetRandomSampler(indices) takes as input the indices of data."
},
{
"code": null,
"e": 6505,
"s": 6433,
"text": "We first create our samplers and then we’ll pass it to our dataloaders."
},
{
"code": null,
"e": 6626,
"s": 6505,
"text": "Create a list of indices.Shuffle the indices.Split the indices based on train-val percentage.Create SubsetRandomSampler."
},
{
"code": null,
"e": 6652,
"s": 6626,
"text": "Create a list of indices."
},
{
"code": null,
"e": 6673,
"s": 6652,
"text": "Shuffle the indices."
},
{
"code": null,
"e": 6722,
"s": 6673,
"text": "Split the indices based on train-val percentage."
},
{
"code": null,
"e": 6750,
"s": 6722,
"text": "Create SubsetRandomSampler."
},
{
"code": null,
"e": 6804,
"s": 6750,
"text": "Create a list of indices from 0 to length of dataset."
},
{
"code": null,
"e": 6887,
"s": 6804,
"text": "dataset_size = len(natural_img_dataset)dataset_indices = list(range(dataset_size))"
},
{
"code": null,
"e": 6933,
"s": 6887,
"text": "Shuffle the list of indices using np.shuffle."
},
{
"code": null,
"e": 6968,
"s": 6933,
"text": "np.random.shuffle(dataset_indices)"
},
{
"code": null,
"e": 7055,
"s": 6968,
"text": "Create the split index. We choose the split index to be 20% (0.2) of the dataset size."
},
{
"code": null,
"e": 7107,
"s": 7055,
"text": "val_split_index = int(np.floor(0.2 * dataset_size))"
},
{
"code": null,
"e": 7187,
"s": 7107,
"text": "Slice the lists to obtain 2 lists of indices, one for train and other for test."
},
{
"code": null,
"e": 7247,
"s": 7187,
"text": "0-----------val_split_index------------------------------n."
},
{
"code": null,
"e": 7277,
"s": 7247,
"text": "Train => val_split_index to n"
},
{
"code": null,
"e": 7305,
"s": 7277,
"text": "Val => 0 to val_split_index"
},
{
"code": null,
"e": 7395,
"s": 7305,
"text": "train_idx, val_idx = dataset_indices[val_split_index:], dataset_indices[:val_split_index]"
},
{
"code": null,
"e": 7421,
"s": 7395,
"text": "Finally, create samplers."
},
{
"code": null,
"e": 7510,
"s": 7421,
"text": "train_sampler = SubsetRandomSampler(train_idx)val_sampler = SubsetRandomSampler(val_idx)"
},
{
"code": null,
"e": 7641,
"s": 7510,
"text": "Now, we will pass the samplers to our dataloader. Note that shuffle=True cannot be used when you're using the SubsetRandomSampler."
},
{
"code": null,
"e": 7850,
"s": 7641,
"text": "train_loader = DataLoader(dataset=natural_img_dataset, shuffle=False, batch_size=1, sampler=train_sampler)val_loader = DataLoader(dataset=natural_img_dataset, shuffle=False, batch_size=1, sampler=val_sampler)"
},
{
"code": null,
"e": 7909,
"s": 7850,
"text": "Now, we’ll plot the class distribution in our dataloaders."
},
{
"code": null,
"e": 8358,
"s": 7909,
"text": "fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18,7))sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution_loaders(train_loader, natural_img_dataset)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[0]).set_title('Train Set')sns.barplot(data = pd.DataFrame.from_dict([get_class_distribution_loaders(val_loader, natural_img_dataset)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[1]).set_title('Val Set')"
},
{
"code": null,
"e": 8475,
"s": 8358,
"text": "As we can observe, the number of samples per class in the validation set is proportional to the number in train set."
},
{
"code": null,
"e": 8620,
"s": 8475,
"text": "WeightedRandomSampler is used, unlike random_split and SubsetRandomSampler, to ensure that each batch sees a proportional number of all classes."
},
{
"code": null,
"e": 8788,
"s": 8620,
"text": "Get all the target classes.Get the class weights. Class weights are the reciprocal of the number of items per class.Obtain corresponding weight for each target sample."
},
{
"code": null,
"e": 8816,
"s": 8788,
"text": "Get all the target classes."
},
{
"code": null,
"e": 8906,
"s": 8816,
"text": "Get the class weights. Class weights are the reciprocal of the number of items per class."
},
{
"code": null,
"e": 8958,
"s": 8906,
"text": "Obtain corresponding weight for each target sample."
},
{
"code": null,
"e": 9005,
"s": 8958,
"text": "Obtain the list of target classes and shuffle."
},
{
"code": null,
"e": 9061,
"s": 9005,
"text": "target_list = torch.tensor(natural_img_dataset.targets)"
},
{
"code": null,
"e": 9140,
"s": 9061,
"text": "Get the class counts and calculate the weights/class by taking its reciprocal."
},
{
"code": null,
"e": 9421,
"s": 9140,
"text": "class_count = [i for i in get_class_distribution(natural_img_dataset).values()]class_weights = 1./torch.tensor(class_count, dtype=torch.float) class_weights###################### OUTPUT ######################tensor([0.0014, 0.0010, 0.0011, 0.0014, 0.0012, 0.0010, 0.0013, 0.0010])"
},
{
"code": null,
"e": 9473,
"s": 9421,
"text": "Assign the weight of each class to all the samples."
},
{
"code": null,
"e": 9651,
"s": 9473,
"text": "class_weights_all = class_weights[target_list]class_weights_all###################### OUTPUT ######################tensor([0.0010, 0.0012, 0.0014, ..., 0.0010, 0.0014, 0.0010])"
},
{
"code": null,
"e": 9719,
"s": 9651,
"text": "Pass the weight and number of samples to the WeightedRandomSampler."
},
{
"code": null,
"e": 9851,
"s": 9719,
"text": "weighted_sampler = WeightedRandomSampler( weights=class_weights_all, num_samples=len(class_weights_all), replacement=True)"
},
{
"code": null,
"e": 9887,
"s": 9851,
"text": "Pass the sampler to the dataloader."
},
{
"code": null,
"e": 9997,
"s": 9887,
"text": "train_loader = DataLoader(dataset=natural_img_dataset, shuffle=False, batch_size=8, sampler=weighted_sampler)"
},
{
"code": null,
"e": 10081,
"s": 9997,
"text": "And this is it. You can now use your dataloader to train your neural network model!"
},
{
"code": null,
"e": 10159,
"s": 10081,
"text": "Thank you for reading. Suggestions and constructive criticism are welcome. :)"
},
{
"code": null,
"e": 10261,
"s": 10159,
"text": "This blog post is a part of the series — “How to train you Neural Net”. You can find the series here."
}
] |
Bootstrap Resampling. No, not Twitter Bootstrap — this... | by James Andrew Godwin | Towards Data Science
|
No, not Twitter Bootstrap — this bootstrapping is a way of sampling data, and it is one of the most important to consider what underlies the variation of numbers, the variation of distributions, what underlies distributions. To that end, bootstrapping works really, really well. For Data Scientists, Machine Learning Engineers, and statisticians alike it is vital to understand resampling methods.
But why use resampling? We use resampling because we only have a limited amount of data — the limits of time, and economics, to say the least. What then is resampling? Resampling is when you take a sample, and then you take a sample of the sample. Why would you do that? Well, it allows you to see how much variation there would have been, it allows you to get a different understanding of the sample that you took. Say, for example, you wanted 1000 people to answer a survey, but you only have 100. By cleverly subsampling the samples we can get a new distribution, which we will know a little bit about the uncertainty of the sample; which we further presume is related to the uncertainty of the underlying population.
We can compute statistics from multiple sub samples of data sets, such as the mean. We take a bunch of these items, we sum them up and divide them by the count by the number of items. The trick to bootstrap resampling is sampling with replacement.
In Python, typically there will be a Boolean argument to your sampling parameter in your sampling code to your sampling function. This Boolean flag will be replace = true or replace = false. If you have 100 items, randomly sample (e.g., Bernoulli sample) the sample — record it, and replace that value back into the sample pool. Then rinse and repeat 99 more times. This subsample population is very likely to be different. They will have different proportions of the original 100 values. For the most part, the values are going to be pretty evenly distributed, but not perfectly. Then repeat this process a total of 10 times to generate 1000 samples. Note that occasionally some weird things can occur — e.g., if your data has one unique value of X — it is possible, but not likely due to sampling with replacement, that you can randomly subsample 100 values that include 5 X values, despite the sampled population only having one.
For each of these samples, we can calculate the mean. And then we can look at the distribution of these means. Or we can look at the average of these means. The average of these means again should be pretty close to the population average, and should be pretty close to that larger sample average. You can do the same thing for other metrics, like standard deviations. Bootstrapping is a very powerful technique that allows you to get to another way of getting the uncertainties of your measurements. Because when you take those, when you get the means this variation of the means of all the sub samples will tell us quite a bit about the uncertainty that we would have that your sample has in respect to the true underlying population.
Bootstrap and resampling are widely applicable statistical methods which relax many of the assumptions of classical statistics. Resampling methods implicitly draw on the Central Limit Theorem, as explained in my previous article. Specifically bootstrap (and other resampling methods):
Allows computation of statistics from limited data.
Allows us to compute statistics from multiple subsamples of the dataset.
Allows us to make minimal distribution assumptions.
Commonly used resampling methods include:
Randomization or permutation methods (e.g., Fisher’s exact test). Randomization and permutation methods were pioneered by Fisher as early as 1911. Fisher fully developed the theory in his 1935 book. Scalability of these methods remain limited, even with modern computers.
Cross validation: resample into folds without replacement. Originally proposed by Kurtz in 1948, cross-validation today is widely used in the testing of machine learning models.
Jackknife: leave one out resampling. Maurice Quenouille originally proposed this method in 1949. The jackknife was fully developed by John W. Tukey, who gave the method its name, in 1958: that the method was a simple tool useful for many purposes like a pocket knife.
Bootstrap: resample with equivalent size and replacement. The bootstrap method was first suggested by Efron and Hinkley in 1978 and further developed by Efron in 1979.
We compute the bootstrap mean as:
To demonstrate the power of bootstrap I will analyze the means of the heights of different populations from Galton’s height dataset in a Jupyter notebook; famous for giving us the phrase “regression to the mean” w/r to children’s heights. The following is an example of a parametric bootstrap estimate — parametric because our model has a parameter, the mean, we are trying to estimate.
I will demonstrate with an example:
import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltimport seaborn as sns%matplotlib inline
Importing the basic libraries
# i imported the dataset from here, and called file_namegalton-families = pd.read_csv(file_name, index_col=0)galton-families.head()
Check that the data is well-imported.
Now I will subset the dataframe by gender to get the number of men and women in the dataset. This is going to create two data sets, one called male one called female. Male is actually sons and female is actually daughters.
male = galton-families[galton-families.gender == ‘male’]female = galton-families[galton-families.gender == ‘female’]len(male), len(female)(481, 453)
The set looks reasonably balanced with 481 males, 453 females in this dataset. The following code shows the min and max values in these distributions:
print(families.childHeight.min())families.childHeight.max()56.0Out[11]: 79.0
They range from 56 inches to 79 inches. The next thing to do is to plot these two histograms:
def plot_hist(x, p=5): # Plot the distribution and mark the mean plt.hist(x, alpha=.5) plt.axvline(x.mean()) # 95% confidence interval plt.axvline(np.percentile(x, p/2.), color=’red’, linewidth=3) plt.axvline(np.percentile(x, 100-p/2.), color=’red’, linewidth=3) def plot_dists(a, b, nbins, a_label=’pop_A’, b_label=’pop_B’, p=5): # Create a single sequence of bins to be shared across both # distribution plots for visualization consistency. combined = pd.concat([a, b]) breaks = np.linspace( combined.min(), combined.max(), num=nbins+1) plt.subplot(2, 1, 1) plot_hist(a) plt.title(a_label) plt.subplot(2, 1, 2) plot_hist(b) plt.title(b_label) plt.tight_layout() plot_dists(male.childHeight, female.childHeight, 20, a_label=’sons’, b_label=’daughters’)plt.show()
The important thing to note here is that there is a significant overlap between sons and daughters. You can see that some of the daughters are actually taller than the mean of the sons. Overall, we can see that the daughters are smaller than the sons, but is it significant?
My last post on the CLT demonstrated very clear ways of how to distinguish between these two distributions. It might look like these are two different distributions. However, we might actually say the distribution of the sons is not that different from the distributions of the daughters, because the 95% confidence level, which is indicated with these red vertical bars, sort of overlaps with the mean.
Bootstrap to the rescue. We are going to resample from our sample. Pandas has built-in support for generating bootstrap samples from a given dataframe. I will use the sample() method of our two dataframes to draw a single bootstrap sample like so:
female.sample(frac=1, replace=True).head()
NB: With the replace equals true argument, you might get the same row multiple times, or some rows you are not going to sample at all.
The above sample of all the daughters sampled from the Galton dataset has the following mean:
female.sample(frac=1, replace=True).father.mean()69.0664459161148
This bootstrapped sample of the female dataframe has a mean height of 69.1 inches for 453 daughters.
Now we will take many (n_replicas) bootstrap samples and plot the distribution of sample means, as well as the mean of the sample, means. In the following code, we bootstrap 1000 subsamples each of the original size of the dataframe (481 and 453).
n_replicas = 1000female_bootstrap_means = pd.Series([ female.sample(frac=1, replace=True).childHeight.mean() for i in range(n_replicas)])male_bootstrap_means = pd.Series([ male.sample(frac=1, replace=True).childHeight.mean() for i in range(n_replicas)])plot_dists(male_bootstrap_means, female_bootstrap_means, nbins=80, a_label=’sons’, b_label=’daughters’)plt.show()
The distribution of the bootstrap means does not overlap at all! This proves that the difference is significant.
In the cell below, I will show how to generate bootstrap samples from the full male + female dataset and then difference in the means of male and female childHeight for each sample, generating a distribution of sample mean diffs.
diffs = []for i in range(n_replicas): sample = families.sample(frac=1.0, replace=True) male_sample_mean = sample[sample.gender == ‘male’].childHeight.mean() female_sample_mean = sample[sample.gender == ‘female’].childHeight.mean() diffs.append(male_sample_mean — female_sample_mean)diffs = pd.Series(diffs)plot_hist(diffs)
The distribution of the difference in means is far from zero. As like before, we can infer that the means of the two populations are significantly different — which for the purposes of this dataset is to say that sons and daughters do have different mean heights. Said differently: the confidence interval does not straddle zero, and because it does not straddle zero, we are confident that the difference is significant. The blue line indicates the mean difference between sons and daughters from the bootstrap sample of around 5.1 inches, of which we are 95% confident that the true population mean difference is between 4.8 inches and around 5.5 inches. This is the answer — that on average, sons are 5.5 inches taller than daughters.
However, we must verify that the distribution of the difference in means normal, as implied by the CLT. If the data is not normally distributed then we cannot trust the 95% CI:
import statsmodels.api as smfig = sm.qqplot(diffs, line=’s’)plt.title(‘Quantiles of standard Normal vs. bookstrapped mean’)plt.show()
The points on the Q-Q Normal plot are nearly on a straight line. Apparently, the bootstrap distribution of the difference in means does conform to the CLT, which allows us to trust the statistics we derived from bootstrap resampling the original dataset.
The results of this analysis have demonstrated how useful a tool resampling is for a Data Scientist or Machine Learning Engineer. Bootstrap is not the only resampling method, there are several, but IMO it is the best for production models because it makes minimal assumptions about the parent distribution and is well implemented into many languages and packages. Data is useless if it is not properly treated and analyzed with the correct context. As Mark Twain famously said, “There are lies, damned lies, and statistics.”
Continue with me as I build on these concepts in Bayes statistics and using bootstrap with regression models.
Find me on Linkedin
Physicist cum Data Scientist- Available for new opportunity | SaaS | Sports | Start-ups | Scale-ups
|
[
{
"code": null,
"e": 569,
"s": 171,
"text": "No, not Twitter Bootstrap — this bootstrapping is a way of sampling data, and it is one of the most important to consider what underlies the variation of numbers, the variation of distributions, what underlies distributions. To that end, bootstrapping works really, really well. For Data Scientists, Machine Learning Engineers, and statisticians alike it is vital to understand resampling methods."
},
{
"code": null,
"e": 1290,
"s": 569,
"text": "But why use resampling? We use resampling because we only have a limited amount of data — the limits of time, and economics, to say the least. What then is resampling? Resampling is when you take a sample, and then you take a sample of the sample. Why would you do that? Well, it allows you to see how much variation there would have been, it allows you to get a different understanding of the sample that you took. Say, for example, you wanted 1000 people to answer a survey, but you only have 100. By cleverly subsampling the samples we can get a new distribution, which we will know a little bit about the uncertainty of the sample; which we further presume is related to the uncertainty of the underlying population."
},
{
"code": null,
"e": 1538,
"s": 1290,
"text": "We can compute statistics from multiple sub samples of data sets, such as the mean. We take a bunch of these items, we sum them up and divide them by the count by the number of items. The trick to bootstrap resampling is sampling with replacement."
},
{
"code": null,
"e": 2471,
"s": 1538,
"text": "In Python, typically there will be a Boolean argument to your sampling parameter in your sampling code to your sampling function. This Boolean flag will be replace = true or replace = false. If you have 100 items, randomly sample (e.g., Bernoulli sample) the sample — record it, and replace that value back into the sample pool. Then rinse and repeat 99 more times. This subsample population is very likely to be different. They will have different proportions of the original 100 values. For the most part, the values are going to be pretty evenly distributed, but not perfectly. Then repeat this process a total of 10 times to generate 1000 samples. Note that occasionally some weird things can occur — e.g., if your data has one unique value of X — it is possible, but not likely due to sampling with replacement, that you can randomly subsample 100 values that include 5 X values, despite the sampled population only having one."
},
{
"code": null,
"e": 3208,
"s": 2471,
"text": "For each of these samples, we can calculate the mean. And then we can look at the distribution of these means. Or we can look at the average of these means. The average of these means again should be pretty close to the population average, and should be pretty close to that larger sample average. You can do the same thing for other metrics, like standard deviations. Bootstrapping is a very powerful technique that allows you to get to another way of getting the uncertainties of your measurements. Because when you take those, when you get the means this variation of the means of all the sub samples will tell us quite a bit about the uncertainty that we would have that your sample has in respect to the true underlying population."
},
{
"code": null,
"e": 3493,
"s": 3208,
"text": "Bootstrap and resampling are widely applicable statistical methods which relax many of the assumptions of classical statistics. Resampling methods implicitly draw on the Central Limit Theorem, as explained in my previous article. Specifically bootstrap (and other resampling methods):"
},
{
"code": null,
"e": 3545,
"s": 3493,
"text": "Allows computation of statistics from limited data."
},
{
"code": null,
"e": 3618,
"s": 3545,
"text": "Allows us to compute statistics from multiple subsamples of the dataset."
},
{
"code": null,
"e": 3670,
"s": 3618,
"text": "Allows us to make minimal distribution assumptions."
},
{
"code": null,
"e": 3712,
"s": 3670,
"text": "Commonly used resampling methods include:"
},
{
"code": null,
"e": 3984,
"s": 3712,
"text": "Randomization or permutation methods (e.g., Fisher’s exact test). Randomization and permutation methods were pioneered by Fisher as early as 1911. Fisher fully developed the theory in his 1935 book. Scalability of these methods remain limited, even with modern computers."
},
{
"code": null,
"e": 4162,
"s": 3984,
"text": "Cross validation: resample into folds without replacement. Originally proposed by Kurtz in 1948, cross-validation today is widely used in the testing of machine learning models."
},
{
"code": null,
"e": 4430,
"s": 4162,
"text": "Jackknife: leave one out resampling. Maurice Quenouille originally proposed this method in 1949. The jackknife was fully developed by John W. Tukey, who gave the method its name, in 1958: that the method was a simple tool useful for many purposes like a pocket knife."
},
{
"code": null,
"e": 4598,
"s": 4430,
"text": "Bootstrap: resample with equivalent size and replacement. The bootstrap method was first suggested by Efron and Hinkley in 1978 and further developed by Efron in 1979."
},
{
"code": null,
"e": 4632,
"s": 4598,
"text": "We compute the bootstrap mean as:"
},
{
"code": null,
"e": 5019,
"s": 4632,
"text": "To demonstrate the power of bootstrap I will analyze the means of the heights of different populations from Galton’s height dataset in a Jupyter notebook; famous for giving us the phrase “regression to the mean” w/r to children’s heights. The following is an example of a parametric bootstrap estimate — parametric because our model has a parameter, the mean, we are trying to estimate."
},
{
"code": null,
"e": 5055,
"s": 5019,
"text": "I will demonstrate with an example:"
},
{
"code": null,
"e": 5168,
"s": 5055,
"text": "import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltimport seaborn as sns%matplotlib inline"
},
{
"code": null,
"e": 5198,
"s": 5168,
"text": "Importing the basic libraries"
},
{
"code": null,
"e": 5330,
"s": 5198,
"text": "# i imported the dataset from here, and called file_namegalton-families = pd.read_csv(file_name, index_col=0)galton-families.head()"
},
{
"code": null,
"e": 5368,
"s": 5330,
"text": "Check that the data is well-imported."
},
{
"code": null,
"e": 5591,
"s": 5368,
"text": "Now I will subset the dataframe by gender to get the number of men and women in the dataset. This is going to create two data sets, one called male one called female. Male is actually sons and female is actually daughters."
},
{
"code": null,
"e": 5740,
"s": 5591,
"text": "male = galton-families[galton-families.gender == ‘male’]female = galton-families[galton-families.gender == ‘female’]len(male), len(female)(481, 453)"
},
{
"code": null,
"e": 5891,
"s": 5740,
"text": "The set looks reasonably balanced with 481 males, 453 females in this dataset. The following code shows the min and max values in these distributions:"
},
{
"code": null,
"e": 5968,
"s": 5891,
"text": "print(families.childHeight.min())families.childHeight.max()56.0Out[11]: 79.0"
},
{
"code": null,
"e": 6062,
"s": 5968,
"text": "They range from 56 inches to 79 inches. The next thing to do is to plot these two histograms:"
},
{
"code": null,
"e": 6831,
"s": 6062,
"text": "def plot_hist(x, p=5): # Plot the distribution and mark the mean plt.hist(x, alpha=.5) plt.axvline(x.mean()) # 95% confidence interval plt.axvline(np.percentile(x, p/2.), color=’red’, linewidth=3) plt.axvline(np.percentile(x, 100-p/2.), color=’red’, linewidth=3) def plot_dists(a, b, nbins, a_label=’pop_A’, b_label=’pop_B’, p=5): # Create a single sequence of bins to be shared across both # distribution plots for visualization consistency. combined = pd.concat([a, b]) breaks = np.linspace( combined.min(), combined.max(), num=nbins+1) plt.subplot(2, 1, 1) plot_hist(a) plt.title(a_label) plt.subplot(2, 1, 2) plot_hist(b) plt.title(b_label) plt.tight_layout() plot_dists(male.childHeight, female.childHeight, 20, a_label=’sons’, b_label=’daughters’)plt.show()"
},
{
"code": null,
"e": 7106,
"s": 6831,
"text": "The important thing to note here is that there is a significant overlap between sons and daughters. You can see that some of the daughters are actually taller than the mean of the sons. Overall, we can see that the daughters are smaller than the sons, but is it significant?"
},
{
"code": null,
"e": 7510,
"s": 7106,
"text": "My last post on the CLT demonstrated very clear ways of how to distinguish between these two distributions. It might look like these are two different distributions. However, we might actually say the distribution of the sons is not that different from the distributions of the daughters, because the 95% confidence level, which is indicated with these red vertical bars, sort of overlaps with the mean."
},
{
"code": null,
"e": 7758,
"s": 7510,
"text": "Bootstrap to the rescue. We are going to resample from our sample. Pandas has built-in support for generating bootstrap samples from a given dataframe. I will use the sample() method of our two dataframes to draw a single bootstrap sample like so:"
},
{
"code": null,
"e": 7801,
"s": 7758,
"text": "female.sample(frac=1, replace=True).head()"
},
{
"code": null,
"e": 7936,
"s": 7801,
"text": "NB: With the replace equals true argument, you might get the same row multiple times, or some rows you are not going to sample at all."
},
{
"code": null,
"e": 8030,
"s": 7936,
"text": "The above sample of all the daughters sampled from the Galton dataset has the following mean:"
},
{
"code": null,
"e": 8096,
"s": 8030,
"text": "female.sample(frac=1, replace=True).father.mean()69.0664459161148"
},
{
"code": null,
"e": 8197,
"s": 8096,
"text": "This bootstrapped sample of the female dataframe has a mean height of 69.1 inches for 453 daughters."
},
{
"code": null,
"e": 8445,
"s": 8197,
"text": "Now we will take many (n_replicas) bootstrap samples and plot the distribution of sample means, as well as the mean of the sample, means. In the following code, we bootstrap 1000 subsamples each of the original size of the dataframe (481 and 453)."
},
{
"code": null,
"e": 8813,
"s": 8445,
"text": "n_replicas = 1000female_bootstrap_means = pd.Series([ female.sample(frac=1, replace=True).childHeight.mean() for i in range(n_replicas)])male_bootstrap_means = pd.Series([ male.sample(frac=1, replace=True).childHeight.mean() for i in range(n_replicas)])plot_dists(male_bootstrap_means, female_bootstrap_means, nbins=80, a_label=’sons’, b_label=’daughters’)plt.show()"
},
{
"code": null,
"e": 8926,
"s": 8813,
"text": "The distribution of the bootstrap means does not overlap at all! This proves that the difference is significant."
},
{
"code": null,
"e": 9156,
"s": 8926,
"text": "In the cell below, I will show how to generate bootstrap samples from the full male + female dataset and then difference in the means of male and female childHeight for each sample, generating a distribution of sample mean diffs."
},
{
"code": null,
"e": 9479,
"s": 9156,
"text": "diffs = []for i in range(n_replicas): sample = families.sample(frac=1.0, replace=True) male_sample_mean = sample[sample.gender == ‘male’].childHeight.mean() female_sample_mean = sample[sample.gender == ‘female’].childHeight.mean() diffs.append(male_sample_mean — female_sample_mean)diffs = pd.Series(diffs)plot_hist(diffs)"
},
{
"code": null,
"e": 10217,
"s": 9479,
"text": "The distribution of the difference in means is far from zero. As like before, we can infer that the means of the two populations are significantly different — which for the purposes of this dataset is to say that sons and daughters do have different mean heights. Said differently: the confidence interval does not straddle zero, and because it does not straddle zero, we are confident that the difference is significant. The blue line indicates the mean difference between sons and daughters from the bootstrap sample of around 5.1 inches, of which we are 95% confident that the true population mean difference is between 4.8 inches and around 5.5 inches. This is the answer — that on average, sons are 5.5 inches taller than daughters."
},
{
"code": null,
"e": 10394,
"s": 10217,
"text": "However, we must verify that the distribution of the difference in means normal, as implied by the CLT. If the data is not normally distributed then we cannot trust the 95% CI:"
},
{
"code": null,
"e": 10528,
"s": 10394,
"text": "import statsmodels.api as smfig = sm.qqplot(diffs, line=’s’)plt.title(‘Quantiles of standard Normal vs. bookstrapped mean’)plt.show()"
},
{
"code": null,
"e": 10783,
"s": 10528,
"text": "The points on the Q-Q Normal plot are nearly on a straight line. Apparently, the bootstrap distribution of the difference in means does conform to the CLT, which allows us to trust the statistics we derived from bootstrap resampling the original dataset."
},
{
"code": null,
"e": 11308,
"s": 10783,
"text": "The results of this analysis have demonstrated how useful a tool resampling is for a Data Scientist or Machine Learning Engineer. Bootstrap is not the only resampling method, there are several, but IMO it is the best for production models because it makes minimal assumptions about the parent distribution and is well implemented into many languages and packages. Data is useless if it is not properly treated and analyzed with the correct context. As Mark Twain famously said, “There are lies, damned lies, and statistics.”"
},
{
"code": null,
"e": 11418,
"s": 11308,
"text": "Continue with me as I build on these concepts in Bayes statistics and using bootstrap with regression models."
},
{
"code": null,
"e": 11438,
"s": 11418,
"text": "Find me on Linkedin"
}
] |
BabylonJS - Scaling
|
Scaling basically means increasing or decreasing the size of the object at a uniform scale. Let us now consider an example where we will increase/decrease the size of the object along the x or y or z-axis.
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<title>BabylonJs - Basic Element-Creating Scene</title>
<script src = "babylon.js"></script>
<style>
canvas {width: 100%; height: 100%;}
</style>
</head>
<body>
<canvas id = "renderCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
var createScene = function() {
var scene = new BABYLON.Scene(engine);
scene.clearColor = new BABYLON.Color3(0, 1, 0);
var camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);
scene.activeCamera.attachControl(canvas);
var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 100, 100), scene);
var boxa = BABYLON.Mesh.CreateBox("BoxA", 1.0, scene);
boxa.position = new BABYLON.Vector3(0,0.5,0);
var boxb = BABYLON.Mesh.CreateBox("BoxB", 1.0, scene);
boxb.position = new BABYLON.Vector3(3,0.5,0);
boxb.scaling = new BABYLON.Vector3(2,1,2);
var boxc = BABYLON.Mesh.CreateBox("BoxC", 1.0, scene);
boxc.position = new BABYLON.Vector3(-3,0.5,0);
boxc.scaling = new BABYLON.Vector3(2,1,2);
var boxd = BABYLON.Mesh.CreateBox("BoxD", 1.0, scene);
boxd.position = new BABYLON.Vector3(0,0.5,3);
boxd.scaling = new BABYLON.Vector3(2,1,2);
var boxe = BABYLON.Mesh.CreateBox("BoxE", 1.0, scene);
boxe.position = new BABYLON.Vector3(0,0.5,-3);
boxe.scaling = new BABYLON.Vector3(2,1,2);
var ground = BABYLON.Mesh.CreateGround("ground1", 10, 6, 2, scene);
ground.position = new BABYLON.Vector3(0,0,0);
return scene;
};
var scene = createScene();
engine.runRenderLoop(function() {
scene.render();
});
</script>
</body>
</html>
We have scaled in x, y and z direction with values as 2, 1,2 and used new BABYLON.Vector3(2,1,2) for scaling.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2389,
"s": 2183,
"text": "Scaling basically means increasing or decreasing the size of the object at a uniform scale. Let us now consider an example where we will increase/decrease the size of the object along the x or y or z-axis."
},
{
"code": null,
"e": 4483,
"s": 2389,
"text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type=\"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n scene.clearColor = new BABYLON.Color3(0, 1, 0);\n \n var camera = new BABYLON.ArcRotateCamera(\"Camera\", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);\n scene.activeCamera.attachControl(canvas);\n \n var light = new BABYLON.PointLight(\"Omni\", new BABYLON.Vector3(0, 100, 100), scene);\n\n var boxa = BABYLON.Mesh.CreateBox(\"BoxA\", 1.0, scene);\n boxa.position = new BABYLON.Vector3(0,0.5,0);\n\n var boxb = BABYLON.Mesh.CreateBox(\"BoxB\", 1.0, scene);\n boxb.position = new BABYLON.Vector3(3,0.5,0);\t\t\n boxb.scaling = new BABYLON.Vector3(2,1,2);\n\n var boxc = BABYLON.Mesh.CreateBox(\"BoxC\", 1.0, scene);\n boxc.position = new BABYLON.Vector3(-3,0.5,0);\n boxc.scaling = new BABYLON.Vector3(2,1,2);\n\n var boxd = BABYLON.Mesh.CreateBox(\"BoxD\", 1.0, scene);\n boxd.position = new BABYLON.Vector3(0,0.5,3);\n boxd.scaling = new BABYLON.Vector3(2,1,2);\n\n var boxe = BABYLON.Mesh.CreateBox(\"BoxE\", 1.0, scene);\n boxe.position = new BABYLON.Vector3(0,0.5,-3);\n boxe.scaling = new BABYLON.Vector3(2,1,2);\n\n var ground = BABYLON.Mesh.CreateGround(\"ground1\", 10, 6, 2, scene);\n ground.position = new BABYLON.Vector3(0,0,0);\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4593,
"s": 4483,
"text": "We have scaled in x, y and z direction with values as 2, 1,2 and used new BABYLON.Vector3(2,1,2) for scaling."
},
{
"code": null,
"e": 4600,
"s": 4593,
"text": " Print"
},
{
"code": null,
"e": 4611,
"s": 4600,
"text": " Add Notes"
}
] |
How to change screen brightness programmatically in android?
|
This example demonstrates how do I change screen brightness programmatically 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"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:padding="8dp"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Off Screen"/>
<SeekBar
android:id="@+id/seekBar"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Context;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
SeekBar lightBar;
Context context;
int brightness;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lightBar = findViewById(R.id.seekBar);
context = getApplicationContext();
brightness =
Settings.System.getInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 0);
lightBar.setProgress(brightness);
lightBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
}
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"
xmlns:tools="http://schemas.android.com/tools"
package="app.com.sample">
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<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 −
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "This example demonstrates how do I change screen brightness programmatically in android."
},
{
"code": null,
"e": 1280,
"s": 1151,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1345,
"s": 1280,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2066,
"s": 1345,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:padding=\"8dp\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Turn Off Screen\"/>\n <SeekBar\n android:id=\"@+id/seekBar\"\n android:layout_marginTop=\"10dp\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2123,
"s": 2066,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3329,
"s": 2123,
"text": "import android.content.Context;\nimport android.provider.Settings;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.SeekBar;\npublic class MainActivity extends AppCompatActivity {\n SeekBar lightBar;\n Context context;\n int brightness;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n lightBar = findViewById(R.id.seekBar);\n context = getApplicationContext();\n brightness =\n Settings.System.getInt(context.getContentResolver(),\n Settings.System.SCREEN_BRIGHTNESS, 0);\n lightBar.setProgress(brightness);\n lightBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {\n @Override\n public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {\n Settings.System.putInt(context.getContentResolver(),\n Settings.System.SCREEN_BRIGHTNESS, progress);\n }\n @Override\n public void onStartTrackingTouch(SeekBar seekBar) { }\n @Override\n public void onStopTrackingTouch(SeekBar seekBar) { }\n });\n }\n}"
},
{
"code": null,
"e": 3384,
"s": 3329,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4260,
"s": 3384,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n package=\"app.com.sample\">\n <uses-permission\n android:name=\"android.permission.WRITE_SETTINGS\"\n tools:ignore=\"ProtectedPermissions\" />\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\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4607,
"s": 4260,
"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 −"
}
] |
Scrapy - Item Loaders
|
Item loaders provide a convenient way to fill the items that are scraped from the websites.
The declaration of Item Loaders is like Items.
For example −
from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst, MapCompose, Join
class DemoLoader(ItemLoader):
default_output_processor = TakeFirst()
title_in = MapCompose(unicode.title)
title_out = Join()
size_in = MapCompose(unicode.strip)
# you can continue scraping here
In the above code, you can see that input processors are declared using _in suffix and output processors are declared using _out suffix.
The ItemLoader.default_input_processor and ItemLoader.default_output_processor attributes are used to declare default input/output processors.
To use Item Loader, first instantiate with dict-like object or without one where the item uses Item class specified in ItemLoader.default_item_class attribute.
You can use selectors to collect values into the Item Loader.
You can use selectors to collect values into the Item Loader.
You can add more values in the same item field, where Item Loader will use an appropriate handler to add these values.
You can add more values in the same item field, where Item Loader will use an appropriate handler to add these values.
The following code demonstrates how items are populated using Item Loaders −
from scrapy.loader import ItemLoader
from demoproject.items import Demo
def parse(self, response):
l = ItemLoader(item = Product(), response = response)
l.add_xpath("title", "//div[@class = 'product_title']")
l.add_xpath("title", "//div[@class = 'product_name']")
l.add_xpath("desc", "//div[@class = 'desc']")
l.add_css("size", "div#size]")
l.add_value("last_updated", "yesterday")
return l.load_item()
As shown above, there are two different XPaths from which the title field is extracted using add_xpath() method −
1. //div[@class = "product_title"]
2. //div[@class = "product_name"]
Thereafter, a similar request is used for desc field. The size data is extracted using add_css() method and last_updated is filled with a value "yesterday" using add_value() method.
Once all the data is collected, call ItemLoader.load_item() method which returns the items filled with data extracted using add_xpath(), add_css() and add_value() methods.
Each field of an Item Loader contains one input processor and one output processor.
When data is extracted, input processor processes it and its result is stored in ItemLoader.
When data is extracted, input processor processes it and its result is stored in ItemLoader.
Next, after collecting the data, call ItemLoader.load_item() method to get the populated Item object.
Next, after collecting the data, call ItemLoader.load_item() method to get the populated Item object.
Finally, you can assign the result of the output processor to the item.
Finally, you can assign the result of the output processor to the item.
The following code demonstrates how to call input and output processors for a specific field −
l = ItemLoader(Product(), some_selector)
l.add_xpath("title", xpath1) # [1]
l.add_xpath("title", xpath2) # [2]
l.add_css("title", css) # [3]
l.add_value("title", "demo") # [4]
return l.load_item() # [5]
Line 1 − The data of title is extracted from xpath1 and passed through the input processor and its result is collected and stored in ItemLoader.
Line 2 − Similarly, the title is extracted from xpath2 and passed through the same input processor and its result is added to the data collected for [1].
Line 3 − The title is extracted from css selector and passed through the same input processor and the result is added to the data collected for [1] and [2].
Line 4 − Next, the value "demo" is assigned and passed through the input processors.
Line 5 − Finally, the data is collected internally from all the fields and passed to the output processor and the final value is assigned to the Item.
The input and output processors are declared in the ItemLoader definition. Apart from this, they can also be specified in the Item Field metadata.
For example −
import scrapy
from scrapy.loader.processors import Join, MapCompose, TakeFirst
from w3lib.html import remove_tags
def filter_size(value):
if value.isdigit():
return value
class Item(scrapy.Item):
name = scrapy.Field(
input_processor = MapCompose(remove_tags),
output_processor = Join(),
)
size = scrapy.Field(
input_processor = MapCompose(remove_tags, filter_price),
output_processor = TakeFirst(),
)
>>> from scrapy.loader import ItemLoader
>>> il = ItemLoader(item = Product())
>>> il.add_value('title', [u'Hello', u'<strong>world</strong>'])
>>> il.add_value('size', [u'<span>100 kg</span>'])
>>> il.load_item()
It displays an output as −
{'title': u'Hello world', 'size': u'100 kg'}
The Item Loader Context is a dict of arbitrary key values shared among input and output processors.
For example, assume you have a function parse_length −
def parse_length(text, loader_context):
unit = loader_context.get('unit', 'cm')
# You can write parsing code of length here
return parsed_length
By receiving loader_context arguements, it tells the Item Loader it can receive Item Loader context. There are several ways to change the value of Item Loader context −
Modify current active Item Loader context −
Modify current active Item Loader context −
loader = ItemLoader (product)
loader.context ["unit"] = "mm"
On Item Loader instantiation −
On Item Loader instantiation −
loader = ItemLoader(product, unit = "mm")
On Item Loader declaration for input/output processors that instantiates with Item Loader context −
On Item Loader declaration for input/output processors that instantiates with Item Loader context −
class ProductLoader(ItemLoader):
length_out = MapCompose(parse_length, unit = "mm")
It is an object which returns a new item loader to populate the given item. It has the following class −
class scrapy.loader.ItemLoader([item, selector, response, ]**kwargs)
The following table shows the parameters of ItemLoader objects −
item
It is the item to populate by calling add_xpath(), add_css() or add_value().
selector
It is used to extract data from websites.
response
It is used to construct selector using default_selector_class.
Following table shows the methods of ItemLoader objects −
get_value(value, *processors, **kwargs)
By a given processor and keyword arguments, the value is processed by get_value() method.
>>> from scrapy.loader.processors import TakeFirst
>>> loader.get_value(u'title: demoweb', TakeFirst(),
unicode.upper, re = 'title: (.+)')
'DEMOWEB`
add_value(field_name, value, *processors, **kwargs)
It processes the value and adds to the field where it is first passed through get_value by giving processors and keyword arguments before passing through field input processor.
loader.add_value('title', u'DVD')
loader.add_value('colors', [u'black', u'white'])
loader.add_value('length', u'80')
loader.add_value('price', u'2500')
replace_value(field_name, value, *processors, **kwargs)
It replaces the collected data with a new value.
loader.replace_value('title', u'DVD')
loader.replace_value('colors', [u'black',
u'white'])
loader.replace_value('length', u'80')
loader.replace_value('price', u'2500')
get_xpath(xpath, *processors, **kwargs)
It is used to extract unicode strings by giving processors and keyword arguments by receiving XPath.
# HTML code: <div class = "item-name">DVD</div>
loader.get_xpath("//div[@class =
'item-name']")
# HTML code: <div id = "length">the length is
45cm</div>
loader.get_xpath("//div[@id = 'length']", TakeFirst(),
re = "the length is (.*)")
add_xpath(field_name, xpath, *processors, **kwargs)
It receives XPath to the field which extracts unicode strings.
# HTML code: <div class = "item-name">DVD</div>
loader.add_xpath('name', '//div
[@class = "item-name"]')
# HTML code: <div id = "length">the length is
45cm</div>
loader.add_xpath('length', '//div[@id = "length"]',
re = 'the length is (.*)')
replace_xpath(field_name, xpath, *processors, **kwargs)
It replaces the collected data using XPath from sites.
# HTML code: <div class = "item-name">DVD</div>
loader.replace_xpath('name', '
//div[@class = "item-name"]')
# HTML code: <div id = "length">the length is
45cm</div>
loader.replace_xpath('length', '
//div[@id = "length"]', re = 'the length is (.*)')
get_css(css, *processors, **kwargs)
It receives CSS selector used to extract the unicode strings.
loader.get_css("div.item-name")
loader.get_css("div#length", TakeFirst(),
re = "the length is (.*)")
add_css(field_name, css, *processors, **kwargs)
It is similar to add_value() method with one difference that it adds CSS selector to the field.
loader.add_css('name', 'div.item-name')
loader.add_css('length', 'div#length',
re = 'the length is (.*)')
replace_css(field_name, css, *processors, **kwargs)
It replaces the extracted data using CSS selector.
loader.replace_css('name', 'div.item-name')
loader.replace_css('length', 'div#length',
re = 'the length is (.*)')
load_item()
When the data is collected, this method fills the item with collected data and returns it.
def parse(self, response):
l = ItemLoader(item = Product(),
response = response)
l.add_xpath('title', '//
div[@class = "product_title"]')
loader.load_item()
nested_xpath(xpath)
It is used to create nested loaders with an XPath selector.
loader = ItemLoader(item = Item())
loader.add_xpath('social', '
a[@class = "social"]/@href')
loader.add_xpath('email', '
a[@class = "email"]/@href')
nested_css(css)
It is used to create nested loaders with a CSS selector.
loader = ItemLoader(item = Item())
loader.add_css('social', 'a[@class = "social"]/@href')
loader.add_css('email', 'a[@class = "email"]/@href')
Following table shows the attributes of ItemLoader objects −
item
It is an object on which the Item Loader performs parsing.
context
It is the current context of Item Loader that is active.
default_item_class
It is used to represent the items, if not given in the constructor.
default_input_processor
The fields which don't specify input processor are the only ones for which default_input_processors are used.
default_output_processor
The fields which don't specify the output processor are the only ones for which default_output_processors are used.
default_selector_class
It is a class used to construct the selector, if it is not given in the constructor.
selector
It is an object that can be used to extract the data from sites.
It is used to create nested loaders while parsing the values from the subsection of a document. If you don't create nested loaders, you need to specify full XPath or CSS for each value that you want to extract.
For instance, assume that the data is being extracted from a header page −
<header>
<a class = "social" href = "http://facebook.com/whatever">facebook</a>
<a class = "social" href = "http://twitter.com/whatever">twitter</a>
<a class = "email" href = "mailto:[email protected]">send mail</a>
</header>
Next, you can create a nested loader with header selector by adding related values to the header −
loader = ItemLoader(item = Item())
header_loader = loader.nested_xpath('//header')
header_loader.add_xpath('social', 'a[@class = "social"]/@href')
header_loader.add_xpath('email', 'a[@class = "email"]/@href')
loader.load_item()
Item Loaders are designed to relieve the maintenance which becomes a fundamental problem when your project acquires more spiders.
For instance, assume that a site has their product name enclosed in three dashes (e.g. --DVD---). You can remove those dashes by reusing the default Product Item Loader, if you don’t want it in the final product names as shown in the following code −
from scrapy.loader.processors import MapCompose
from demoproject.ItemLoaders import DemoLoader
def strip_dashes(x):
return x.strip('-')
class SiteSpecificLoader(DemoLoader):
title_in = MapCompose(strip_dashes, DemoLoader.title_in)
Following are some of the commonly used built-in processors −
It returns the original value without altering it. For example −
>>> from scrapy.loader.processors import Identity
>>> proc = Identity()
>>> proc(['a', 'b', 'c'])
['a', 'b', 'c']
It returns the first value that is non-null/non-empty from the list of received values. For example −
>>> from scrapy.loader.processors import TakeFirst
>>> proc = TakeFirst()
>>> proc(['', 'a', 'b', 'c'])
'a'
It returns the value attached to the separator. The default separator is u' ' and it is equivalent to the function u' '.join. For example −
>>> from scrapy.loader.processors import Join
>>> proc = Join()
>>> proc(['a', 'b', 'c'])
u'a b c'
>>> proc = Join('<br>')
>>> proc(['a', 'b', 'c'])
u'a<br>b<br>c'
It is defined by a processor where each of its input value is passed to the first function, and the result of that function is passed to the second function and so on, till lthe ast function returns the final value as output.
For example −
>>> from scrapy.loader.processors import Compose
>>> proc = Compose(lambda v: v[0], str.upper)
>>> proc(['python', 'scrapy'])
'PYTHON'
It is a processor where the input value is iterated and the first function is applied to each element. Next, the result of these function calls are concatenated to build new iterable that is then applied to the second function and so on, till the last function.
For example −
>>> def filter_scrapy(x):
return None if x == 'scrapy' else x
>>> from scrapy.loader.processors import MapCompose
>>> proc = MapCompose(filter_scrapy, unicode.upper)
>>> proc([u'hi', u'everyone', u'im', u'pythonscrapy'])
[u'HI, u'IM', u'PYTHONSCRAPY']
This class queries the value using the provided json path and returns the output.
For example −
>>> from scrapy.loader.processors import SelectJmes, Compose, MapCompose
>>> proc = SelectJmes("hello")
>>> proc({'hello': 'scrapy'})
'scrapy'
>>> proc({'hello': {'scrapy': 'world'}})
{'scrapy': 'world'}
Following is the code, which queries the value by importing json −
>>> import json
>>> proc_single_json_str = Compose(json.loads, SelectJmes("hello"))
>>> proc_single_json_str('{"hello": "scrapy"}')
u'scrapy'
>>> proc_json_list = Compose(json.loads, MapCompose(SelectJmes('hello')))
>>> proc_json_list('[{"hello":"scrapy"}, {"world":"env"}]')
[u'scrapy']
27 Lectures
3.5 hours
Attreya Bhatt
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2329,
"s": 2237,
"text": "Item loaders provide a convenient way to fill the items that are scraped from the websites."
},
{
"code": null,
"e": 2376,
"s": 2329,
"text": "The declaration of Item Loaders is like Items."
},
{
"code": null,
"e": 2390,
"s": 2376,
"text": "For example −"
},
{
"code": null,
"e": 2714,
"s": 2390,
"text": "from scrapy.loader import ItemLoader \nfrom scrapy.loader.processors import TakeFirst, MapCompose, Join \n\nclass DemoLoader(ItemLoader): \n default_output_processor = TakeFirst() \n title_in = MapCompose(unicode.title) \n title_out = Join() \n size_in = MapCompose(unicode.strip) \n # you can continue scraping here"
},
{
"code": null,
"e": 2851,
"s": 2714,
"text": "In the above code, you can see that input processors are declared using _in suffix and output processors are declared using _out suffix."
},
{
"code": null,
"e": 2994,
"s": 2851,
"text": "The ItemLoader.default_input_processor and ItemLoader.default_output_processor attributes are used to declare default input/output processors."
},
{
"code": null,
"e": 3154,
"s": 2994,
"text": "To use Item Loader, first instantiate with dict-like object or without one where the item uses Item class specified in ItemLoader.default_item_class attribute."
},
{
"code": null,
"e": 3216,
"s": 3154,
"text": "You can use selectors to collect values into the Item Loader."
},
{
"code": null,
"e": 3278,
"s": 3216,
"text": "You can use selectors to collect values into the Item Loader."
},
{
"code": null,
"e": 3397,
"s": 3278,
"text": "You can add more values in the same item field, where Item Loader will use an appropriate handler to add these values."
},
{
"code": null,
"e": 3516,
"s": 3397,
"text": "You can add more values in the same item field, where Item Loader will use an appropriate handler to add these values."
},
{
"code": null,
"e": 3593,
"s": 3516,
"text": "The following code demonstrates how items are populated using Item Loaders −"
},
{
"code": null,
"e": 4022,
"s": 3593,
"text": "from scrapy.loader import ItemLoader \nfrom demoproject.items import Demo \n\ndef parse(self, response): \n l = ItemLoader(item = Product(), response = response)\n l.add_xpath(\"title\", \"//div[@class = 'product_title']\")\n l.add_xpath(\"title\", \"//div[@class = 'product_name']\")\n l.add_xpath(\"desc\", \"//div[@class = 'desc']\")\n l.add_css(\"size\", \"div#size]\")\n l.add_value(\"last_updated\", \"yesterday\")\n return l.load_item()"
},
{
"code": null,
"e": 4136,
"s": 4022,
"text": "As shown above, there are two different XPaths from which the title field is extracted using add_xpath() method −"
},
{
"code": null,
"e": 4207,
"s": 4136,
"text": "1. //div[@class = \"product_title\"] \n2. //div[@class = \"product_name\"]\n"
},
{
"code": null,
"e": 4389,
"s": 4207,
"text": "Thereafter, a similar request is used for desc field. The size data is extracted using add_css() method and last_updated is filled with a value \"yesterday\" using add_value() method."
},
{
"code": null,
"e": 4561,
"s": 4389,
"text": "Once all the data is collected, call ItemLoader.load_item() method which returns the items filled with data extracted using add_xpath(), add_css() and add_value() methods."
},
{
"code": null,
"e": 4645,
"s": 4561,
"text": "Each field of an Item Loader contains one input processor and one output processor."
},
{
"code": null,
"e": 4738,
"s": 4645,
"text": "When data is extracted, input processor processes it and its result is stored in ItemLoader."
},
{
"code": null,
"e": 4831,
"s": 4738,
"text": "When data is extracted, input processor processes it and its result is stored in ItemLoader."
},
{
"code": null,
"e": 4933,
"s": 4831,
"text": "Next, after collecting the data, call ItemLoader.load_item() method to get the populated Item object."
},
{
"code": null,
"e": 5035,
"s": 4933,
"text": "Next, after collecting the data, call ItemLoader.load_item() method to get the populated Item object."
},
{
"code": null,
"e": 5107,
"s": 5035,
"text": "Finally, you can assign the result of the output processor to the item."
},
{
"code": null,
"e": 5179,
"s": 5107,
"text": "Finally, you can assign the result of the output processor to the item."
},
{
"code": null,
"e": 5274,
"s": 5179,
"text": "The following code demonstrates how to call input and output processors for a specific field −"
},
{
"code": null,
"e": 5490,
"s": 5274,
"text": "l = ItemLoader(Product(), some_selector)\nl.add_xpath(\"title\", xpath1) # [1]\nl.add_xpath(\"title\", xpath2) # [2]\nl.add_css(\"title\", css) # [3]\nl.add_value(\"title\", \"demo\") # [4]\nreturn l.load_item() # [5]"
},
{
"code": null,
"e": 5635,
"s": 5490,
"text": "Line 1 − The data of title is extracted from xpath1 and passed through the input processor and its result is collected and stored in ItemLoader."
},
{
"code": null,
"e": 5789,
"s": 5635,
"text": "Line 2 − Similarly, the title is extracted from xpath2 and passed through the same input processor and its result is added to the data collected for [1]."
},
{
"code": null,
"e": 5946,
"s": 5789,
"text": "Line 3 − The title is extracted from css selector and passed through the same input processor and the result is added to the data collected for [1] and [2]."
},
{
"code": null,
"e": 6031,
"s": 5946,
"text": "Line 4 − Next, the value \"demo\" is assigned and passed through the input processors."
},
{
"code": null,
"e": 6182,
"s": 6031,
"text": "Line 5 − Finally, the data is collected internally from all the fields and passed to the output processor and the final value is assigned to the Item."
},
{
"code": null,
"e": 6329,
"s": 6182,
"text": "The input and output processors are declared in the ItemLoader definition. Apart from this, they can also be specified in the Item Field metadata."
},
{
"code": null,
"e": 6343,
"s": 6329,
"text": "For example −"
},
{
"code": null,
"e": 7026,
"s": 6343,
"text": "import scrapy \nfrom scrapy.loader.processors import Join, MapCompose, TakeFirst \nfrom w3lib.html import remove_tags \n\ndef filter_size(value): \n if value.isdigit(): \n return value \n\nclass Item(scrapy.Item): \n name = scrapy.Field( \n input_processor = MapCompose(remove_tags), \n output_processor = Join(), \n )\n size = scrapy.Field( \n input_processor = MapCompose(remove_tags, filter_price), \n output_processor = TakeFirst(), \n ) \n\n>>> from scrapy.loader import ItemLoader \n>>> il = ItemLoader(item = Product()) \n>>> il.add_value('title', [u'Hello', u'<strong>world</strong>']) \n>>> il.add_value('size', [u'<span>100 kg</span>']) \n>>> il.load_item()"
},
{
"code": null,
"e": 7053,
"s": 7026,
"text": "It displays an output as −"
},
{
"code": null,
"e": 7099,
"s": 7053,
"text": "{'title': u'Hello world', 'size': u'100 kg'}\n"
},
{
"code": null,
"e": 7199,
"s": 7099,
"text": "The Item Loader Context is a dict of arbitrary key values shared among input and output processors."
},
{
"code": null,
"e": 7254,
"s": 7199,
"text": "For example, assume you have a function parse_length −"
},
{
"code": null,
"e": 7416,
"s": 7254,
"text": "def parse_length(text, loader_context): \n unit = loader_context.get('unit', 'cm') \n \n # You can write parsing code of length here \n return parsed_length"
},
{
"code": null,
"e": 7585,
"s": 7416,
"text": "By receiving loader_context arguements, it tells the Item Loader it can receive Item Loader context. There are several ways to change the value of Item Loader context −"
},
{
"code": null,
"e": 7629,
"s": 7585,
"text": "Modify current active Item Loader context −"
},
{
"code": null,
"e": 7673,
"s": 7629,
"text": "Modify current active Item Loader context −"
},
{
"code": null,
"e": 7734,
"s": 7673,
"text": "loader = ItemLoader (product)\nloader.context [\"unit\"] = \"mm\""
},
{
"code": null,
"e": 7765,
"s": 7734,
"text": "On Item Loader instantiation −"
},
{
"code": null,
"e": 7796,
"s": 7765,
"text": "On Item Loader instantiation −"
},
{
"code": null,
"e": 7838,
"s": 7796,
"text": "loader = ItemLoader(product, unit = \"mm\")"
},
{
"code": null,
"e": 7938,
"s": 7838,
"text": "On Item Loader declaration for input/output processors that instantiates with Item Loader context −"
},
{
"code": null,
"e": 8038,
"s": 7938,
"text": "On Item Loader declaration for input/output processors that instantiates with Item Loader context −"
},
{
"code": null,
"e": 8125,
"s": 8038,
"text": "class ProductLoader(ItemLoader):\n length_out = MapCompose(parse_length, unit = \"mm\")"
},
{
"code": null,
"e": 8230,
"s": 8125,
"text": "It is an object which returns a new item loader to populate the given item. It has the following class −"
},
{
"code": null,
"e": 8299,
"s": 8230,
"text": "class scrapy.loader.ItemLoader([item, selector, response, ]**kwargs)"
},
{
"code": null,
"e": 8364,
"s": 8299,
"text": "The following table shows the parameters of ItemLoader objects −"
},
{
"code": null,
"e": 8369,
"s": 8364,
"text": "item"
},
{
"code": null,
"e": 8446,
"s": 8369,
"text": "It is the item to populate by calling add_xpath(), add_css() or add_value()."
},
{
"code": null,
"e": 8455,
"s": 8446,
"text": "selector"
},
{
"code": null,
"e": 8497,
"s": 8455,
"text": "It is used to extract data from websites."
},
{
"code": null,
"e": 8506,
"s": 8497,
"text": "response"
},
{
"code": null,
"e": 8569,
"s": 8506,
"text": "It is used to construct selector using default_selector_class."
},
{
"code": null,
"e": 8627,
"s": 8569,
"text": "Following table shows the methods of ItemLoader objects −"
},
{
"code": null,
"e": 8667,
"s": 8627,
"text": "get_value(value, *processors, **kwargs)"
},
{
"code": null,
"e": 8757,
"s": 8667,
"text": "By a given processor and keyword arguments, the value is processed by get_value() method."
},
{
"code": null,
"e": 8907,
"s": 8757,
"text": ">>> from scrapy.loader.processors import TakeFirst\n>>> loader.get_value(u'title: demoweb', TakeFirst(), \nunicode.upper, re = 'title: (.+)')\n'DEMOWEB`"
},
{
"code": null,
"e": 8959,
"s": 8907,
"text": "add_value(field_name, value, *processors, **kwargs)"
},
{
"code": null,
"e": 9136,
"s": 8959,
"text": "It processes the value and adds to the field where it is first passed through get_value by giving processors and keyword arguments before passing through field input processor."
},
{
"code": null,
"e": 9288,
"s": 9136,
"text": "loader.add_value('title', u'DVD')\nloader.add_value('colors', [u'black', u'white'])\nloader.add_value('length', u'80')\nloader.add_value('price', u'2500')"
},
{
"code": null,
"e": 9344,
"s": 9288,
"text": "replace_value(field_name, value, *processors, **kwargs)"
},
{
"code": null,
"e": 9393,
"s": 9344,
"text": "It replaces the collected data with a new value."
},
{
"code": null,
"e": 9562,
"s": 9393,
"text": "loader.replace_value('title', u'DVD')\nloader.replace_value('colors', [u'black', \nu'white'])\nloader.replace_value('length', u'80')\nloader.replace_value('price', u'2500')"
},
{
"code": null,
"e": 9602,
"s": 9562,
"text": "get_xpath(xpath, *processors, **kwargs)"
},
{
"code": null,
"e": 9703,
"s": 9602,
"text": "It is used to extract unicode strings by giving processors and keyword arguments by receiving XPath."
},
{
"code": null,
"e": 9942,
"s": 9703,
"text": "# HTML code: <div class = \"item-name\">DVD</div>\nloader.get_xpath(\"//div[@class = \n'item-name']\")\n\n# HTML code: <div id = \"length\">the length is \n45cm</div>\nloader.get_xpath(\"//div[@id = 'length']\", TakeFirst(), \nre = \"the length is (.*)\")"
},
{
"code": null,
"e": 9994,
"s": 9942,
"text": "add_xpath(field_name, xpath, *processors, **kwargs)"
},
{
"code": null,
"e": 10057,
"s": 9994,
"text": "It receives XPath to the field which extracts unicode strings."
},
{
"code": null,
"e": 10301,
"s": 10057,
"text": "# HTML code: <div class = \"item-name\">DVD</div>\nloader.add_xpath('name', '//div\n[@class = \"item-name\"]')\n\n# HTML code: <div id = \"length\">the length is \n45cm</div>\nloader.add_xpath('length', '//div[@id = \"length\"]',\n re = 'the length is (.*)')"
},
{
"code": null,
"e": 10357,
"s": 10301,
"text": "replace_xpath(field_name, xpath, *processors, **kwargs)"
},
{
"code": null,
"e": 10412,
"s": 10357,
"text": "It replaces the collected data using XPath from sites."
},
{
"code": null,
"e": 10664,
"s": 10412,
"text": "# HTML code: <div class = \"item-name\">DVD</div>\nloader.replace_xpath('name', '\n//div[@class = \"item-name\"]')\n\n# HTML code: <div id = \"length\">the length is\n 45cm</div>\nloader.replace_xpath('length', '\n//div[@id = \"length\"]', re = 'the length is (.*)')"
},
{
"code": null,
"e": 10700,
"s": 10664,
"text": "get_css(css, *processors, **kwargs)"
},
{
"code": null,
"e": 10762,
"s": 10700,
"text": "It receives CSS selector used to extract the unicode strings."
},
{
"code": null,
"e": 10864,
"s": 10762,
"text": "loader.get_css(\"div.item-name\")\nloader.get_css(\"div#length\", TakeFirst(), \nre = \"the length is (.*)\")"
},
{
"code": null,
"e": 10912,
"s": 10864,
"text": "add_css(field_name, css, *processors, **kwargs)"
},
{
"code": null,
"e": 11008,
"s": 10912,
"text": "It is similar to add_value() method with one difference that it adds CSS selector to the field."
},
{
"code": null,
"e": 11115,
"s": 11008,
"text": "loader.add_css('name', 'div.item-name')\nloader.add_css('length', 'div#length', \nre = 'the length is (.*)')"
},
{
"code": null,
"e": 11167,
"s": 11115,
"text": "replace_css(field_name, css, *processors, **kwargs)"
},
{
"code": null,
"e": 11218,
"s": 11167,
"text": "It replaces the extracted data using CSS selector."
},
{
"code": null,
"e": 11333,
"s": 11218,
"text": "loader.replace_css('name', 'div.item-name')\nloader.replace_css('length', 'div#length',\n re = 'the length is (.*)')"
},
{
"code": null,
"e": 11345,
"s": 11333,
"text": "load_item()"
},
{
"code": null,
"e": 11436,
"s": 11345,
"text": "When the data is collected, this method fills the item with collected data and returns it."
},
{
"code": null,
"e": 11594,
"s": 11436,
"text": "def parse(self, response):\nl = ItemLoader(item = Product(), \nresponse = response)\nl.add_xpath('title', '//\ndiv[@class = \"product_title\"]')\nloader.load_item()"
},
{
"code": null,
"e": 11614,
"s": 11594,
"text": "nested_xpath(xpath)"
},
{
"code": null,
"e": 11674,
"s": 11614,
"text": "It is used to create nested loaders with an XPath selector."
},
{
"code": null,
"e": 11823,
"s": 11674,
"text": "loader = ItemLoader(item = Item())\nloader.add_xpath('social', '\na[@class = \"social\"]/@href')\nloader.add_xpath('email', '\na[@class = \"email\"]/@href')"
},
{
"code": null,
"e": 11839,
"s": 11823,
"text": "nested_css(css)"
},
{
"code": null,
"e": 11896,
"s": 11839,
"text": "It is used to create nested loaders with a CSS selector."
},
{
"code": null,
"e": 12040,
"s": 11896,
"text": "loader = ItemLoader(item = Item())\nloader.add_css('social', 'a[@class = \"social\"]/@href')\nloader.add_css('email', 'a[@class = \"email\"]/@href')\t"
},
{
"code": null,
"e": 12101,
"s": 12040,
"text": "Following table shows the attributes of ItemLoader objects −"
},
{
"code": null,
"e": 12106,
"s": 12101,
"text": "item"
},
{
"code": null,
"e": 12165,
"s": 12106,
"text": "It is an object on which the Item Loader performs parsing."
},
{
"code": null,
"e": 12173,
"s": 12165,
"text": "context"
},
{
"code": null,
"e": 12230,
"s": 12173,
"text": "It is the current context of Item Loader that is active."
},
{
"code": null,
"e": 12249,
"s": 12230,
"text": "default_item_class"
},
{
"code": null,
"e": 12317,
"s": 12249,
"text": "It is used to represent the items, if not given in the constructor."
},
{
"code": null,
"e": 12341,
"s": 12317,
"text": "default_input_processor"
},
{
"code": null,
"e": 12451,
"s": 12341,
"text": "The fields which don't specify input processor are the only ones for which default_input_processors are used."
},
{
"code": null,
"e": 12476,
"s": 12451,
"text": "default_output_processor"
},
{
"code": null,
"e": 12592,
"s": 12476,
"text": "The fields which don't specify the output processor are the only ones for which default_output_processors are used."
},
{
"code": null,
"e": 12615,
"s": 12592,
"text": "default_selector_class"
},
{
"code": null,
"e": 12700,
"s": 12615,
"text": "It is a class used to construct the selector, if it is not given in the constructor."
},
{
"code": null,
"e": 12709,
"s": 12700,
"text": "selector"
},
{
"code": null,
"e": 12774,
"s": 12709,
"text": "It is an object that can be used to extract the data from sites."
},
{
"code": null,
"e": 12985,
"s": 12774,
"text": "It is used to create nested loaders while parsing the values from the subsection of a document. If you don't create nested loaders, you need to specify full XPath or CSS for each value that you want to extract."
},
{
"code": null,
"e": 13060,
"s": 12985,
"text": "For instance, assume that the data is being extracted from a header page −"
},
{
"code": null,
"e": 13297,
"s": 13060,
"text": "<header>\n <a class = \"social\" href = \"http://facebook.com/whatever\">facebook</a>\n <a class = \"social\" href = \"http://twitter.com/whatever\">twitter</a>\n <a class = \"email\" href = \"mailto:[email protected]\">send mail</a>\n</header>"
},
{
"code": null,
"e": 13396,
"s": 13297,
"text": "Next, you can create a nested loader with header selector by adding related values to the header −"
},
{
"code": null,
"e": 13624,
"s": 13396,
"text": "loader = ItemLoader(item = Item())\nheader_loader = loader.nested_xpath('//header')\nheader_loader.add_xpath('social', 'a[@class = \"social\"]/@href')\nheader_loader.add_xpath('email', 'a[@class = \"email\"]/@href')\nloader.load_item()"
},
{
"code": null,
"e": 13754,
"s": 13624,
"text": "Item Loaders are designed to relieve the maintenance which becomes a fundamental problem when your project acquires more spiders."
},
{
"code": null,
"e": 14005,
"s": 13754,
"text": "For instance, assume that a site has their product name enclosed in three dashes (e.g. --DVD---). You can remove those dashes by reusing the default Product Item Loader, if you don’t want it in the final product names as shown in the following code −"
},
{
"code": null,
"e": 14251,
"s": 14005,
"text": "from scrapy.loader.processors import MapCompose \nfrom demoproject.ItemLoaders import DemoLoader \n\ndef strip_dashes(x): \n return x.strip('-') \n\nclass SiteSpecificLoader(DemoLoader): \n title_in = MapCompose(strip_dashes, DemoLoader.title_in)"
},
{
"code": null,
"e": 14313,
"s": 14251,
"text": "Following are some of the commonly used built-in processors −"
},
{
"code": null,
"e": 14378,
"s": 14313,
"text": "It returns the original value without altering it. For example −"
},
{
"code": null,
"e": 14492,
"s": 14378,
"text": ">>> from scrapy.loader.processors import Identity\n>>> proc = Identity()\n>>> proc(['a', 'b', 'c'])\n['a', 'b', 'c']"
},
{
"code": null,
"e": 14594,
"s": 14492,
"text": "It returns the first value that is non-null/non-empty from the list of received values. For example −"
},
{
"code": null,
"e": 14702,
"s": 14594,
"text": ">>> from scrapy.loader.processors import TakeFirst\n>>> proc = TakeFirst()\n>>> proc(['', 'a', 'b', 'c'])\n'a'"
},
{
"code": null,
"e": 14842,
"s": 14702,
"text": "It returns the value attached to the separator. The default separator is u' ' and it is equivalent to the function u' '.join. For example −"
},
{
"code": null,
"e": 15006,
"s": 14842,
"text": ">>> from scrapy.loader.processors import Join\n>>> proc = Join()\n>>> proc(['a', 'b', 'c'])\nu'a b c'\n>>> proc = Join('<br>')\n>>> proc(['a', 'b', 'c'])\nu'a<br>b<br>c'"
},
{
"code": null,
"e": 15232,
"s": 15006,
"text": "It is defined by a processor where each of its input value is passed to the first function, and the result of that function is passed to the second function and so on, till lthe ast function returns the final value as output."
},
{
"code": null,
"e": 15246,
"s": 15232,
"text": "For example −"
},
{
"code": null,
"e": 15381,
"s": 15246,
"text": ">>> from scrapy.loader.processors import Compose\n>>> proc = Compose(lambda v: v[0], str.upper)\n>>> proc(['python', 'scrapy'])\n'PYTHON'"
},
{
"code": null,
"e": 15643,
"s": 15381,
"text": "It is a processor where the input value is iterated and the first function is applied to each element. Next, the result of these function calls are concatenated to build new iterable that is then applied to the second function and so on, till the last function."
},
{
"code": null,
"e": 15657,
"s": 15643,
"text": "For example −"
},
{
"code": null,
"e": 15920,
"s": 15657,
"text": ">>> def filter_scrapy(x): \n return None if x == 'scrapy' else x \n\n>>> from scrapy.loader.processors import MapCompose \n>>> proc = MapCompose(filter_scrapy, unicode.upper) \n>>> proc([u'hi', u'everyone', u'im', u'pythonscrapy']) \n[u'HI, u'IM', u'PYTHONSCRAPY'] "
},
{
"code": null,
"e": 16002,
"s": 15920,
"text": "This class queries the value using the provided json path and returns the output."
},
{
"code": null,
"e": 16016,
"s": 16002,
"text": "For example −"
},
{
"code": null,
"e": 16220,
"s": 16016,
"text": ">>> from scrapy.loader.processors import SelectJmes, Compose, MapCompose\n>>> proc = SelectJmes(\"hello\")\n>>> proc({'hello': 'scrapy'})\n'scrapy'\n>>> proc({'hello': {'scrapy': 'world'}})\n{'scrapy': 'world'}"
},
{
"code": null,
"e": 16287,
"s": 16220,
"text": "Following is the code, which queries the value by importing json −"
},
{
"code": null,
"e": 16575,
"s": 16287,
"text": ">>> import json\n>>> proc_single_json_str = Compose(json.loads, SelectJmes(\"hello\"))\n>>> proc_single_json_str('{\"hello\": \"scrapy\"}')\nu'scrapy'\n>>> proc_json_list = Compose(json.loads, MapCompose(SelectJmes('hello')))\n>>> proc_json_list('[{\"hello\":\"scrapy\"}, {\"world\":\"env\"}]')\n[u'scrapy']"
},
{
"code": null,
"e": 16610,
"s": 16575,
"text": "\n 27 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 16625,
"s": 16610,
"text": " Attreya Bhatt"
},
{
"code": null,
"e": 16632,
"s": 16625,
"text": " Print"
},
{
"code": null,
"e": 16643,
"s": 16632,
"text": " Add Notes"
}
] |
How to add a new list element under a <ul> using jQuery?
|
To add a new list element under a ul element, use the jQuery append() method
Set input type text initially
Value: <input type="text" name="task" id="input">
Now on the click of a button, add a new list element using the val() and append() methods in jQuery:
$('button').click(function() {
var mylist = $('#input').val();
$('#list').append('<li>'+mylist+'</li>');
return false;
});
You can try to run the following code to learn how to add a new list element using jQuery:<./p>
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function() {
var mylist = $('#input').val();
$('#list').append('<li>'+mylist+'</li>');
return false;
});
});
</script>
</head>
<body>
<form>
Value: <input type="text" name="task" id="input">
<button>Submit</button>
<br>
<p>Add a value above and click Submit to add a new list.</p>
<ul id="list">
</ul>
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To add a new list element under a ul element, use the jQuery append() method"
},
{
"code": null,
"e": 1169,
"s": 1139,
"text": "Set input type text initially"
},
{
"code": null,
"e": 1219,
"s": 1169,
"text": "Value: <input type=\"text\" name=\"task\" id=\"input\">"
},
{
"code": null,
"e": 1320,
"s": 1219,
"text": "Now on the click of a button, add a new list element using the val() and append() methods in jQuery:"
},
{
"code": null,
"e": 1452,
"s": 1320,
"text": "$('button').click(function() {\n var mylist = $('#input').val();\n $('#list').append('<li>'+mylist+'</li>');\n return false;\n});"
},
{
"code": null,
"e": 1548,
"s": 1452,
"text": "You can try to run the following code to learn how to add a new list element using jQuery:<./p>"
},
{
"code": null,
"e": 1559,
"s": 1548,
"text": " Live Demo"
},
{
"code": null,
"e": 2191,
"s": 1559,
"text": "<!DOCTYPE html>\n<html>\n<head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $('button').click(function() {\n var mylist = $('#input').val();\n $('#list').append('<li>'+mylist+'</li>');\n return false;\n });\n });\n </script>\n</head>\n<body>\n <form>\n Value: <input type=\"text\" name=\"task\" id=\"input\">\n <button>Submit</button>\n <br>\n\n <p>Add a value above and click Submit to add a new list.</p>\n <ul id=\"list\">\n </ul>\n </form>\n</body>\n</html>"
}
] |
How to remove an element from a doubly-nested array in a MongoDB document?
|
To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator.
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.removeElementFromDoublyNestedArrayDemo.insertOne(
... {
... "_id" : "1",
... "UserName" : "Larry",
... "UserDetails" : [
... {
... "UserCountryName" : "US",
... "UserLocation" : [
... {
... "UserCityName" : "New York"
... },
... {
... "UserZipCode" : "10001"
... }
... ]
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : "1" }
> db.removeElementFromDoublyNestedArrayDemo.insertOne(
... {
... "_id" : "2",
... "UserName" : "Mike",
... "UserDetails" : [
... {
... "UserCountryName" : "UK",
... "UserLocation" : [
... {
... "UserCityName" : "Bangor"
... },
... {
... "UserZipCode" : "20010"
... }
... ]
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : "2" }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.removeElementFromDoublyNestedArrayDemo.find().pretty();
The following is the output −
{
"_id" : "1",
"UserName" : "Larry",
"UserDetails" : [
{
"UserCountryName" : "US",
"UserLocation" : [
{
"UserCityName" : "New York"
},
{
"UserZipCode" : "10001"
}
]
}
]
}
{
"_id" : "2",
"UserName" : "Mike",
"UserDetails" : [
{
"UserCountryName" : "UK",
"UserLocation" : [
{
"UserCityName" : "Bangor"
},
{
"UserZipCode" : "20010"
}
]
}
]
}
Here is the query to remove an element from a doubly-nested array in MongoDB document −
> db.removeElementFromDoublyNestedArrayDemo.update(
... { _id : "2" },
... {$pull : {"UserDetails.0.UserLocation" : {"UserZipCode":"20010"}}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Lets us check the documents from a collection with the help of find(). The query is as follows −
> db.removeElementFromDoublyNestedArrayDemo.find().pretty();
The following is the output −
{
"_id" : "1",
"UserName" : "Larry",
"UserDetails" : [
{
"UserCountryName" : "US",
"UserLocation" : [
{
"UserCityName" : "New York"
},
{
"UserZipCode" : "10001"
}
]
}
]
}
{
"_id" : "2",
"UserName" : "Mike",
"UserDetails" : [
{
"UserCountryName" : "UK",
"UserLocation" : [
{
"UserCityName" : "Bangor"
}
]
}
]
}
Now field "UserZipCode": "20010" has been removed from a doubly-nested array.
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator."
},
{
"code": null,
"e": 1297,
"s": 1159,
"text": "To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 2348,
"s": 1297,
"text": "> db.removeElementFromDoublyNestedArrayDemo.insertOne(\n ... {\n ... \"_id\" : \"1\",\n ... \"UserName\" : \"Larry\",\n ... \"UserDetails\" : [\n ... {\n ... \"UserCountryName\" : \"US\",\n ... \"UserLocation\" : [\n ... {\n ... \"UserCityName\" : \"New York\"\n ... },\n ... {\n ... \"UserZipCode\" : \"10001\"\n ... }\n ... ]\n ... }\n ... ]\n ... }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : \"1\" }\n> db.removeElementFromDoublyNestedArrayDemo.insertOne(\n ... {\n ... \"_id\" : \"2\",\n ... \"UserName\" : \"Mike\",\n ... \"UserDetails\" : [\n ... {\n ... \"UserCountryName\" : \"UK\",\n ... \"UserLocation\" : [\n ... {\n ... \"UserCityName\" : \"Bangor\"\n ... },\n ... {\n ... \"UserZipCode\" : \"20010\"\n ... }\n ... ]\n ... }\n ... ]\n ... }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : \"2\" }"
},
{
"code": null,
"e": 2446,
"s": 2348,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2507,
"s": 2446,
"text": "> db.removeElementFromDoublyNestedArrayDemo.find().pretty();"
},
{
"code": null,
"e": 2537,
"s": 2507,
"text": "The following is the output −"
},
{
"code": null,
"e": 3134,
"s": 2537,
"text": "{\n \"_id\" : \"1\",\n \"UserName\" : \"Larry\",\n \"UserDetails\" : [\n {\n \"UserCountryName\" : \"US\",\n \"UserLocation\" : [\n {\n \"UserCityName\" : \"New York\"\n },\n {\n \"UserZipCode\" : \"10001\"\n }\n ]\n }\n ]\n}\n{\n \"_id\" : \"2\",\n \"UserName\" : \"Mike\",\n \"UserDetails\" : [\n {\n \"UserCountryName\" : \"UK\",\n \"UserLocation\" : [\n {\n \"UserCityName\" : \"Bangor\"\n },\n {\n \"UserZipCode\" : \"20010\"\n }\n ]\n }\n ]\n}"
},
{
"code": null,
"e": 3222,
"s": 3134,
"text": "Here is the query to remove an element from a doubly-nested array in MongoDB document −"
},
{
"code": null,
"e": 3443,
"s": 3222,
"text": "> db.removeElementFromDoublyNestedArrayDemo.update(\n ... { _id : \"2\" },\n ... {$pull : {\"UserDetails.0.UserLocation\" : {\"UserZipCode\":\"20010\"}}}\n... );\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 3540,
"s": 3443,
"text": "Lets us check the documents from a collection with the help of find(). The query is as follows −"
},
{
"code": null,
"e": 3601,
"s": 3540,
"text": "> db.removeElementFromDoublyNestedArrayDemo.find().pretty();"
},
{
"code": null,
"e": 3631,
"s": 3601,
"text": "The following is the output −"
},
{
"code": null,
"e": 4160,
"s": 3631,
"text": "{\n \"_id\" : \"1\",\n \"UserName\" : \"Larry\",\n \"UserDetails\" : [\n {\n \"UserCountryName\" : \"US\",\n \"UserLocation\" : [\n {\n \"UserCityName\" : \"New York\"\n },\n {\n \"UserZipCode\" : \"10001\"\n }\n ]\n }\n ]\n}\n{\n \"_id\" : \"2\",\n \"UserName\" : \"Mike\",\n \"UserDetails\" : [\n {\n \"UserCountryName\" : \"UK\",\n \"UserLocation\" : [\n {\n \"UserCityName\" : \"Bangor\"\n }\n ]\n }\n ]\n}"
},
{
"code": null,
"e": 4238,
"s": 4160,
"text": "Now field \"UserZipCode\": \"20010\" has been removed from a doubly-nested array."
}
] |
Different ways of writing functions in JavaScript - GeeksforGeeks
|
09 Jul, 2021
What is a Function ?
A Function is a block of code that is designed to perform a task and executed when it is been called or invoked.
There are 3 ways of writing a function in JavaScript:
Function Declaration
Function Expression
Arrow Function
1. Function Declaration: Function Declaration is the traditional way to define a function. It is somehow similar to the way we define a function in other programming languages. We start declaring using the keyword “function”. Then we write the function name and then parameters.
Below is the example that illustrate the use of Function Declaration.
Javascript
// Function declarationfunction add(a, b) { console.log(a + b);} // Calling a functionadd(2, 3);
After defining a function, we call it whenever the function is required.
Output:
5
2. Function Expression: Function Expression is another way to define a function in JavaScript. Here we define a function using a variable and store the returned value in that variable.
Below is the example that illustrate the use of Function Expression.
Javascript
// Function Expressionconst add = function(a, b) { console.log(a+b);} // Calling functionadd(2, 3);
Here, the whole function is an expression and the returned value is stored in the variable. We use the variable name to call the function.
Output:
5
3. Arrow Functions: Arrow functions are been introduced in the ES6 version of JavaScript. It is used to shorten the code. Here we do not use the “function” keyword and use the arrow symbol.
Below is the example that illustrate the use of Arrow Function.
Example:
Javascript
// Single line of codelet add = (a, b) => a + b; console.log(add(3, 2));
This shortens the code to a single line compared to other approaches. In a single line of code, the function returns implicitly.
Output:
5
Note: When there is a need to include multiple lines of code we use brackets. Also, when there are multiple lines of code in the bracket we should write return explicitly to return the value from the function.
Example:
Javascript
// Multiple line of codeconst great = (a, b) => { if (a > b) return "a is greater"; else return "b is greater";} console.log(great(3,5));
Output:
b is greater
gulshankumarar231
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 24930,
"s": 24909,
"text": "What is a Function ?"
},
{
"code": null,
"e": 25043,
"s": 24930,
"text": "A Function is a block of code that is designed to perform a task and executed when it is been called or invoked."
},
{
"code": null,
"e": 25097,
"s": 25043,
"text": "There are 3 ways of writing a function in JavaScript:"
},
{
"code": null,
"e": 25118,
"s": 25097,
"text": "Function Declaration"
},
{
"code": null,
"e": 25138,
"s": 25118,
"text": "Function Expression"
},
{
"code": null,
"e": 25153,
"s": 25138,
"text": "Arrow Function"
},
{
"code": null,
"e": 25432,
"s": 25153,
"text": "1. Function Declaration: Function Declaration is the traditional way to define a function. It is somehow similar to the way we define a function in other programming languages. We start declaring using the keyword “function”. Then we write the function name and then parameters."
},
{
"code": null,
"e": 25502,
"s": 25432,
"text": "Below is the example that illustrate the use of Function Declaration."
},
{
"code": null,
"e": 25513,
"s": 25502,
"text": "Javascript"
},
{
"code": "// Function declarationfunction add(a, b) { console.log(a + b);} // Calling a functionadd(2, 3);",
"e": 25621,
"s": 25513,
"text": null
},
{
"code": null,
"e": 25694,
"s": 25621,
"text": "After defining a function, we call it whenever the function is required."
},
{
"code": null,
"e": 25702,
"s": 25694,
"text": "Output:"
},
{
"code": null,
"e": 25704,
"s": 25702,
"text": "5"
},
{
"code": null,
"e": 25889,
"s": 25704,
"text": "2. Function Expression: Function Expression is another way to define a function in JavaScript. Here we define a function using a variable and store the returned value in that variable."
},
{
"code": null,
"e": 25958,
"s": 25889,
"text": "Below is the example that illustrate the use of Function Expression."
},
{
"code": null,
"e": 25969,
"s": 25958,
"text": "Javascript"
},
{
"code": "// Function Expressionconst add = function(a, b) { console.log(a+b);} // Calling functionadd(2, 3);",
"e": 26072,
"s": 25969,
"text": null
},
{
"code": null,
"e": 26214,
"s": 26075,
"text": "Here, the whole function is an expression and the returned value is stored in the variable. We use the variable name to call the function."
},
{
"code": null,
"e": 26224,
"s": 26216,
"text": "Output:"
},
{
"code": null,
"e": 26228,
"s": 26226,
"text": "5"
},
{
"code": null,
"e": 26420,
"s": 26230,
"text": "3. Arrow Functions: Arrow functions are been introduced in the ES6 version of JavaScript. It is used to shorten the code. Here we do not use the “function” keyword and use the arrow symbol."
},
{
"code": null,
"e": 26486,
"s": 26422,
"text": "Below is the example that illustrate the use of Arrow Function."
},
{
"code": null,
"e": 26497,
"s": 26488,
"text": "Example:"
},
{
"code": null,
"e": 26510,
"s": 26499,
"text": "Javascript"
},
{
"code": "// Single line of codelet add = (a, b) => a + b; console.log(add(3, 2));",
"e": 26583,
"s": 26510,
"text": null
},
{
"code": null,
"e": 26712,
"s": 26583,
"text": "This shortens the code to a single line compared to other approaches. In a single line of code, the function returns implicitly."
},
{
"code": null,
"e": 26720,
"s": 26712,
"text": "Output:"
},
{
"code": null,
"e": 26722,
"s": 26720,
"text": "5"
},
{
"code": null,
"e": 26932,
"s": 26722,
"text": "Note: When there is a need to include multiple lines of code we use brackets. Also, when there are multiple lines of code in the bracket we should write return explicitly to return the value from the function."
},
{
"code": null,
"e": 26941,
"s": 26932,
"text": "Example:"
},
{
"code": null,
"e": 26952,
"s": 26941,
"text": "Javascript"
},
{
"code": "// Multiple line of codeconst great = (a, b) => { if (a > b) return \"a is greater\"; else return \"b is greater\";} console.log(great(3,5));",
"e": 27110,
"s": 26952,
"text": null
},
{
"code": null,
"e": 27118,
"s": 27110,
"text": "Output:"
},
{
"code": null,
"e": 27131,
"s": 27118,
"text": "b is greater"
},
{
"code": null,
"e": 27149,
"s": 27131,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 27170,
"s": 27149,
"text": "javascript-functions"
},
{
"code": null,
"e": 27181,
"s": 27170,
"text": "JavaScript"
},
{
"code": null,
"e": 27198,
"s": 27181,
"text": "Web Technologies"
},
{
"code": null,
"e": 27296,
"s": 27198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27305,
"s": 27296,
"text": "Comments"
},
{
"code": null,
"e": 27318,
"s": 27305,
"text": "Old Comments"
},
{
"code": null,
"e": 27379,
"s": 27318,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27420,
"s": 27379,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27474,
"s": 27420,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27514,
"s": 27474,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27576,
"s": 27514,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27632,
"s": 27576,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27665,
"s": 27632,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27727,
"s": 27665,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27770,
"s": 27727,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Rexx - Logical Operators
|
Logical Operators are used to evaluate Boolean expressions. Following are the logical operators available in Rexx.
The following program shows how the various operators can be used.
/* Main program*/
say 1 & 0
say 1 | 0
say 1 && 0
say \1
The output of the above program will be −
0
1
1
0
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2454,
"s": 2339,
"text": "Logical Operators are used to evaluate Boolean expressions. Following are the logical operators available in Rexx."
},
{
"code": null,
"e": 2521,
"s": 2454,
"text": "The following program shows how the various operators can be used."
},
{
"code": null,
"e": 2582,
"s": 2521,
"text": "/* Main program*/ \nsay 1 & 0 \nsay 1 | 0 \nsay 1 && 0 \nsay \\1 "
},
{
"code": null,
"e": 2624,
"s": 2582,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 2633,
"s": 2624,
"text": "0\n1\n1\n0\n"
},
{
"code": null,
"e": 2640,
"s": 2633,
"text": " Print"
},
{
"code": null,
"e": 2651,
"s": 2640,
"text": " Add Notes"
}
] |
Ruby on Rails - Directory Structure
|
When you use the Rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don't have to provide any input.
Here is a top-level view of a directory tree created by the helper script at the time of application creation. Except for minor changes between releases, every Rails project will have the same structure, with the same naming conventions. This consistency gives you a tremendous advantage; you can quickly move between Rails projects without relearning the project's organization.
To understand this directory structure, let's use the demo application created in the Installation chapter. It can be created using a simple helper command rails demo.
Now, go into the demo application root directory as follows −
tp> cd demo
demo> dir
You will find a directory structure in Windows as follows −
Now let's explain the purpose of each directory
app − It organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).
app − It organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).
app/controllers − The controllers subdirectory is where Rails looks to find the controller classes. A controller handles a web request from the user.
app/controllers − The controllers subdirectory is where Rails looks to find the controller classes. A controller handles a web request from the user.
app/helpers − The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.
app/helpers − The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.
app/models − The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!
app/models − The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!
app/view − The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.
app/view − The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.
app/view/layouts − Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout:default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout.
app/view/layouts − Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout:default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout.
components − This directory holds components, tiny self-contained applications that bundle model, view, and controller.
components − This directory holds components, tiny self-contained applications that bundle model, view, and controller.
config − This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory.
config − This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory.
db − Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory.
db − Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory.
doc − Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all the RubyDoc-generated Rails and application documentation.
doc − Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all the RubyDoc-generated Rails and application documentation.
lib − You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries).
lib − You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries).
log − Error logs go here. Rails creates scripts that help you manage various error logs. You'll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log).
log − Error logs go here. Rails creates scripts that help you manage various error logs. You'll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log).
public − Like the public directory for a web server, this directory has web files that don't change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public).
public − Like the public directory for a web server, this directory has web files that don't change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public).
script − This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server).
script − This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server).
test − The tests you write and those that Rails creates for you, all goes here. You'll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional).
test − The tests you write and those that Rails creates for you, all goes here. You'll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional).
tmp − Rails uses this directory to hold temporary files for intermediate processing.
tmp − Rails uses this directory to hold temporary files for intermediate processing.
vendor − Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here.
vendor − Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here.
Apart from these directories, there will be two files available in demo directory.
README − This file contains a basic detail about Rail Application and description of the directory structure explained above.
README − This file contains a basic detail about Rail Application and description of the directory structure explained above.
Rakefile − This file is similar to Unix Makefile, which helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with the Ruby installation.
Rakefile − This file is similar to Unix Makefile, which helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with the Ruby installation.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2336,
"s": 2103,
"text": "When you use the Rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don't have to provide any input."
},
{
"code": null,
"e": 2716,
"s": 2336,
"text": "Here is a top-level view of a directory tree created by the helper script at the time of application creation. Except for minor changes between releases, every Rails project will have the same structure, with the same naming conventions. This consistency gives you a tremendous advantage; you can quickly move between Rails projects without relearning the project's organization."
},
{
"code": null,
"e": 2884,
"s": 2716,
"text": "To understand this directory structure, let's use the demo application created in the Installation chapter. It can be created using a simple helper command rails demo."
},
{
"code": null,
"e": 2946,
"s": 2884,
"text": "Now, go into the demo application root directory as follows −"
},
{
"code": null,
"e": 2969,
"s": 2946,
"text": "tp> cd demo\ndemo> dir\n"
},
{
"code": null,
"e": 3029,
"s": 2969,
"text": "You will find a directory structure in Windows as follows −"
},
{
"code": null,
"e": 3077,
"s": 3029,
"text": "Now let's explain the purpose of each directory"
},
{
"code": null,
"e": 3256,
"s": 3077,
"text": "app − It organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models)."
},
{
"code": null,
"e": 3435,
"s": 3256,
"text": "app − It organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models)."
},
{
"code": null,
"e": 3585,
"s": 3435,
"text": "app/controllers − The controllers subdirectory is where Rails looks to find the controller classes. A controller handles a web request from the user."
},
{
"code": null,
"e": 3735,
"s": 3585,
"text": "app/controllers − The controllers subdirectory is where Rails looks to find the controller classes. A controller handles a web request from the user."
},
{
"code": null,
"e": 3944,
"s": 3735,
"text": "app/helpers − The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered."
},
{
"code": null,
"e": 4153,
"s": 3944,
"text": "app/helpers − The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered."
},
{
"code": null,
"e": 4410,
"s": 4153,
"text": "app/models − The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!"
},
{
"code": null,
"e": 4667,
"s": 4410,
"text": "app/models − The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!"
},
{
"code": null,
"e": 4823,
"s": 4667,
"text": "app/view − The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser."
},
{
"code": null,
"e": 4979,
"s": 4823,
"text": "app/view − The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser."
},
{
"code": null,
"e": 5308,
"s": 4979,
"text": "app/view/layouts − Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout:default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout."
},
{
"code": null,
"e": 5637,
"s": 5308,
"text": "app/view/layouts − Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout:default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout."
},
{
"code": null,
"e": 5757,
"s": 5637,
"text": "components − This directory holds components, tiny self-contained applications that bundle model, view, and controller."
},
{
"code": null,
"e": 5877,
"s": 5757,
"text": "components − This directory holds components, tiny self-contained applications that bundle model, view, and controller."
},
{
"code": null,
"e": 6291,
"s": 5877,
"text": "config − This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory."
},
{
"code": null,
"e": 6705,
"s": 6291,
"text": "config − This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory."
},
{
"code": null,
"e": 6898,
"s": 6705,
"text": "db − Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory."
},
{
"code": null,
"e": 7091,
"s": 6898,
"text": "db − Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory."
},
{
"code": null,
"e": 7337,
"s": 7091,
"text": "doc − Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all the RubyDoc-generated Rails and application documentation."
},
{
"code": null,
"e": 7583,
"s": 7337,
"text": "doc − Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all the RubyDoc-generated Rails and application documentation."
},
{
"code": null,
"e": 7684,
"s": 7583,
"text": "lib − You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries)."
},
{
"code": null,
"e": 7785,
"s": 7684,
"text": "lib − You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries)."
},
{
"code": null,
"e": 8004,
"s": 7785,
"text": "log − Error logs go here. Rails creates scripts that help you manage various error logs. You'll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log)."
},
{
"code": null,
"e": 8223,
"s": 8004,
"text": "log − Error logs go here. Rails creates scripts that help you manage various error logs. You'll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log)."
},
{
"code": null,
"e": 8456,
"s": 8223,
"text": "public − Like the public directory for a web server, this directory has web files that don't change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public)."
},
{
"code": null,
"e": 8689,
"s": 8456,
"text": "public − Like the public directory for a web server, this directory has web files that don't change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public)."
},
{
"code": null,
"e": 8889,
"s": 8689,
"text": "script − This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server)."
},
{
"code": null,
"e": 9089,
"s": 8889,
"text": "script − This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server)."
},
{
"code": null,
"e": 9289,
"s": 9089,
"text": "test − The tests you write and those that Rails creates for you, all goes here. You'll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional)."
},
{
"code": null,
"e": 9489,
"s": 9289,
"text": "test − The tests you write and those that Rails creates for you, all goes here. You'll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional)."
},
{
"code": null,
"e": 9574,
"s": 9489,
"text": "tmp − Rails uses this directory to hold temporary files for intermediate processing."
},
{
"code": null,
"e": 9659,
"s": 9574,
"text": "tmp − Rails uses this directory to hold temporary files for intermediate processing."
},
{
"code": null,
"e": 9806,
"s": 9659,
"text": "vendor − Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here."
},
{
"code": null,
"e": 9953,
"s": 9806,
"text": "vendor − Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here."
},
{
"code": null,
"e": 10036,
"s": 9953,
"text": "Apart from these directories, there will be two files available in demo directory."
},
{
"code": null,
"e": 10162,
"s": 10036,
"text": "README − This file contains a basic detail about Rail Application and description of the directory structure explained above."
},
{
"code": null,
"e": 10288,
"s": 10162,
"text": "README − This file contains a basic detail about Rail Application and description of the directory structure explained above."
},
{
"code": null,
"e": 10480,
"s": 10288,
"text": "Rakefile − This file is similar to Unix Makefile, which helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with the Ruby installation."
},
{
"code": null,
"e": 10672,
"s": 10480,
"text": "Rakefile − This file is similar to Unix Makefile, which helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with the Ruby installation."
},
{
"code": null,
"e": 10679,
"s": 10672,
"text": " Print"
},
{
"code": null,
"e": 10690,
"s": 10679,
"text": " Add Notes"
}
] |
Tryit Editor v3.6 - Show React
|
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const [inputValue, setInputValue] = useState("");
const count = useRef(0);
useEffect(() => {
count.current = count.current + 1;
});
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h1>Render Count: {count.current}</h1>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
/*
Try typing in the input field, and you will
see the application render conut increase.
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
|
[
{
"code": null,
"e": 648,
"s": 0,
"text": "\nimport { useState, useEffect, useRef } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction App() {\n const [inputValue, setInputValue] = useState(\"\");\n const count = useRef(0);\n\n useEffect(() => {\n count.current = count.current + 1;\n });\n\n return (\n <>\n <input\n type=\"text\"\n value={inputValue}\n onChange={(e) => setInputValue(e.target.value)}\n />\n <h1>Render Count: {count.current}</h1>\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<App />);\n\n/*\nTry typing in the input field, and you will\nsee the application render conut increase.\n*/\n\n"
}
] |
Iterating C# StringBuilder in a foreach loop
|
Firstly, set a string array and StringBuilder −
// string array
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();
Now, use foreach loop to iterate −
foreach (string item in myStr) {
str.Append(item).AppendLine();
}
The following is the complete code −
Live Demo
using System;
using System.Text;
public class Demo {
public static void Main() {
// string array
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();
// foreach loop to append elements
foreach (string item in myStr) {
str.Append(item).AppendLine();
}
Console.WriteLine(str.ToString());
Console.ReadLine();
}
}
We will print now...
One
Two
Three
Four
|
[
{
"code": null,
"e": 1110,
"s": 1062,
"text": "Firstly, set a string array and StringBuilder −"
},
{
"code": null,
"e": 1254,
"s": 1110,
"text": "// string array\nstring[] myStr = { \"One\", \"Two\", \"Three\", \"Four\" };\nStringBuilder str = new StringBuilder(\"We will print now...\").AppendLine();"
},
{
"code": null,
"e": 1289,
"s": 1254,
"text": "Now, use foreach loop to iterate −"
},
{
"code": null,
"e": 1358,
"s": 1289,
"text": "foreach (string item in myStr) {\n str.Append(item).AppendLine();\n}"
},
{
"code": null,
"e": 1395,
"s": 1358,
"text": "The following is the complete code −"
},
{
"code": null,
"e": 1406,
"s": 1395,
"text": " Live Demo"
},
{
"code": null,
"e": 1856,
"s": 1406,
"text": "using System;\nusing System.Text;\n\npublic class Demo {\n public static void Main() {\n // string array\n string[] myStr = { \"One\", \"Two\", \"Three\", \"Four\" };\n StringBuilder str = new StringBuilder(\"We will print now...\").AppendLine();\n\n // foreach loop to append elements\n foreach (string item in myStr) {\n str.Append(item).AppendLine();\n }\n Console.WriteLine(str.ToString());\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 1896,
"s": 1856,
"text": "We will print now...\nOne\nTwo\nThree\nFour"
}
] |
jQuery Effect - Highlight Effect
|
The Highlight effect can be used with effect() method. This highlights the element's background with a specific color, default is yellow.
Here is the simple syntax to use this effect −
selector.effect( "highlight", {arguments}, speed );
Here is the description of all the arguments −
color − Highlight color. Default is "#ffff99".
color − Highlight color. Default is "#ffff99".
mode − The mode of the effect. Can be "show", "hide". Default is "show".
mode − The mode of the effect. Can be "show", "hide". Default is "show".
Following is a simple example a simple showing the usage of this effect −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#button").click(function(){
$(".target").effect( "highlight", {color:"#669966"}, 3000 );
});
});
</script>
<style>
p {background-color:#bca; width:200px; border:1px solid green;}
div{ width:100px; height:100px; background:red;}
</style>
</head>
<body>
<p>Click the button</p>
<button id = "button"> Highlight </button>
<div class = "target">
</div>
</body>
</html>
This will produce following result −
Click the button
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2460,
"s": 2322,
"text": "The Highlight effect can be used with effect() method. This highlights the element's background with a specific color, default is yellow."
},
{
"code": null,
"e": 2507,
"s": 2460,
"text": "Here is the simple syntax to use this effect −"
},
{
"code": null,
"e": 2560,
"s": 2507,
"text": "selector.effect( \"highlight\", {arguments}, speed );\n"
},
{
"code": null,
"e": 2607,
"s": 2560,
"text": "Here is the description of all the arguments −"
},
{
"code": null,
"e": 2654,
"s": 2607,
"text": "color − Highlight color. Default is \"#ffff99\"."
},
{
"code": null,
"e": 2701,
"s": 2654,
"text": "color − Highlight color. Default is \"#ffff99\"."
},
{
"code": null,
"e": 2774,
"s": 2701,
"text": "mode − The mode of the effect. Can be \"show\", \"hide\". Default is \"show\"."
},
{
"code": null,
"e": 2847,
"s": 2774,
"text": "mode − The mode of the effect. Can be \"show\", \"hide\". Default is \"show\"."
},
{
"code": null,
"e": 2921,
"s": 2847,
"text": "Following is a simple example a simple showing the usage of this effect −"
},
{
"code": null,
"e": 3872,
"s": 2921,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n \n $(document).ready(function() {\n\n $(\"#button\").click(function(){\n $(\".target\").effect( \"highlight\", {color:\"#669966\"}, 3000 );\n });\n });\n\t\t\t\n </script>\n\t\t\n <style>\n p {background-color:#bca; width:200px; border:1px solid green;}\n div{ width:100px; height:100px; background:red;}\n </style>\n </head>\n\t\n <body>\n <p>Click the button</p>\n <button id = \"button\"> Highlight </button>\n\n <div class = \"target\">\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 3909,
"s": 3872,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3926,
"s": 3909,
"text": "Click the button"
},
{
"code": null,
"e": 3959,
"s": 3926,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3973,
"s": 3959,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4008,
"s": 3973,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4022,
"s": 4008,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4057,
"s": 4022,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4074,
"s": 4057,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4107,
"s": 4074,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4135,
"s": 4107,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4168,
"s": 4135,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4189,
"s": 4168,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4221,
"s": 4189,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4238,
"s": 4221,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4245,
"s": 4238,
"text": " Print"
},
{
"code": null,
"e": 4256,
"s": 4245,
"text": " Add Notes"
}
] |
C# Coding Standards - GeeksforGeeks
|
15 Dec, 2021
C# is a general-purpose, modern and object-oriented programming language pronounced as “C Sharp”. It was developed by Microsoft led by Anders Hejlsberg and his team within the .NET initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# is among the languages for Common Language Infrastructure. C# is a lot similar to Java syntactically and is easy for users who have knowledge of C, C++, or Java.
Below are some of the best practices which all the .Net Developers should follow:
1. Class and Method names should always be in Pascal Case
public class Employee
{
public Employee GetDetails()
{
//...
}
public double GetBonus()
{
//...
}
}
2. Method argument and Local variables should always be in Camel Case
public class Employee
{
public void PrintDetails(int employeeId, String firstName)
{
int totalSalary = 2000;
// ...
}
}
3. Avoid the use of underscore while naming identifiers
// Correct
public DateTime fromDate;
public String firstName;
// Avoid
public DateTime from_Date;
public String first_Name;
4. Avoid the use of System data types and prefer using the Predefined data types.
// Correct
int employeeId;
string employeeName;
bool isActive;
// Avoid
Int32 employeeId;
String employeeName;
Boolean isActive;
5. Always prefix an interface with letter I.
// Correct
public interface IEmployee
{
}
public interface IShape
{
}
public interface IAnimal
{
}
// Avoid
public interface Employee
{
}
public interface Shape
{
}
public interface Animal
{
}
6. For better code indentation and readability always align the curly braces vertically.
// Correct
class Employee
{
static void PrintDetails()
{
}
}
// Avoid
class Employee
{
static void PrintDetails()
{
}
}
7. Always use the using keyword when working with disposable types. It automatically disposes the object when program flow leaves the scope.
using(var conn = new SqlConnection(connectionString))
{
// use the connection and the stream
using (var dr = cmd.ExecuteReader())
{
//
}
}
8. Always declare the variables as close as possible to their use.
// Correct
String firstName = "Shubham";
Console.WriteLine(firstName);
//--------------------------
// Avoid
String firstName = "Shubham";
//--------------------------
//--------------------------
//--------------------------
Console.WriteLine(firstName);
9. Always declare the properties as private so as to achieve Encapsulation and ensure data hiding.
// Correct
private int employeeId { get; set; }
// Avoid
public int employeeId { get; set; }
10. Always separate the methods, different sections of program by one space.
// Correct
class Employee
{
private int employeeId { get; set; }
public void PrintDetails()
{
//------------
}
}
// Avoid
class Employee
{
private int employeeId { get; set; }
public void PrintDetails()
{
//------------
}
}
11. Constants should always be declared in UPPER_CASE.
// Correct
public const int MIN_AGE = 18;
public const int MAX_AGE = 60;
// Avoid
public const int Min_Age = 18;
public const int Max_Age = 60;
simranarora5sos
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
Difference between Ref and Out keywords in C#
Introduction to .NET Framework
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
C# | Delegates
Top 50 C# Interview Questions & Answers
Different ways to sort an array in descending order in C#
C# | Replace() Method
|
[
{
"code": null,
"e": 23932,
"s": 23904,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 24413,
"s": 23932,
"text": "C# is a general-purpose, modern and object-oriented programming language pronounced as “C Sharp”. It was developed by Microsoft led by Anders Hejlsberg and his team within the .NET initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# is among the languages for Common Language Infrastructure. C# is a lot similar to Java syntactically and is easy for users who have knowledge of C, C++, or Java. "
},
{
"code": null,
"e": 24496,
"s": 24413,
"text": "Below are some of the best practices which all the .Net Developers should follow: "
},
{
"code": null,
"e": 24555,
"s": 24496,
"text": "1. Class and Method names should always be in Pascal Case "
},
{
"code": null,
"e": 24695,
"s": 24555,
"text": "public class Employee\n{\n public Employee GetDetails()\n {\n //...\n }\n public double GetBonus()\n {\n //...\n }\n}"
},
{
"code": null,
"e": 24767,
"s": 24695,
"text": "2. Method argument and Local variables should always be in Camel Case "
},
{
"code": null,
"e": 24915,
"s": 24767,
"text": "public class Employee\n{\n public void PrintDetails(int employeeId, String firstName)\n {\n int totalSalary = 2000;\n // ...\n }\n}"
},
{
"code": null,
"e": 24973,
"s": 24915,
"text": "3. Avoid the use of underscore while naming identifiers "
},
{
"code": null,
"e": 25100,
"s": 24973,
"text": "// Correct\npublic DateTime fromDate;\npublic String firstName;\n \n\n// Avoid\npublic DateTime from_Date;\npublic String first_Name;"
},
{
"code": null,
"e": 25184,
"s": 25100,
"text": "4. Avoid the use of System data types and prefer using the Predefined data types. "
},
{
"code": null,
"e": 25316,
"s": 25184,
"text": "// Correct\nint employeeId;\nstring employeeName;\nbool isActive;\n \n\n// Avoid\nInt32 employeeId;\nString employeeName;\nBoolean isActive;"
},
{
"code": null,
"e": 25363,
"s": 25316,
"text": "5. Always prefix an interface with letter I. "
},
{
"code": null,
"e": 25557,
"s": 25363,
"text": "// Correct\npublic interface IEmployee\n{\n}\npublic interface IShape\n{\n}\npublic interface IAnimal\n{\n}\n\n// Avoid\npublic interface Employee\n{\n}\npublic interface Shape\n{\n}\npublic interface Animal\n{\n}"
},
{
"code": null,
"e": 25648,
"s": 25557,
"text": "6. For better code indentation and readability always align the curly braces vertically. "
},
{
"code": null,
"e": 25801,
"s": 25648,
"text": "// Correct\nclass Employee\n{\n static void PrintDetails()\n {\n }\n}\n \n\n// Avoid\nclass Employee\n {\n static void PrintDetails()\n {\n }\n}"
},
{
"code": null,
"e": 25944,
"s": 25801,
"text": "7. Always use the using keyword when working with disposable types. It automatically disposes the object when program flow leaves the scope. "
},
{
"code": null,
"e": 26104,
"s": 25944,
"text": "using(var conn = new SqlConnection(connectionString))\n{\n // use the connection and the stream\n using (var dr = cmd.ExecuteReader())\n {\n //\n }\n}"
},
{
"code": null,
"e": 26173,
"s": 26104,
"text": "8. Always declare the variables as close as possible to their use. "
},
{
"code": null,
"e": 26432,
"s": 26173,
"text": "// Correct\nString firstName = \"Shubham\";\nConsole.WriteLine(firstName);\n//--------------------------\n \n\n// Avoid\nString firstName = \"Shubham\";\n//--------------------------\n//--------------------------\n//--------------------------\nConsole.WriteLine(firstName);"
},
{
"code": null,
"e": 26533,
"s": 26432,
"text": "9. Always declare the properties as private so as to achieve Encapsulation and ensure data hiding. "
},
{
"code": null,
"e": 26627,
"s": 26533,
"text": "// Correct\nprivate int employeeId { get; set; }\n\n// Avoid\npublic int employeeId { get; set; }"
},
{
"code": null,
"e": 26706,
"s": 26627,
"text": "10. Always separate the methods, different sections of program by one space. "
},
{
"code": null,
"e": 26937,
"s": 26706,
"text": "// Correct\nclass Employee\n{\nprivate int employeeId { get; set; }\n\npublic void PrintDetails()\n{\n//------------\n}\n}\n\n// Avoid\nclass Employee\n{\n\nprivate int employeeId { get; set; }\n\n\n\npublic void PrintDetails()\n{\n//------------\n}\n\n}"
},
{
"code": null,
"e": 26994,
"s": 26937,
"text": "11. Constants should always be declared in UPPER_CASE. "
},
{
"code": null,
"e": 27139,
"s": 26994,
"text": "// Correct\npublic const int MIN_AGE = 18;\npublic const int MAX_AGE = 60;\n\n// Avoid\npublic const int Min_Age = 18;\npublic const int Max_Age = 60;"
},
{
"code": null,
"e": 27157,
"s": 27141,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27171,
"s": 27157,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 27174,
"s": 27171,
"text": "C#"
},
{
"code": null,
"e": 27272,
"s": 27174,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27281,
"s": 27272,
"text": "Comments"
},
{
"code": null,
"e": 27294,
"s": 27281,
"text": "Old Comments"
},
{
"code": null,
"e": 27322,
"s": 27294,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27368,
"s": 27322,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27399,
"s": 27368,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27422,
"s": 27399,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27462,
"s": 27422,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27484,
"s": 27462,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27499,
"s": 27484,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27539,
"s": 27499,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27597,
"s": 27539,
"text": "Different ways to sort an array in descending order in C#"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.