title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to Find Shortest Dependency Path with spaCy and StanfordNLP | by Xu LIANG | Towards Data Science
|
Considering the documentation and dependency parsing accuracy, I recommend using spaCy than StanfordNLP.
The content is structured as follows.
What is Shortest Dependency Path (SDP)?
Find Shortest Dependency Path with spaCy
Find Shortest Dependency Path with StanfordNLP
Semantic dependency parsing had been frequently used to dissect sentence and to capture word semantic information close in context but far in sentence distance.
To extract the relationship between two entities, the most direct approach is to use SDP. The motivation of using SDP is based on the observation that the SDP between entities usually contains the necessary information to identify their relationship.[1]
Convulsions that occur after DTaP are caused by a fever.
In the above figure, words in square brackets are marked entities. The red dashed-line arrows indicate the SDP between two entities.
First, install the necessary libraries in the terminal. I add the version number for clearness.
pip install spacy==2.1.4python -m spacy download en_core_web_smpip install stanfordnlp==0.2.0pip install networkx==2.3
First, we print out all dependency labels follow the official tutorial.
import spacyimport networkx as nxnlp = spacy.load("en_core_web_sm")doc = nlp(u'Convulsions that occur after DTaP are caused by a fever.')for token in doc: print((token.head.text, token.text, token.dep_))# output: (head, current_token, dep_relation)('caused', 'Convulsions', 'nsubjpass')('occur', 'that', 'nsubj')('Convulsions', 'occur', 'relcl')('occur', 'after', 'prep')('caused', 'DTaP', 'nsubjpass')('caused', 'are', 'auxpass')('caused', 'caused', 'ROOT')('caused', 'by', 'agent')('fever', 'a', 'det')('by', 'fever', 'pobj')('caused', '.', 'punct')
We can plot the whole dependency tree by the convenient spaCy visualization tool.
The code below can give the SDP
import spacyimport networkx as nxnlp = spacy.load("en_core_web_sm")doc = nlp(u'Convulsions that occur after DTaP are caused by a fever.')print('sentence:'.format(doc))# Load spacy's dependency tree into a networkx graphedges = []for token in doc: for child in token.children: edges.append(('{0}'.format(token.lower_), '{0}'.format(child.lower_)))graph = nx.Graph(edges)# Get the length and pathentity1 = 'Convulsions'.lower()entity2 = 'fever'print(nx.shortest_path_length(graph, source=entity1, target=entity2))print(nx.shortest_path(graph, source=entity1, target=entity2))
The edges looks like below.
In [6]: edgesOut[6]:[('convulsions', 'occur'), ('occur', 'that'), ('occur', 'after'), ('caused', 'convulsions'), ('caused', 'dtap'), ('caused', 'are'), ('caused', 'by'), ('caused', '.'), ('by', 'fever'), ('fever', 'a')]
The output is below
3['convulsions', 'caused', 'by', 'fever']
This means the SDP length from ‘convulsions’ to ‘fever’ is 3.
If you don’t want to use networkx library, and only use the spaCy, you can check my another post, Find Lowest Common Ancestor Shortest Dependency Path with spaCy
First, we print out all dependency labels follow the official tutorial.
import stanfordnlpstanfordnlp.download('en')nlp = stanfordnlp.Pipeline()doc = nlp('Convulsions that occur after DTaP are caused by a fever.')doc.sentences[0].print_dependencies()# output: (current_token, head_index, dep_relation)('Convulsions', '0', 'root')('that', '3', 'nsubj')('occur', '1', 'acl:relcl')('after', '7', 'mark')('DTaP', '7', 'nsubj:pass')('are', '7', 'aux:pass')('caused', '3', 'advcl')('by', '10', 'case')('a', '10', 'det')('fever', '7', 'obl')
In order to follow the [(token, children), (token, children),...]format for networkx graph, we need to modify the code according to the source code.
import stanfordnlpstanfordnlp.download('en')nlp = stanfordnlp.Pipeline()doc = nlp('Convulsions that occur after DTaP are caused by a fever.')# Load stanfordnlp's dependency tree into a networkx graphedges = []for token in doc.sentences[0].dependencies: if token[0].text.lower() != 'root': edges.append((token[0].text.lower(), token[2].text))graph = nx.Graph(edges)# Get the length and pathentity1 = 'Convulsions'.lower()entity2 = 'fever'print(nx.shortest_path_length(graph, source=entity1, target=entity2))print(nx.shortest_path(graph, source=entity1, target=entity2))
The edges looks like below.
In [19]: edgesOut[19]:[('occur', 'that'), ('convulsions', 'occur'), ('caused', 'after'), ('caused', 'DTaP'), ('caused', 'are'), ('occur', 'caused'), ('fever', 'by'), ('fever', 'a'), ('caused', 'fever'), ('convulsions', '.')]
The output is below
3['convulsions', 'occur', 'caused', 'fever']
Even the SDP length calculated by StanfordNLP is the same with spaCy. But the words in the SDP between two entity should be 'caused', 'by'. So the dependency parsing accuracy of spaCy is better than StanfordNLP.
Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu
|
[
{
"code": null,
"e": 277,
"s": 172,
"text": "Considering the documentation and dependency parsing accuracy, I recommend using spaCy than StanfordNLP."
},
{
"code": null,
"e": 315,
"s": 277,
"text": "The content is structured as follows."
},
{
"code": null,
"e": 355,
"s": 315,
"text": "What is Shortest Dependency Path (SDP)?"
},
{
"code": null,
"e": 396,
"s": 355,
"text": "Find Shortest Dependency Path with spaCy"
},
{
"code": null,
"e": 443,
"s": 396,
"text": "Find Shortest Dependency Path with StanfordNLP"
},
{
"code": null,
"e": 604,
"s": 443,
"text": "Semantic dependency parsing had been frequently used to dissect sentence and to capture word semantic information close in context but far in sentence distance."
},
{
"code": null,
"e": 858,
"s": 604,
"text": "To extract the relationship between two entities, the most direct approach is to use SDP. The motivation of using SDP is based on the observation that the SDP between entities usually contains the necessary information to identify their relationship.[1]"
},
{
"code": null,
"e": 915,
"s": 858,
"text": "Convulsions that occur after DTaP are caused by a fever."
},
{
"code": null,
"e": 1048,
"s": 915,
"text": "In the above figure, words in square brackets are marked entities. The red dashed-line arrows indicate the SDP between two entities."
},
{
"code": null,
"e": 1144,
"s": 1048,
"text": "First, install the necessary libraries in the terminal. I add the version number for clearness."
},
{
"code": null,
"e": 1263,
"s": 1144,
"text": "pip install spacy==2.1.4python -m spacy download en_core_web_smpip install stanfordnlp==0.2.0pip install networkx==2.3"
},
{
"code": null,
"e": 1335,
"s": 1263,
"text": "First, we print out all dependency labels follow the official tutorial."
},
{
"code": null,
"e": 1890,
"s": 1335,
"text": "import spacyimport networkx as nxnlp = spacy.load(\"en_core_web_sm\")doc = nlp(u'Convulsions that occur after DTaP are caused by a fever.')for token in doc: print((token.head.text, token.text, token.dep_))# output: (head, current_token, dep_relation)('caused', 'Convulsions', 'nsubjpass')('occur', 'that', 'nsubj')('Convulsions', 'occur', 'relcl')('occur', 'after', 'prep')('caused', 'DTaP', 'nsubjpass')('caused', 'are', 'auxpass')('caused', 'caused', 'ROOT')('caused', 'by', 'agent')('fever', 'a', 'det')('by', 'fever', 'pobj')('caused', '.', 'punct')"
},
{
"code": null,
"e": 1972,
"s": 1890,
"text": "We can plot the whole dependency tree by the convenient spaCy visualization tool."
},
{
"code": null,
"e": 2004,
"s": 1972,
"text": "The code below can give the SDP"
},
{
"code": null,
"e": 2609,
"s": 2004,
"text": "import spacyimport networkx as nxnlp = spacy.load(\"en_core_web_sm\")doc = nlp(u'Convulsions that occur after DTaP are caused by a fever.')print('sentence:'.format(doc))# Load spacy's dependency tree into a networkx graphedges = []for token in doc: for child in token.children: edges.append(('{0}'.format(token.lower_), '{0}'.format(child.lower_)))graph = nx.Graph(edges)# Get the length and pathentity1 = 'Convulsions'.lower()entity2 = 'fever'print(nx.shortest_path_length(graph, source=entity1, target=entity2))print(nx.shortest_path(graph, source=entity1, target=entity2))"
},
{
"code": null,
"e": 2637,
"s": 2609,
"text": "The edges looks like below."
},
{
"code": null,
"e": 2857,
"s": 2637,
"text": "In [6]: edgesOut[6]:[('convulsions', 'occur'), ('occur', 'that'), ('occur', 'after'), ('caused', 'convulsions'), ('caused', 'dtap'), ('caused', 'are'), ('caused', 'by'), ('caused', '.'), ('by', 'fever'), ('fever', 'a')]"
},
{
"code": null,
"e": 2877,
"s": 2857,
"text": "The output is below"
},
{
"code": null,
"e": 2919,
"s": 2877,
"text": "3['convulsions', 'caused', 'by', 'fever']"
},
{
"code": null,
"e": 2981,
"s": 2919,
"text": "This means the SDP length from ‘convulsions’ to ‘fever’ is 3."
},
{
"code": null,
"e": 3143,
"s": 2981,
"text": "If you don’t want to use networkx library, and only use the spaCy, you can check my another post, Find Lowest Common Ancestor Shortest Dependency Path with spaCy"
},
{
"code": null,
"e": 3215,
"s": 3143,
"text": "First, we print out all dependency labels follow the official tutorial."
},
{
"code": null,
"e": 3678,
"s": 3215,
"text": "import stanfordnlpstanfordnlp.download('en')nlp = stanfordnlp.Pipeline()doc = nlp('Convulsions that occur after DTaP are caused by a fever.')doc.sentences[0].print_dependencies()# output: (current_token, head_index, dep_relation)('Convulsions', '0', 'root')('that', '3', 'nsubj')('occur', '1', 'acl:relcl')('after', '7', 'mark')('DTaP', '7', 'nsubj:pass')('are', '7', 'aux:pass')('caused', '3', 'advcl')('by', '10', 'case')('a', '10', 'det')('fever', '7', 'obl')"
},
{
"code": null,
"e": 3827,
"s": 3678,
"text": "In order to follow the [(token, children), (token, children),...]format for networkx graph, we need to modify the code according to the source code."
},
{
"code": null,
"e": 4406,
"s": 3827,
"text": "import stanfordnlpstanfordnlp.download('en')nlp = stanfordnlp.Pipeline()doc = nlp('Convulsions that occur after DTaP are caused by a fever.')# Load stanfordnlp's dependency tree into a networkx graphedges = []for token in doc.sentences[0].dependencies: if token[0].text.lower() != 'root': edges.append((token[0].text.lower(), token[2].text))graph = nx.Graph(edges)# Get the length and pathentity1 = 'Convulsions'.lower()entity2 = 'fever'print(nx.shortest_path_length(graph, source=entity1, target=entity2))print(nx.shortest_path(graph, source=entity1, target=entity2))"
},
{
"code": null,
"e": 4434,
"s": 4406,
"text": "The edges looks like below."
},
{
"code": null,
"e": 4659,
"s": 4434,
"text": "In [19]: edgesOut[19]:[('occur', 'that'), ('convulsions', 'occur'), ('caused', 'after'), ('caused', 'DTaP'), ('caused', 'are'), ('occur', 'caused'), ('fever', 'by'), ('fever', 'a'), ('caused', 'fever'), ('convulsions', '.')]"
},
{
"code": null,
"e": 4679,
"s": 4659,
"text": "The output is below"
},
{
"code": null,
"e": 4724,
"s": 4679,
"text": "3['convulsions', 'occur', 'caused', 'fever']"
},
{
"code": null,
"e": 4936,
"s": 4724,
"text": "Even the SDP length calculated by StanfordNLP is the same with spaCy. But the words in the SDP between two entity should be 'caused', 'by'. So the dependency parsing accuracy of spaCy is better than StanfordNLP."
}
] |
How to find the position of one or more values in a vector into another vector that contains same values in R?
|
Finding the position of one of more values that are common in two vectors can be easily done with the help of match function. The match function will match the values in first and second vector then return the index or position of these common values in second vector.
Live Demo
set.seed(145)
x1<-0:5
y1<-10:0
match(x1,y1)
[1] 11 10 9 8 7 6
Live Demo
x2<-sample(0:9,100,replace=TRUE)
x2
[1] 9 9 0 5 1 7 3 4 2 4 0 8 0 2 3 2 4 3 2 0 9 2 3 4 6 2 7 9 1 0 8 6 4 1 7 7 4
[38] 8 6 6 4 4 0 0 0 7 4 2 0 3 8 8 0 3 7 2 1 7 7 9 7 7 1 6 7 6 5 5 7 7 4 3 8 5
[75] 0 2 1 5 3 0 2 7 2 5 5 2 5 5 2 9 2 3 6 8 0 1 7 0 6 7
Live Demo
y2<-sample(6:9,100,replace=TRUE)
y2
[1] 8 7 7 7 8 7 6 6 9 6 6 7 7 9 9 8 6 9 7 7 7 6 6 6 8 9 6 7 6 7 6 7 7 9 6 9 8
[38] 7 8 6 6 6 8 6 8 7 7 6 6 6 9 9 6 9 7 9 6 9 7 8 9 7 9 9 6 7 8 8 8 7 6 7 8 8
[75] 9 9 6 9 6 8 6 8 9 7 8 7 8 9 8 7 8 8 7 9 8 7 6 6 9 6
match(x2,y2)
[1] 8 3 3 NA NA NA NA NA NA NA NA NA NA 1 NA 3 NA 3 NA NA NA 1 NA NA 1
[26] NA NA 2 NA 8 NA NA 8 NA NA 3 NA 8 2 NA NA NA NA NA 8 NA NA NA 8 1
[51] NA 1 NA NA NA NA NA NA NA NA 2 2 NA NA 8 8 1 NA 8 NA 8 1 8 2 NA
[76] NA NA NA NA NA NA NA 8 8 NA 1 8 NA NA 3 3 NA NA NA 3 NA NA 8 NA NA
Live Demo
x3<-sample(21:50,100,replace=TRUE)
x3
[1] 28 30 33 32 47 26 43 42 27 32 35 31 37 26 46 49 27 44 39 49 42 43 31 33 24
[26] 45 50 50 23 30 23 48 27 29 45 39 27 27 45 49 41 27 47 39 47 42 21 40 50 50
[51] 30 29 45 25 47 34 26 31 30 41 34 44 25 47 23 45 48 43 44 47 24 47 21 43 44
[76] 43 36 39 44 22 28 49 28 34 30 37 50 25 25 46 43 44 30 32 37 45 23 43 48 48
Live Demo
y3<-sample(10:50,100,replace=TRUE)
y3
[1] 29 14 49 34 45 13 15 44 35 36 37 41 37 38 37 41 37 39 29 33 31 39 35 28 12
[26] 32 21 14 42 45 13 38 18 33 33 24 48 17 47 24 19 10 39 33 41 39 49 27 28 27
[51] 31 20 31 18 17 45 49 17 11 14 45 18 21 42 50 41 50 22 33 15 36 20 44 10 39
[76] 23 21 41 15 16 20 48 47 40 16 48 23 33 47 43 13 23 38 11 33 41 45 21 18 29
match(x3,y3)
[1] 62 48 68 62 49 55 8 14 1 8 1 93 46 2 22 23 19 48 41 6 13 14 28 55 85
[26] 9 21 9 13 55 8 88 66 41 6 62 33 33 46 23 62 13 14 12 33 27 33 21 55 12
[51] 23 12 15 47 9 48 21 23 48 85 15 47 2 1 15 19 41 93 28 46 48 93 13 62 62
[76] 55 41 21 22 46 6 14 14 22 66 68 47 33 13 55 47 6 15 48 88 21 6 8 41 13
Live Demo
x4<-sample(501:999,100,replace=TRUE)
x4
[1] 593 568 672 827 854 927 961 854 867 743 812 631 656 543 633 914 605 721
[19] 935 921 909 669 961 655 891 765 975 781 803 708 857 735 753 795 752 650
[37] 635 605 656 857 599 807 629 705 828 554 534 544 986 607 979 954 785 746
[55] 634 977 566 996 775 700 837 800 507 995 744 833 654 641 779 707 560 509
[73] 665 761 680 855 518 780 928 668 508 982 722 589 566 621 541 624 867 839
[91] 766 950 667 638 989 582 971 583 979 538
Live Demo
y4<-sample(1:999,100,replace=TRUE)
y4
[1] 41 165 870 243 622 33 75 643 636 591 336 684 586 831 872 868 331 371
[19] 230 851 664 387 742 535 324 918 325 576 987 609 740 307 938 257 740 441
[37] 881 242 277 939 819 401 841 376 297 115 695 266 900 23 553 991 527 76
[55] 448 817 251 876 225 25 255 166 480 488 143 477 942 396 264 957 133 405
[73] 889 582 425 96 273 414 707 713 201 398 442 762 641 484 591 190 776 905
[91] 852 680 468 294 13 452 541 183 865 143
match(x4,y4)
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 58 NA NA NA NA NA NA NA
[26] NA NA NA NA NA 59 NA NA NA NA NA NA NA NA 87 NA NA NA NA NA 27 NA NA NA NA
[51] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 87 NA NA NA NA
[76] NA NA 37 NA NA NA NA NA NA NA 50 NA NA NA NA NA NA NA NA 43 NA NA NA NA NA
Live Demo
x5<-rpois(150,5)
x5
[1] 6 4 4 5 3 5 8 8 7 3 4 4 7 4 4 9 10 6 4 3 4 8 3 5 6
[26] 4 8 3 7 2 7 6 4 3 7 4 4 7 2 3 8 2 7 7 6 5 2 4 7 1
[51] 7 4 4 3 3 7 10 5 3 8 9 0 4 8 4 4 5 3 5 9 4 3 3 3 4
[76] 2 7 5 4 5 8 6 3 2 2 1 5 4 1 4 7 3 6 1 9 6 4 3 5 4
[101] 1 4 8 6 5 5 1 7 5 2 8 4 2 3 7 2 0 4 4 7 5 2 5 3 4
[126] 2 10 7 7 4 5 3 0 3 5 2 6 7 4 6 5 5 4 6 6 9 1 3 5 4
Live Demo
y5<-rpois(150,3)
y5
[1] 1 2 2 5 2 3 6 5 3 4 3 1 4 6 1 2 5 2 3 3 6 1 6 1 4 1 6 0 1 3 3 3 4 1 5 5 4
[38] 1 4 5 3 3 1 1 2 4 3 2 2 2 3 5 4 4 2 1 3 0 4 2 3 0 5 4 3 3 3 4 5 6 4 2 3 4
[75] 3 2 1 3 0 1 2 1 7 0 2 3 2 1 5 4 1 3 1 1 4 1 4 1 6 3 4 4 0 3 1 1 2 6 1 2 2
[112] 3 5 5 3 2 5 3 2 3 2 1 2 4 1 2 1 4 2 5 3 6 3 4 2 6 6 3 3 2 3 6 2 2 3 2 5 2
[149] 3 3
match(x5,y5)
[1] 6 6 NA 1 3 1 6 6 2 1 23 6 23 1 4 1 4 1
[19] 133 1 4 6 4 133 11 133 6 23 4 23 133 1 6 11 133 NA
[37] 4 2 133 11 2 11 4 3 23 11 11 NA 133 133 2 4 6 133
[55] 4 NA 6 6 6 6 3 NA 4 133 6 4 133 11 1 1 NA 133
[73] 1 11 2 4 1 4 11 3 11 4 23 11 6 11 3 1 11 1
[91] 2 1 1 6 1 2 NA 23 1 1 1 2 3 133 4 3 6 3
[109] 4 1 23 133 4 NA NA 11 133 4 NA 11 1 6 4 4 6 11
[127] 6 1 11 1 6 11 133 4 4 6 1 6 6 133 1 6 23 4
[145] 4 11 6 11 23 1
Live Demo
x6<-round(runif(100,2,5))
x6
[1] 4 3 3 5 3 5 2 3 3 5 3 3 4 4 4 4 3 2 4 5 2 5 2 4 4 5 2 4 4 3 3 3 3 2 3 4 4
[38] 4 3 4 5 4 2 2 2 5 4 3 4 2 5 2 2 4 4 4 5 3 3 3 3 3 4 4 5 4 2 4 2 2 4 2 5 4
[75] 3 3 4 4 2 2 4 2 3 5 4 4 4 4 3 4 5 2 4 4 4 3 5 4 5 3
Live Demo
y6<-round(runif(100,2,10))
y6
[1] 3 2 5 9 7 8 2 6 6 9 9 9 8 3 8 9 7 5 4 3 5 2 6 6 10
[26] 10 6 4 3 3 5 3 3 3 5 6 7 6 7 6 9 6 5 7 9 2 3 4 2 9
[51] 7 6 3 6 6 4 6 9 6 3 5 8 4 9 6 5 8 10 3 8 7 3 3 6 3
[76] 2 5 10 2 7 10 4 9 6 3 2 6 6 5 4 8 3 8 2 2 2 8 4 3 8
match(x6,y6)
[1] 26 18 1 18 18 1 18 18 1 12 26 18 18 18 1 1 1 18 18 18 1 26 1 18 18
[26] 26 26 12 18 26 1 18 18 12 1 26 1 1 26 1 18 26 12 18 26 26 18 26 18 18
[51] 18 12 1 1 12 26 1 1 12 1 1 26 1 1 1 1 1 18 26 12 26 26 12 26 18
[76] 18 1 26 1 26 18 1 1 1 26 12 18 26 1 18 1 18 18 1 1 1 18 1 12 1
|
[
{
"code": null,
"e": 1331,
"s": 1062,
"text": "Finding the position of one of more values that are common in two vectors can be easily done with the help of match function. The match function will match the values in first and second vector then return the index or position of these common values in second vector."
},
{
"code": null,
"e": 1342,
"s": 1331,
"text": " Live Demo"
},
{
"code": null,
"e": 1386,
"s": 1342,
"text": "set.seed(145)\nx1<-0:5\ny1<-10:0\nmatch(x1,y1)"
},
{
"code": null,
"e": 1404,
"s": 1386,
"text": "[1] 11 10 9 8 7 6"
},
{
"code": null,
"e": 1415,
"s": 1404,
"text": " Live Demo"
},
{
"code": null,
"e": 1451,
"s": 1415,
"text": "x2<-sample(0:9,100,replace=TRUE)\nx2"
},
{
"code": null,
"e": 1665,
"s": 1451,
"text": "[1] 9 9 0 5 1 7 3 4 2 4 0 8 0 2 3 2 4 3 2 0 9 2 3 4 6 2 7 9 1 0 8 6 4 1 7 7 4\n[38] 8 6 6 4 4 0 0 0 7 4 2 0 3 8 8 0 3 7 2 1 7 7 9 7 7 1 6 7 6 5 5 7 7 4 3 8 5\n[75] 0 2 1 5 3 0 2 7 2 5 5 2 5 5 2 9 2 3 6 8 0 1 7 0 6 7"
},
{
"code": null,
"e": 1676,
"s": 1665,
"text": " Live Demo"
},
{
"code": null,
"e": 1712,
"s": 1676,
"text": "y2<-sample(6:9,100,replace=TRUE)\ny2"
},
{
"code": null,
"e": 1926,
"s": 1712,
"text": "[1] 8 7 7 7 8 7 6 6 9 6 6 7 7 9 9 8 6 9 7 7 7 6 6 6 8 9 6 7 6 7 6 7 7 9 6 9 8\n[38] 7 8 6 6 6 8 6 8 7 7 6 6 6 9 9 6 9 7 9 6 9 7 8 9 7 9 9 6 7 8 8 8 7 6 7 8 8\n[75] 9 9 6 9 6 8 6 8 9 7 8 7 8 9 8 7 8 8 7 9 8 7 6 6 9 6"
},
{
"code": null,
"e": 1939,
"s": 1926,
"text": "match(x2,y2)"
},
{
"code": null,
"e": 2223,
"s": 1939,
"text": "[1] 8 3 3 NA NA NA NA NA NA NA NA NA NA 1 NA 3 NA 3 NA NA NA 1 NA NA 1\n [26] NA NA 2 NA 8 NA NA 8 NA NA 3 NA 8 2 NA NA NA NA NA 8 NA NA NA 8 1\n[51] NA 1 NA NA NA NA NA NA NA NA 2 2 NA NA 8 8 1 NA 8 NA 8 1 8 2 NA\n[76] NA NA NA NA NA NA NA 8 8 NA 1 8 NA NA 3 3 NA NA NA 3 NA NA 8 NA NA"
},
{
"code": null,
"e": 2234,
"s": 2223,
"text": " Live Demo"
},
{
"code": null,
"e": 2272,
"s": 2234,
"text": "x3<-sample(21:50,100,replace=TRUE)\nx3"
},
{
"code": null,
"e": 2591,
"s": 2272,
"text": "[1] 28 30 33 32 47 26 43 42 27 32 35 31 37 26 46 49 27 44 39 49 42 43 31 33 24\n[26] 45 50 50 23 30 23 48 27 29 45 39 27 27 45 49 41 27 47 39 47 42 21 40 50 50\n[51] 30 29 45 25 47 34 26 31 30 41 34 44 25 47 23 45 48 43 44 47 24 47 21 43 44\n[76] 43 36 39 44 22 28 49 28 34 30 37 50 25 25 46 43 44 30 32 37 45 23 43 48 48"
},
{
"code": null,
"e": 2602,
"s": 2591,
"text": " Live Demo"
},
{
"code": null,
"e": 2640,
"s": 2602,
"text": "y3<-sample(10:50,100,replace=TRUE)\ny3"
},
{
"code": null,
"e": 2959,
"s": 2640,
"text": "[1] 29 14 49 34 45 13 15 44 35 36 37 41 37 38 37 41 37 39 29 33 31 39 35 28 12\n[26] 32 21 14 42 45 13 38 18 33 33 24 48 17 47 24 19 10 39 33 41 39 49 27 28 27\n[51] 31 20 31 18 17 45 49 17 11 14 45 18 21 42 50 41 50 22 33 15 36 20 44 10 39\n[76] 23 21 41 15 16 20 48 47 40 16 48 23 33 47 43 13 23 38 11 33 41 45 21 18 29"
},
{
"code": null,
"e": 2972,
"s": 2959,
"text": "match(x3,y3)"
},
{
"code": null,
"e": 3274,
"s": 2972,
"text": "[1] 62 48 68 62 49 55 8 14 1 8 1 93 46 2 22 23 19 48 41 6 13 14 28 55 85\n[26] 9 21 9 13 55 8 88 66 41 6 62 33 33 46 23 62 13 14 12 33 27 33 21 55 12\n[51] 23 12 15 47 9 48 21 23 48 85 15 47 2 1 15 19 41 93 28 46 48 93 13 62 62\n[76] 55 41 21 22 46 6 14 14 22 66 68 47 33 13 55 47 6 15 48 88 21 6 8 41 13"
},
{
"code": null,
"e": 3285,
"s": 3274,
"text": " Live Demo"
},
{
"code": null,
"e": 3325,
"s": 3285,
"text": "x4<-sample(501:999,100,replace=TRUE)\nx4"
},
{
"code": null,
"e": 3754,
"s": 3325,
"text": "[1] 593 568 672 827 854 927 961 854 867 743 812 631 656 543 633 914 605 721\n[19] 935 921 909 669 961 655 891 765 975 781 803 708 857 735 753 795 752 650\n[37] 635 605 656 857 599 807 629 705 828 554 534 544 986 607 979 954 785 746\n[55] 634 977 566 996 775 700 837 800 507 995 744 833 654 641 779 707 560 509\n[73] 665 761 680 855 518 780 928 668 508 982 722 589 566 621 541 624 867 839\n[91] 766 950 667 638 989 582 971 583 979 538"
},
{
"code": null,
"e": 3765,
"s": 3754,
"text": " Live Demo"
},
{
"code": null,
"e": 3803,
"s": 3765,
"text": "y4<-sample(1:999,100,replace=TRUE)\ny4"
},
{
"code": null,
"e": 4224,
"s": 3803,
"text": "[1] 41 165 870 243 622 33 75 643 636 591 336 684 586 831 872 868 331 371\n[19] 230 851 664 387 742 535 324 918 325 576 987 609 740 307 938 257 740 441\n[37] 881 242 277 939 819 401 841 376 297 115 695 266 900 23 553 991 527 76\n[55] 448 817 251 876 225 25 255 166 480 488 143 477 942 396 264 957 133 405\n[73] 889 582 425 96 273 414 707 713 201 398 442 762 641 484 591 190 776 905\n[91] 852 680 468 294 13 452 541 183 865 143"
},
{
"code": null,
"e": 4237,
"s": 4224,
"text": "match(x4,y4)"
},
{
"code": null,
"e": 4556,
"s": 4237,
"text": "[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 58 NA NA NA NA NA NA NA\n[26] NA NA NA NA NA 59 NA NA NA NA NA NA NA NA 87 NA NA NA NA NA 27 NA NA NA NA\n[51] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 87 NA NA NA NA\n[76] NA NA 37 NA NA NA NA NA NA NA 50 NA NA NA NA NA NA NA NA 43 NA NA NA NA NA"
},
{
"code": null,
"e": 4567,
"s": 4556,
"text": " Live Demo"
},
{
"code": null,
"e": 4587,
"s": 4567,
"text": "x5<-rpois(150,5)\nx5"
},
{
"code": null,
"e": 4921,
"s": 4587,
"text": "[1] 6 4 4 5 3 5 8 8 7 3 4 4 7 4 4 9 10 6 4 3 4 8 3 5 6\n[26] 4 8 3 7 2 7 6 4 3 7 4 4 7 2 3 8 2 7 7 6 5 2 4 7 1\n[51] 7 4 4 3 3 7 10 5 3 8 9 0 4 8 4 4 5 3 5 9 4 3 3 3 4\n[76] 2 7 5 4 5 8 6 3 2 2 1 5 4 1 4 7 3 6 1 9 6 4 3 5 4\n[101] 1 4 8 6 5 5 1 7 5 2 8 4 2 3 7 2 0 4 4 7 5 2 5 3 4\n[126] 2 10 7 7 4 5 3 0 3 5 2 6 7 4 6 5 5 4 6 6 9 1 3 5 4"
},
{
"code": null,
"e": 4932,
"s": 4921,
"text": " Live Demo"
},
{
"code": null,
"e": 4952,
"s": 4932,
"text": "y5<-rpois(150,3)\ny5"
},
{
"code": null,
"e": 5278,
"s": 4952,
"text": "[1] 1 2 2 5 2 3 6 5 3 4 3 1 4 6 1 2 5 2 3 3 6 1 6 1 4 1 6 0 1 3 3 3 4 1 5 5 4\n[38] 1 4 5 3 3 1 1 2 4 3 2 2 2 3 5 4 4 2 1 3 0 4 2 3 0 5 4 3 3 3 4 5 6 4 2 3 4\n[75] 3 2 1 3 0 1 2 1 7 0 2 3 2 1 5 4 1 3 1 1 4 1 4 1 6 3 4 4 0 3 1 1 2 6 1 2 2\n[112] 3 5 5 3 2 5 3 2 3 2 1 2 4 1 2 1 4 2 5 3 6 3 4 2 6 6 3 3 2 3 6 2 2 3 2 5 2\n[149] 3 3"
},
{
"code": null,
"e": 5291,
"s": 5278,
"text": "match(x5,y5)"
},
{
"code": null,
"e": 5712,
"s": 5291,
"text": "[1] 6 6 NA 1 3 1 6 6 2 1 23 6 23 1 4 1 4 1\n[19] 133 1 4 6 4 133 11 133 6 23 4 23 133 1 6 11 133 NA\n[37] 4 2 133 11 2 11 4 3 23 11 11 NA 133 133 2 4 6 133\n[55] 4 NA 6 6 6 6 3 NA 4 133 6 4 133 11 1 1 NA 133\n[73] 1 11 2 4 1 4 11 3 11 4 23 11 6 11 3 1 11 1\n[91] 2 1 1 6 1 2 NA 23 1 1 1 2 3 133 4 3 6 3\n[109] 4 1 23 133 4 NA NA 11 133 4 NA 11 1 6 4 4 6 11\n[127] 6 1 11 1 6 11 133 4 4 6 1 6 6 133 1 6 23 4\n[145] 4 11 6 11 23 1"
},
{
"code": null,
"e": 5723,
"s": 5712,
"text": " Live Demo"
},
{
"code": null,
"e": 5752,
"s": 5723,
"text": "x6<-round(runif(100,2,5))\nx6"
},
{
"code": null,
"e": 5966,
"s": 5752,
"text": "[1] 4 3 3 5 3 5 2 3 3 5 3 3 4 4 4 4 3 2 4 5 2 5 2 4 4 5 2 4 4 3 3 3 3 2 3 4 4\n[38] 4 3 4 5 4 2 2 2 5 4 3 4 2 5 2 2 4 4 4 5 3 3 3 3 3 4 4 5 4 2 4 2 2 4 2 5 4\n[75] 3 3 4 4 2 2 4 2 3 5 4 4 4 4 3 4 5 2 4 4 4 3 5 4 5 3"
},
{
"code": null,
"e": 5977,
"s": 5966,
"text": " Live Demo"
},
{
"code": null,
"e": 6007,
"s": 5977,
"text": "y6<-round(runif(100,2,10))\ny6"
},
{
"code": null,
"e": 6231,
"s": 6007,
"text": "[1] 3 2 5 9 7 8 2 6 6 9 9 9 8 3 8 9 7 5 4 3 5 2 6 6 10\n[26] 10 6 4 3 3 5 3 3 3 5 6 7 6 7 6 9 6 5 7 9 2 3 4 2 9\n[51] 7 6 3 6 6 4 6 9 6 3 5 8 4 9 6 5 8 10 3 8 7 3 3 6 3\n[76] 2 5 10 2 7 10 4 9 6 3 2 6 6 5 4 8 3 8 2 2 2 8 4 3 8"
},
{
"code": null,
"e": 6244,
"s": 6231,
"text": "match(x6,y6)"
},
{
"code": null,
"e": 6527,
"s": 6244,
"text": "[1] 26 18 1 18 18 1 18 18 1 12 26 18 18 18 1 1 1 18 18 18 1 26 1 18 18\n[26] 26 26 12 18 26 1 18 18 12 1 26 1 1 26 1 18 26 12 18 26 26 18 26 18 18\n[51] 18 12 1 1 12 26 1 1 12 1 1 26 1 1 1 1 1 18 26 12 26 26 12 26 18\n[76] 18 1 26 1 26 18 1 1 1 26 12 18 26 1 18 1 18 18 1 1 1 18 1 12 1"
}
] |
How to create a free VPN server on AWS | by Israel Aminu | Towards Data Science
|
A VPN (Virtual Private Network) is important if you want to have more secure and safe browsing and also using it when you want to create access to your VPC(Virtual Private Cloud). Sometimes getting a VPN can be hard at times, especially when you have to pay to use the service. In this article, I will show you how you can set up a working VPN server on AWS and you don’t have to necessarily pay for anything at all to use it. Let’s get started.
To get started with this tutorial, you need a Free Tier AWS account so you won’t be charged for running the VPN on AWS. If you don’t have an AWS account, not to worry, you can create one here which comes with a Free Tier Eligibility for 12 months.
Login to your AWS account, Navigate to the EC2 service and then click on Launch Instance.
Then on the page click on “AWS Marketplace” and type “openvpn” select the “OpenVPN Access Server”, the one with the “Free tier eligible” option and click Select.
OpenVPN is an opensource VPN server, in this case, we are using an Ubuntu AMI(Amazon Machine Image) to run the VPN, sometimes AWS marketplace is better if you don't want to go through the headache of configuring the OpenVPN server yourself.
After clicking Select, you will be directed the page below. Remember, as I said earlier OpenVPN is a free and Open Source VPN, but it’s a commercial service but although we can be allowed to open two VPN accounts for free without being charged anything using the Bring Your Own License(BYOL) option and that’s the essence of the page being displayed here. After this, scroll down and click Select.
Then you’ll be directed to this page, this is where the service will be running on, select the t2.micro which contains the Free tier eligible tag, then click on “Review and Launch”
After clicking on Review and Launch, you see a review of the instance you’re about to create. If you read through you’ll see that the cost of running the service is $0.00 per hour. Click on Launch
Then you’ll see a pop up which ask you to create or use an existing key pair, this part is very important because you’ll need it to SSH to your server. If you don't have one already you can create a new key pair and download it to your computer. Then click on Launch Instances. In a few seconds, your instance will start running and you’re good to go.
After your instance has successfully launched. Open your terminal and SSH to your server as a root user in order to configure the admin side of the VPN, to do that use the command below:
ssh -i "<your-key-pair>" root@<your-public-instance-domain>
Your key pair is the one you either recently downloaded or you have on your computer, also ensure you specify the path of your key pair for it to work, that’s if it’s in a different directory. Your public instance domain can be found on the EC2 dashboard. If entered correctly you should see a license agreement terms, type yes and enter.
Next, you’ll be prompted with how you want to configure your VPN, to leave the settings default just continue to hit enter and it will start the configuration process for you. After it's done you’ll see an instruction to no longer login as root but as user “openvpnas” which is created by default.
Now SSH to the instance again, but not as root but as user “openvpnas” using the command below:
ssh -i "<your-key-pair>" openvpnas@<your-public-instance-domain>
When you’ve logged in successfully, create a password for the user “openvpnas”, this is going to be the admin and client password to have access to the VPN portal, you can do that using the command below:
sudo passwd openvpn
You’ll see a prompt to create a new password. And that’s it, you’ve successfully configured the server.
Congratulations on getting to this point of the tutorial, but before we start using it we just need to enable one little feature in our VPN.
Copy the public DNS or the IP address for your instance and paste the following on your browser:
http://<your-instance-public-DNS or IP address>:943/admin
You should see the following page:
If you don’t see this page, try using an incognito browser to open the webpage. For the Username enter, “openvpnas” and password is the one you created earlier in step 2. If successful, you’ll be asked to accept license agreement terms and then you should see this page:
Now on the left page, go to configuration and click on “VPN Settings”
Then scroll down to Routing and enable “Should client Internet traffic be routed through the VPN?” option:
Scroll down and click on Save Settings.
When you change the settings, you’ll need to update the server, so click on “Update Running Server” and you're done!!!
Go to the URL and remove the admin path, it should be something like this:
http://<your-instance-public-DNS or IP address>:943/
You should see the user login page, enter the same credentials you use to log in for the admin
Now select the OS of your choice you want to use the VPN on, follow the prompts and you’re good to go!!!
And that's all. Thanks for reading and stay safe 😃.
|
[
{
"code": null,
"e": 618,
"s": 172,
"text": "A VPN (Virtual Private Network) is important if you want to have more secure and safe browsing and also using it when you want to create access to your VPC(Virtual Private Cloud). Sometimes getting a VPN can be hard at times, especially when you have to pay to use the service. In this article, I will show you how you can set up a working VPN server on AWS and you don’t have to necessarily pay for anything at all to use it. Let’s get started."
},
{
"code": null,
"e": 866,
"s": 618,
"text": "To get started with this tutorial, you need a Free Tier AWS account so you won’t be charged for running the VPN on AWS. If you don’t have an AWS account, not to worry, you can create one here which comes with a Free Tier Eligibility for 12 months."
},
{
"code": null,
"e": 956,
"s": 866,
"text": "Login to your AWS account, Navigate to the EC2 service and then click on Launch Instance."
},
{
"code": null,
"e": 1118,
"s": 956,
"text": "Then on the page click on “AWS Marketplace” and type “openvpn” select the “OpenVPN Access Server”, the one with the “Free tier eligible” option and click Select."
},
{
"code": null,
"e": 1359,
"s": 1118,
"text": "OpenVPN is an opensource VPN server, in this case, we are using an Ubuntu AMI(Amazon Machine Image) to run the VPN, sometimes AWS marketplace is better if you don't want to go through the headache of configuring the OpenVPN server yourself."
},
{
"code": null,
"e": 1757,
"s": 1359,
"text": "After clicking Select, you will be directed the page below. Remember, as I said earlier OpenVPN is a free and Open Source VPN, but it’s a commercial service but although we can be allowed to open two VPN accounts for free without being charged anything using the Bring Your Own License(BYOL) option and that’s the essence of the page being displayed here. After this, scroll down and click Select."
},
{
"code": null,
"e": 1938,
"s": 1757,
"text": "Then you’ll be directed to this page, this is where the service will be running on, select the t2.micro which contains the Free tier eligible tag, then click on “Review and Launch”"
},
{
"code": null,
"e": 2135,
"s": 1938,
"text": "After clicking on Review and Launch, you see a review of the instance you’re about to create. If you read through you’ll see that the cost of running the service is $0.00 per hour. Click on Launch"
},
{
"code": null,
"e": 2487,
"s": 2135,
"text": "Then you’ll see a pop up which ask you to create or use an existing key pair, this part is very important because you’ll need it to SSH to your server. If you don't have one already you can create a new key pair and download it to your computer. Then click on Launch Instances. In a few seconds, your instance will start running and you’re good to go."
},
{
"code": null,
"e": 2674,
"s": 2487,
"text": "After your instance has successfully launched. Open your terminal and SSH to your server as a root user in order to configure the admin side of the VPN, to do that use the command below:"
},
{
"code": null,
"e": 2734,
"s": 2674,
"text": "ssh -i \"<your-key-pair>\" root@<your-public-instance-domain>"
},
{
"code": null,
"e": 3073,
"s": 2734,
"text": "Your key pair is the one you either recently downloaded or you have on your computer, also ensure you specify the path of your key pair for it to work, that’s if it’s in a different directory. Your public instance domain can be found on the EC2 dashboard. If entered correctly you should see a license agreement terms, type yes and enter."
},
{
"code": null,
"e": 3371,
"s": 3073,
"text": "Next, you’ll be prompted with how you want to configure your VPN, to leave the settings default just continue to hit enter and it will start the configuration process for you. After it's done you’ll see an instruction to no longer login as root but as user “openvpnas” which is created by default."
},
{
"code": null,
"e": 3467,
"s": 3371,
"text": "Now SSH to the instance again, but not as root but as user “openvpnas” using the command below:"
},
{
"code": null,
"e": 3532,
"s": 3467,
"text": "ssh -i \"<your-key-pair>\" openvpnas@<your-public-instance-domain>"
},
{
"code": null,
"e": 3737,
"s": 3532,
"text": "When you’ve logged in successfully, create a password for the user “openvpnas”, this is going to be the admin and client password to have access to the VPN portal, you can do that using the command below:"
},
{
"code": null,
"e": 3757,
"s": 3737,
"text": "sudo passwd openvpn"
},
{
"code": null,
"e": 3861,
"s": 3757,
"text": "You’ll see a prompt to create a new password. And that’s it, you’ve successfully configured the server."
},
{
"code": null,
"e": 4002,
"s": 3861,
"text": "Congratulations on getting to this point of the tutorial, but before we start using it we just need to enable one little feature in our VPN."
},
{
"code": null,
"e": 4099,
"s": 4002,
"text": "Copy the public DNS or the IP address for your instance and paste the following on your browser:"
},
{
"code": null,
"e": 4157,
"s": 4099,
"text": "http://<your-instance-public-DNS or IP address>:943/admin"
},
{
"code": null,
"e": 4192,
"s": 4157,
"text": "You should see the following page:"
},
{
"code": null,
"e": 4463,
"s": 4192,
"text": "If you don’t see this page, try using an incognito browser to open the webpage. For the Username enter, “openvpnas” and password is the one you created earlier in step 2. If successful, you’ll be asked to accept license agreement terms and then you should see this page:"
},
{
"code": null,
"e": 4533,
"s": 4463,
"text": "Now on the left page, go to configuration and click on “VPN Settings”"
},
{
"code": null,
"e": 4640,
"s": 4533,
"text": "Then scroll down to Routing and enable “Should client Internet traffic be routed through the VPN?” option:"
},
{
"code": null,
"e": 4680,
"s": 4640,
"text": "Scroll down and click on Save Settings."
},
{
"code": null,
"e": 4799,
"s": 4680,
"text": "When you change the settings, you’ll need to update the server, so click on “Update Running Server” and you're done!!!"
},
{
"code": null,
"e": 4874,
"s": 4799,
"text": "Go to the URL and remove the admin path, it should be something like this:"
},
{
"code": null,
"e": 4927,
"s": 4874,
"text": "http://<your-instance-public-DNS or IP address>:943/"
},
{
"code": null,
"e": 5022,
"s": 4927,
"text": "You should see the user login page, enter the same credentials you use to log in for the admin"
},
{
"code": null,
"e": 5127,
"s": 5022,
"text": "Now select the OS of your choice you want to use the VPN on, follow the prompts and you’re good to go!!!"
}
] |
How can I get the current Android SDK version programmatically?
|
This example demonstrates how do I get the current SDK version programmatically.
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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:text=""
android:id="@+id/textView"
android:layout_marginTop="30dp"
android:textStyle="bold"
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
int versionAPI = Build.VERSION.SDK_INT;
String versionRelease = Build.VERSION.RELEASE;
textView.setText("API Version :" + versionAPI + "\n" + "Version Release : " + versionRelease);
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "This example demonstrates how do I get the current SDK version programmatically."
},
{
"code": null,
"e": 1272,
"s": 1143,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1337,
"s": 1272,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1941,
"s": 1337,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:text=\"\"\n android:id=\"@+id/textView\"\n android:layout_marginTop=\"30dp\"\n android:textStyle=\"bold\"\n android:textSize=\"24sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"/>\n</LinearLayout>"
},
{
"code": null,
"e": 1998,
"s": 1941,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2568,
"s": 1998,
"text": "import android.os.Build;\nimport android.os.Bundle;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n int versionAPI = Build.VERSION.SDK_INT;\n String versionRelease = Build.VERSION.RELEASE;\n textView.setText(\"API Version :\" + versionAPI + \"\\n\" + \"Version Release : \" + versionRelease);\n }\n}\n"
},
{
"code": null,
"e": 2623,
"s": 2568,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3293,
"s": 2623,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3644,
"s": 3293,
"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 the 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": 3685,
"s": 3644,
"text": "Click here to download the project code."
}
] |
Introduction to Statistical Methods in AI | by Atul Agarwal | Towards Data Science
|
Statistical Learning is a set of tools for understanding data. These tools broadly come under two classes: supervised learning & unsupervised learning. Generally, supervised learning refers to predicting or estimating an output based on one or more inputs. Unsupervised learning, on the other hand, provides a relationship or finds a pattern within the given data without a supervised output.
Let, suppose that we observe a response Y and p different predictors X = (X1, X2,...., Xp). In general, we can say:
Y =f(X) + ε
Here f is an unknown function, and ε is the random error term.
In essence, statistical learning refers to a set of approaches for estimating f.
In cases where we have set of X readily available, but the output Y, not so much, the error averages to zero, and we can say:
¥ = ƒ(X)
where ƒ represents our estimate of f and ¥ represents the resulting prediction.
Hence for a set of predictors X, we can say:
E(Y — ¥)2 = E[f(X) + ε — ƒ(X)]2=> E(Y — ¥)2 = [f(X) - ƒ(X)]2 + Var(ε)
where,
E(Y — ¥)2 represents the expected value of the squared difference between actual and expected result.
[f(X) — ƒ(X)]2 represents the reducible error. It is reducible because we can potentially improve the accuracy of ƒ by better modeling.
Var(ε) represents the irreducible error. It is irreducible because no matter how well we estimate ƒ, we cannot reduce the error introduced by variance in ε.
Variables, Y, can be broadly be characterised as quantitative or qualitative( also known as categorical). Quantitative variables take on numerical values, e.g., age, height, income, price, and much more. Estimating qualitative responses is often termed as a regression problem. Qualitative variables take on categorical values, e.g., gender, brand, parts of speech, and much more. Estimating qualitative responses is often termed as a classification problem.
There is no free lunch in statistics: no one method dominates all other over all possible data sets.
Variance refers to the amount by which ƒ would change if we estimated with different training data sets. In general, when we over-fit a model on a given training data set(reducible error in training set is very low but on test set is very high), we get a model that has higher variance since any change in the data points would results in a significantly different model.
Bias refers to the error introduced by approximating a real-life problem, which may be extremely complicated by a much simpler model — for example, modeling non-linear problems with a linear model. In general, when we over-fit, a model on given data set it results in very less bias.
This results in the variance bias trade-off.
As we fit the model over a given data set, the bias tends to decrease faster than the variance increases initially. Consequently, the expected test error(reducible) declines. However, at some point, when over-fitting starts, there is a little impact on the bias, but variance starts to increase rapidly when this happens the test error increases.
Linear regression is a statistical method belonging to supervised learning used for predicting quantitative responses.
Simple Linear Regression approach predicts a quantitative response ¥ based on a single variable X assuming a linear relationship. We can say :
¥ ≈ β0 + β1X
Our job is now to estimate β0 and β1, the parameters/coefficients of our model based on the training data set, such that the hyperplane(in this case a line) is close to the training data set. Many criteria can estimate the closeness, the most common being least square.
The sum of the square of the difference between all observed response and the predicted response formulates to Residual Sum Of Squares(RSS).
Problems in Linear Regression
Non-linearity of the response-predictor relationships.
Correlation of error terms.
The non-constant variance of error terms.
Outliers: when the actual prediction is very far from the estimated one, can arise due to inaccurate recording of data.
High-leverage points: Unusual values of the predictors impact the regression line known as high leverage points.
Collinearity: where two or more predictor variables are closely related to each other, it may be challenging to weed out the individual effect of a single predictor variable.
KNN Regression
KNN Regression is a non-parametric approach towards estimating or predicting values, which do not assume the form of ƒ(X). It estimates/predicts ƒ(x0) where x0 is a prediction point by averaging out all N0 responses closest to x0. We can say:
Note: If K is small, the fit would be flexible and any change in the data would result in a different fit, hence for small K the variance would be high and bias low; conversely, if K is large, it might mask some structure in the data hence the bias would be high.
The responses as we discussed till now, may not always be quantitative, it can be also qualitative, predicting these qualitative responses is called classification.
We will discuss various statistical approaches to classification including:
SVM
Logistic Regression
KNN Classifier
GAM
Trees
Random Forest
Boosting
SVM or support vector machine is the classifier that maximizes the margin. The goal of a classifier in our example below is to find a line or (n-1) dimension hyper-plane that separates the two classes present in the n-dimensional space. I have written a detailed article explaining the derivation and formulation of SVM. In my opinion, it is one of the most powerful techniques in our tool box of statistical methods in AI.
Logistic model models the probability of output response ¥ belonging to a particular category.
We can say:
Applying componendo dividendo we get:
which is nothing but the odds.
For estimating the beta coefficients, we can use maximum likelihood. The basic idea is to estimate the betas such that the estimated value and observed value of the results are as close as possible. In a binary classification, with observed classes as 1 and 0, we can say the likelihood function would look like:
KNN(K nearest neighbors) Classifier is a lazy learning technique, where the training data set is represented on a Euclidean hyperplane, and test data is assigned the labels based on the K Euclidean distance metrics.
Practical Aspects
K should be chosen empirically and preferably odd to avoid tie situation.
KNN should have both discrete and continuous target functions.
Weighted contribution(e.g. distance based) from different neighbors can be used computing the final label.
Note: Performance of KNN degrades when the data is high dimensional. This can be avoided by providing weights to the features itself.
Effect Of K on the decision boundary
Advantages Of KNN
We can learn a complex target function.
Zero loss of any information.
Disadvantages of KNN
Classification cost of new instances is very high.
Significant computation takes place at classification time.
GAM provides a generalized framework extending standard multivariable linear regression with the nonlinear function of each variable while maintaining its additive nature. Thus, all nonlinear functions can be independently calculated and added later.
Note: GAM like linear regression can be applied to both quantitative and qualitative responses.
Trees or decision trees are useful and straightforward methods for both regression and classification involving segmenting the predictor space into simple regions.
Typically decision trees are drawn upside down meaning the leaves are at the bottom of the tree. The points where the predictor space is split are known as internal nodes, and the leaf nodes or terminal nodes are the ones which given the predictions. Segments joining the nodes are known as branches.
For prediction, we take a top-down(at the first point all the observation belongs to just one region), greedy(best split is made in the particular step) approach known as recursive binary fitting.
There are strategies like tree pruning that solves the over-fitting problem of trees by cutting some of the branches to get a small sub-tree.
For a classification problem, we either use Gini index,
or entropy
to represent the purity of a node, where Pmk is the proportion of samples in the mth region from kth class.
Decision trees still suffer from high variance and are not competitive with other supervised approaches. Therefore, we introduce random forest boosting and bagging.
Bagging
Bagging is a general-purpose method to reduce variance in a statistical learning method. The core idea is that averaging a set of observations reduces variance. Hence we do a random sampling of our data multiple times, and for each sample, we construct a tree and average out all the predictions to give a low variance result.
Random Forest
When in the collection of bagged trees, a fix k predictors are chosen at random from each tree having total m predictors (k < m), then bagging becomes a random forest.
This is done because most of the bagged trees would look more or less the same. Hence, the predictions of individual bag trees would be highly co-related. Therefore, there would not be much reduction in the variance of our inferences. Random forests can be thought of as the process of de-correlating bagged trees.
Boosting
Boosting approach is a slow learning statistical method, where classifiers are learned on modified data set sequentially. In the context of decision trees, each tree is grown using information from the previous trees. This way, we do not fit a single large tree.
All the above methods had some form of annotated data set. But when we want to learn patterns in our data without any annotations unsupervised learning comes into the picture.
The most widely used statistical method for unsupervised learning is K-Means Clustering. We take k random points in our data set and map all other points to one of the K regions based on their closeness to K chosen random points. Then we change the K random points to the centroid of the clusters thus formed. We do that until we observe a negligible change in the cluster formed after each iteration.
There are other techniques like PCA in unsupervised learning that are used a lot, but for now, we end here.
Next: Introduction to Artificial Neural Nets
|
[
{
"code": null,
"e": 565,
"s": 172,
"text": "Statistical Learning is a set of tools for understanding data. These tools broadly come under two classes: supervised learning & unsupervised learning. Generally, supervised learning refers to predicting or estimating an output based on one or more inputs. Unsupervised learning, on the other hand, provides a relationship or finds a pattern within the given data without a supervised output."
},
{
"code": null,
"e": 681,
"s": 565,
"text": "Let, suppose that we observe a response Y and p different predictors X = (X1, X2,...., Xp). In general, we can say:"
},
{
"code": null,
"e": 693,
"s": 681,
"text": "Y =f(X) + ε"
},
{
"code": null,
"e": 756,
"s": 693,
"text": "Here f is an unknown function, and ε is the random error term."
},
{
"code": null,
"e": 837,
"s": 756,
"text": "In essence, statistical learning refers to a set of approaches for estimating f."
},
{
"code": null,
"e": 963,
"s": 837,
"text": "In cases where we have set of X readily available, but the output Y, not so much, the error averages to zero, and we can say:"
},
{
"code": null,
"e": 972,
"s": 963,
"text": "¥ = ƒ(X)"
},
{
"code": null,
"e": 1052,
"s": 972,
"text": "where ƒ represents our estimate of f and ¥ represents the resulting prediction."
},
{
"code": null,
"e": 1097,
"s": 1052,
"text": "Hence for a set of predictors X, we can say:"
},
{
"code": null,
"e": 1167,
"s": 1097,
"text": "E(Y — ¥)2 = E[f(X) + ε — ƒ(X)]2=> E(Y — ¥)2 = [f(X) - ƒ(X)]2 + Var(ε)"
},
{
"code": null,
"e": 1174,
"s": 1167,
"text": "where,"
},
{
"code": null,
"e": 1276,
"s": 1174,
"text": "E(Y — ¥)2 represents the expected value of the squared difference between actual and expected result."
},
{
"code": null,
"e": 1412,
"s": 1276,
"text": "[f(X) — ƒ(X)]2 represents the reducible error. It is reducible because we can potentially improve the accuracy of ƒ by better modeling."
},
{
"code": null,
"e": 1569,
"s": 1412,
"text": "Var(ε) represents the irreducible error. It is irreducible because no matter how well we estimate ƒ, we cannot reduce the error introduced by variance in ε."
},
{
"code": null,
"e": 2028,
"s": 1569,
"text": "Variables, Y, can be broadly be characterised as quantitative or qualitative( also known as categorical). Quantitative variables take on numerical values, e.g., age, height, income, price, and much more. Estimating qualitative responses is often termed as a regression problem. Qualitative variables take on categorical values, e.g., gender, brand, parts of speech, and much more. Estimating qualitative responses is often termed as a classification problem."
},
{
"code": null,
"e": 2129,
"s": 2028,
"text": "There is no free lunch in statistics: no one method dominates all other over all possible data sets."
},
{
"code": null,
"e": 2501,
"s": 2129,
"text": "Variance refers to the amount by which ƒ would change if we estimated with different training data sets. In general, when we over-fit a model on a given training data set(reducible error in training set is very low but on test set is very high), we get a model that has higher variance since any change in the data points would results in a significantly different model."
},
{
"code": null,
"e": 2785,
"s": 2501,
"text": "Bias refers to the error introduced by approximating a real-life problem, which may be extremely complicated by a much simpler model — for example, modeling non-linear problems with a linear model. In general, when we over-fit, a model on given data set it results in very less bias."
},
{
"code": null,
"e": 2830,
"s": 2785,
"text": "This results in the variance bias trade-off."
},
{
"code": null,
"e": 3177,
"s": 2830,
"text": "As we fit the model over a given data set, the bias tends to decrease faster than the variance increases initially. Consequently, the expected test error(reducible) declines. However, at some point, when over-fitting starts, there is a little impact on the bias, but variance starts to increase rapidly when this happens the test error increases."
},
{
"code": null,
"e": 3296,
"s": 3177,
"text": "Linear regression is a statistical method belonging to supervised learning used for predicting quantitative responses."
},
{
"code": null,
"e": 3439,
"s": 3296,
"text": "Simple Linear Regression approach predicts a quantitative response ¥ based on a single variable X assuming a linear relationship. We can say :"
},
{
"code": null,
"e": 3452,
"s": 3439,
"text": "¥ ≈ β0 + β1X"
},
{
"code": null,
"e": 3722,
"s": 3452,
"text": "Our job is now to estimate β0 and β1, the parameters/coefficients of our model based on the training data set, such that the hyperplane(in this case a line) is close to the training data set. Many criteria can estimate the closeness, the most common being least square."
},
{
"code": null,
"e": 3863,
"s": 3722,
"text": "The sum of the square of the difference between all observed response and the predicted response formulates to Residual Sum Of Squares(RSS)."
},
{
"code": null,
"e": 3893,
"s": 3863,
"text": "Problems in Linear Regression"
},
{
"code": null,
"e": 3948,
"s": 3893,
"text": "Non-linearity of the response-predictor relationships."
},
{
"code": null,
"e": 3976,
"s": 3948,
"text": "Correlation of error terms."
},
{
"code": null,
"e": 4018,
"s": 3976,
"text": "The non-constant variance of error terms."
},
{
"code": null,
"e": 4138,
"s": 4018,
"text": "Outliers: when the actual prediction is very far from the estimated one, can arise due to inaccurate recording of data."
},
{
"code": null,
"e": 4251,
"s": 4138,
"text": "High-leverage points: Unusual values of the predictors impact the regression line known as high leverage points."
},
{
"code": null,
"e": 4426,
"s": 4251,
"text": "Collinearity: where two or more predictor variables are closely related to each other, it may be challenging to weed out the individual effect of a single predictor variable."
},
{
"code": null,
"e": 4441,
"s": 4426,
"text": "KNN Regression"
},
{
"code": null,
"e": 4684,
"s": 4441,
"text": "KNN Regression is a non-parametric approach towards estimating or predicting values, which do not assume the form of ƒ(X). It estimates/predicts ƒ(x0) where x0 is a prediction point by averaging out all N0 responses closest to x0. We can say:"
},
{
"code": null,
"e": 4948,
"s": 4684,
"text": "Note: If K is small, the fit would be flexible and any change in the data would result in a different fit, hence for small K the variance would be high and bias low; conversely, if K is large, it might mask some structure in the data hence the bias would be high."
},
{
"code": null,
"e": 5113,
"s": 4948,
"text": "The responses as we discussed till now, may not always be quantitative, it can be also qualitative, predicting these qualitative responses is called classification."
},
{
"code": null,
"e": 5189,
"s": 5113,
"text": "We will discuss various statistical approaches to classification including:"
},
{
"code": null,
"e": 5193,
"s": 5189,
"text": "SVM"
},
{
"code": null,
"e": 5213,
"s": 5193,
"text": "Logistic Regression"
},
{
"code": null,
"e": 5228,
"s": 5213,
"text": "KNN Classifier"
},
{
"code": null,
"e": 5232,
"s": 5228,
"text": "GAM"
},
{
"code": null,
"e": 5238,
"s": 5232,
"text": "Trees"
},
{
"code": null,
"e": 5252,
"s": 5238,
"text": "Random Forest"
},
{
"code": null,
"e": 5261,
"s": 5252,
"text": "Boosting"
},
{
"code": null,
"e": 5685,
"s": 5261,
"text": "SVM or support vector machine is the classifier that maximizes the margin. The goal of a classifier in our example below is to find a line or (n-1) dimension hyper-plane that separates the two classes present in the n-dimensional space. I have written a detailed article explaining the derivation and formulation of SVM. In my opinion, it is one of the most powerful techniques in our tool box of statistical methods in AI."
},
{
"code": null,
"e": 5780,
"s": 5685,
"text": "Logistic model models the probability of output response ¥ belonging to a particular category."
},
{
"code": null,
"e": 5792,
"s": 5780,
"text": "We can say:"
},
{
"code": null,
"e": 5830,
"s": 5792,
"text": "Applying componendo dividendo we get:"
},
{
"code": null,
"e": 5861,
"s": 5830,
"text": "which is nothing but the odds."
},
{
"code": null,
"e": 6174,
"s": 5861,
"text": "For estimating the beta coefficients, we can use maximum likelihood. The basic idea is to estimate the betas such that the estimated value and observed value of the results are as close as possible. In a binary classification, with observed classes as 1 and 0, we can say the likelihood function would look like:"
},
{
"code": null,
"e": 6390,
"s": 6174,
"text": "KNN(K nearest neighbors) Classifier is a lazy learning technique, where the training data set is represented on a Euclidean hyperplane, and test data is assigned the labels based on the K Euclidean distance metrics."
},
{
"code": null,
"e": 6408,
"s": 6390,
"text": "Practical Aspects"
},
{
"code": null,
"e": 6482,
"s": 6408,
"text": "K should be chosen empirically and preferably odd to avoid tie situation."
},
{
"code": null,
"e": 6545,
"s": 6482,
"text": "KNN should have both discrete and continuous target functions."
},
{
"code": null,
"e": 6652,
"s": 6545,
"text": "Weighted contribution(e.g. distance based) from different neighbors can be used computing the final label."
},
{
"code": null,
"e": 6786,
"s": 6652,
"text": "Note: Performance of KNN degrades when the data is high dimensional. This can be avoided by providing weights to the features itself."
},
{
"code": null,
"e": 6823,
"s": 6786,
"text": "Effect Of K on the decision boundary"
},
{
"code": null,
"e": 6841,
"s": 6823,
"text": "Advantages Of KNN"
},
{
"code": null,
"e": 6881,
"s": 6841,
"text": "We can learn a complex target function."
},
{
"code": null,
"e": 6911,
"s": 6881,
"text": "Zero loss of any information."
},
{
"code": null,
"e": 6932,
"s": 6911,
"text": "Disadvantages of KNN"
},
{
"code": null,
"e": 6983,
"s": 6932,
"text": "Classification cost of new instances is very high."
},
{
"code": null,
"e": 7043,
"s": 6983,
"text": "Significant computation takes place at classification time."
},
{
"code": null,
"e": 7294,
"s": 7043,
"text": "GAM provides a generalized framework extending standard multivariable linear regression with the nonlinear function of each variable while maintaining its additive nature. Thus, all nonlinear functions can be independently calculated and added later."
},
{
"code": null,
"e": 7390,
"s": 7294,
"text": "Note: GAM like linear regression can be applied to both quantitative and qualitative responses."
},
{
"code": null,
"e": 7554,
"s": 7390,
"text": "Trees or decision trees are useful and straightforward methods for both regression and classification involving segmenting the predictor space into simple regions."
},
{
"code": null,
"e": 7855,
"s": 7554,
"text": "Typically decision trees are drawn upside down meaning the leaves are at the bottom of the tree. The points where the predictor space is split are known as internal nodes, and the leaf nodes or terminal nodes are the ones which given the predictions. Segments joining the nodes are known as branches."
},
{
"code": null,
"e": 8052,
"s": 7855,
"text": "For prediction, we take a top-down(at the first point all the observation belongs to just one region), greedy(best split is made in the particular step) approach known as recursive binary fitting."
},
{
"code": null,
"e": 8194,
"s": 8052,
"text": "There are strategies like tree pruning that solves the over-fitting problem of trees by cutting some of the branches to get a small sub-tree."
},
{
"code": null,
"e": 8250,
"s": 8194,
"text": "For a classification problem, we either use Gini index,"
},
{
"code": null,
"e": 8261,
"s": 8250,
"text": "or entropy"
},
{
"code": null,
"e": 8369,
"s": 8261,
"text": "to represent the purity of a node, where Pmk is the proportion of samples in the mth region from kth class."
},
{
"code": null,
"e": 8534,
"s": 8369,
"text": "Decision trees still suffer from high variance and are not competitive with other supervised approaches. Therefore, we introduce random forest boosting and bagging."
},
{
"code": null,
"e": 8542,
"s": 8534,
"text": "Bagging"
},
{
"code": null,
"e": 8869,
"s": 8542,
"text": "Bagging is a general-purpose method to reduce variance in a statistical learning method. The core idea is that averaging a set of observations reduces variance. Hence we do a random sampling of our data multiple times, and for each sample, we construct a tree and average out all the predictions to give a low variance result."
},
{
"code": null,
"e": 8883,
"s": 8869,
"text": "Random Forest"
},
{
"code": null,
"e": 9051,
"s": 8883,
"text": "When in the collection of bagged trees, a fix k predictors are chosen at random from each tree having total m predictors (k < m), then bagging becomes a random forest."
},
{
"code": null,
"e": 9366,
"s": 9051,
"text": "This is done because most of the bagged trees would look more or less the same. Hence, the predictions of individual bag trees would be highly co-related. Therefore, there would not be much reduction in the variance of our inferences. Random forests can be thought of as the process of de-correlating bagged trees."
},
{
"code": null,
"e": 9375,
"s": 9366,
"text": "Boosting"
},
{
"code": null,
"e": 9638,
"s": 9375,
"text": "Boosting approach is a slow learning statistical method, where classifiers are learned on modified data set sequentially. In the context of decision trees, each tree is grown using information from the previous trees. This way, we do not fit a single large tree."
},
{
"code": null,
"e": 9814,
"s": 9638,
"text": "All the above methods had some form of annotated data set. But when we want to learn patterns in our data without any annotations unsupervised learning comes into the picture."
},
{
"code": null,
"e": 10216,
"s": 9814,
"text": "The most widely used statistical method for unsupervised learning is K-Means Clustering. We take k random points in our data set and map all other points to one of the K regions based on their closeness to K chosen random points. Then we change the K random points to the centroid of the clusters thus formed. We do that until we observe a negligible change in the cluster formed after each iteration."
},
{
"code": null,
"e": 10324,
"s": 10216,
"text": "There are other techniques like PCA in unsupervised learning that are used a lot, but for now, we end here."
}
] |
C# program to get the total number of cores on a computer
|
Use the Environment.ProcessorCount to get the total number of cores on a computer −
Environment.ProcessorCount
The following is the code that displays the total number of cores on a computer in C# −
Using System;
namespace Demo {
class Program {
static void Main(string[] args) {
Console.WriteLine(Environment.ProcessorCount);
}
}
}
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "Use the Environment.ProcessorCount to get the total number of cores on a computer −"
},
{
"code": null,
"e": 1173,
"s": 1146,
"text": "Environment.ProcessorCount"
},
{
"code": null,
"e": 1261,
"s": 1173,
"text": "The following is the code that displays the total number of cores on a computer in C# −"
},
{
"code": null,
"e": 1422,
"s": 1261,
"text": "Using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(Environment.ProcessorCount);\n }\n }\n}"
}
] |
JDBC Scrollable ResultSet Example | JDBC ResultSet Scrollable Tutorials
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Whenever we create an object of ResultSet by default, it allows us to retrieve in the forward direction only and we cannot perform any modifications on ResultSet object. Therefore, by default, the ResultSet object is non-scrollable and non-updatable ResultSet.
In this tutorials, I am going to tell you how to make a ResultSet object as scrollable.
A scrollable ResultSet is one which allows us to retrieve the data in forward direction as well as backward direction but no updations are allowed. In order to make the non-scrollable ResultSet as scrollable ResultSet we must use the following createStatement() method which is present in Connection interface.
public Statement createStatement(int Type, int Mode);
Here type represents the type of scrollability and mode represents either read only or updatable. The
value of Type and the Modes are present in ResultSet interface as constant data members and they are:
TYPE_FORWARD_ONLY -> 1
TYPE_SCROLL_INSENSITIVE -> 2
CONCUR_READ_ONLY u0001 -> 3
We can pass the above constants to ResultSet as below:
Statement st=con.createStatement ( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
ResultSet rs=st.executeQuery (“select * from empleyee”);
Whenever we create a ResultSet object, by default, constant-1 as a Type and constant-3 as mode will be assigned.
ResultSet interface provides us several methods to make an ResultSet as Scrollable ResultSet below is the list of methods available in ResultSet interface.
public boolean next (); It returns true when rs contains next record otherwise false.
public void beforeFirst (); It is used for making the ResultSet object to point to just before the first record (it is by default)
public boolean isFirst (); It returns true when rs is pointing to first record otherwise false.
public void first (); It is used to point the ResultSet object to first record.
public boolean isBeforeFirst (); It returns true when rs pointing to before first record otherwise false.
public boolean previous (); It returns true when rs contains previous record otherwise false.
public void afterLast (); It is used for making the ResultSet object to point to just after the last record.
public boolean isLast (); It returns true when rs is pointing to last record otherwise false.
public void last (); It is used to point the ResultSet object to last record.
public boolean isAfterLast (); It returns true when rs is pointing after last record otherwise false.
public void absolute (int); It is used for moving the ResultSet object to a particular record either in forward direction or in backward direction with respect to first record and last record respectively. If int value is positive, rs move in forward direction to that with respect to first record. If int value is negative, rs move in backward direction to that with respect to last record.
public void relative (int); It is used for moving rs to that record either in forward direction or in backward direction with respect to current record.
package com.onlinetutorialspoint.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ScrollResultSet {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/onlinetutorialspoint", "root",
"123456");
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("select * from student");
System.out.println("RECORDS IN THE TABLE...");
while (rs.next()) {
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
}
rs.first();
System.out.println("FIRST RECORD...");
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
rs.absolute(3);
System.out.println("THIRD RECORD...");
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
rs.last();
System.out.println("LAST RECORD...");
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
rs.previous();
rs.relative(-1);
System.out.println("LAST TO FIRST RECORD...");
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
con.close();
}
}
Output:
RECORDS IN THE TABLE...
28 -> Chandra Shekhar
30 -> Chandra Shekhar
101 -> Rajesh
102 -> rajesh
202 -> chandrashekhar
2002 -> Rahul
2003 -> chandrashekhar
2004 -> Rahul
2005 -> chandrashekhar
3002 -> Bhargav
3005 -> Rahul
3006 -> Bharat
FIRST RECORD...
28 -> Chandra Shekhar
THIRD RECORD...
101 -> Rajesh
LAST RECORD...
3006 -> Bharat
FIRST RECORD...
3002 -> Bhargav
Happy Learning 🙂
JDBC Updatable ResultSet Example
JDBC Interview Questions and Answers
JDBC Select Program Example
JDBC Insert Program Example
JDBC Update Program Example
JDBC Delete Program Example
JDBC PreparedStatement Example Program
Insert an Image using JDBC in Mysql DB
Read an Image in JDBC Example
CallableStatement in jdbc Example
ResultSetMetaData in JDBC Example
DatabaseMetaData in JDBC Example
Transaction Management in JDBC Example
Batch Processing in JDBC Example
JDBC Connection with Properties file
JDBC Updatable ResultSet Example
JDBC Interview Questions and Answers
JDBC Select Program Example
JDBC Insert Program Example
JDBC Update Program Example
JDBC Delete Program Example
JDBC PreparedStatement Example Program
Insert an Image using JDBC in Mysql DB
Read an Image in JDBC Example
CallableStatement in jdbc Example
ResultSetMetaData in JDBC Example
DatabaseMetaData in JDBC Example
Transaction Management in JDBC Example
Batch Processing in JDBC Example
JDBC Connection with Properties file
Suhana
November 5, 2019 at 1:19 pm - Reply
It’s too good and helpful. So, thanks sir
Jagadeeswaran Rangappan
October 12, 2021 at 10:48 am - Reply
try to avoid using “SELECT * FROM”. It wont work for UPDATABLE resultset. In this example, it is insignificant because, it is READONLY. so no issues.
Suhana
November 5, 2019 at 1:19 pm - Reply
It’s too good and helpful. So, thanks sir
It’s too good and helpful. So, thanks sir
Jagadeeswaran Rangappan
October 12, 2021 at 10:48 am - Reply
try to avoid using “SELECT * FROM”. It wont work for UPDATABLE resultset. In this example, it is insignificant because, it is READONLY. so no issues.
try to avoid using “SELECT * FROM”. It wont work for UPDATABLE resultset. In this example, it is insignificant because, it is READONLY. so no issues.
Δ
JDBC Driver Types
Step by Step JDBC Program
JDBC Select Program
JDBC Insert Program
JDBC Update Program
JDBC Delete Program
JDBC Connection – Properties File
JDBC PreparedStatement Program
JDBC – CallableStatement Example
JDBC – Read an Image from DB
JDBC – Insert an Image in DB
JDBC – Updatable ResultSet
JDBC – Scrollable ResultSet
JDBC – ResultSetMetaData
JDBC – DatabaseMetaData
JDBC – Transaction Management
JDBC – Batch Processing
JDBC Interview Questions
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 659,
"s": 398,
"text": "Whenever we create an object of ResultSet by default, it allows us to retrieve in the forward direction only and we cannot perform any modifications on ResultSet object. Therefore, by default, the ResultSet object is non-scrollable and non-updatable ResultSet."
},
{
"code": null,
"e": 747,
"s": 659,
"text": "In this tutorials, I am going to tell you how to make a ResultSet object as scrollable."
},
{
"code": null,
"e": 1058,
"s": 747,
"text": "A scrollable ResultSet is one which allows us to retrieve the data in forward direction as well as backward direction but no updations are allowed. In order to make the non-scrollable ResultSet as scrollable ResultSet we must use the following createStatement() method which is present in Connection interface."
},
{
"code": null,
"e": 1112,
"s": 1058,
"text": "public Statement createStatement(int Type, int Mode);"
},
{
"code": null,
"e": 1316,
"s": 1112,
"text": "Here type represents the type of scrollability and mode represents either read only or updatable. The\nvalue of Type and the Modes are present in ResultSet interface as constant data members and they are:"
},
{
"code": null,
"e": 1339,
"s": 1316,
"text": "TYPE_FORWARD_ONLY -> 1"
},
{
"code": null,
"e": 1368,
"s": 1339,
"text": "TYPE_SCROLL_INSENSITIVE -> 2"
},
{
"code": null,
"e": 1396,
"s": 1368,
"text": "CONCUR_READ_ONLY u0001 -> 3"
},
{
"code": null,
"e": 1451,
"s": 1396,
"text": "We can pass the above constants to ResultSet as below:"
},
{
"code": null,
"e": 1608,
"s": 1451,
"text": "Statement st=con.createStatement ( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );\nResultSet rs=st.executeQuery (“select * from empleyee”);"
},
{
"code": null,
"e": 1721,
"s": 1608,
"text": "Whenever we create a ResultSet object, by default, constant-1 as a Type and constant-3 as mode will be assigned."
},
{
"code": null,
"e": 1877,
"s": 1721,
"text": "ResultSet interface provides us several methods to make an ResultSet as Scrollable ResultSet below is the list of methods available in ResultSet interface."
},
{
"code": null,
"e": 1963,
"s": 1877,
"text": "public boolean next (); It returns true when rs contains next record otherwise false."
},
{
"code": null,
"e": 2095,
"s": 1963,
"text": "public void beforeFirst (); It is used for making the ResultSet object to point to just before the first record (it is by default)"
},
{
"code": null,
"e": 2192,
"s": 2095,
"text": "public boolean isFirst (); It returns true when rs is pointing to first record otherwise false."
},
{
"code": null,
"e": 2273,
"s": 2192,
"text": "public void first (); It is used to point the ResultSet object to first record."
},
{
"code": null,
"e": 2379,
"s": 2273,
"text": "public boolean isBeforeFirst (); It returns true when rs pointing to before first record otherwise false."
},
{
"code": null,
"e": 2474,
"s": 2379,
"text": "public boolean previous (); It returns true when rs contains previous record otherwise false."
},
{
"code": null,
"e": 2584,
"s": 2474,
"text": "public void afterLast (); It is used for making the ResultSet object to point to just after the last record."
},
{
"code": null,
"e": 2679,
"s": 2584,
"text": "public boolean isLast (); It returns true when rs is pointing to last record otherwise false."
},
{
"code": null,
"e": 2758,
"s": 2679,
"text": "public void last (); It is used to point the ResultSet object to last record."
},
{
"code": null,
"e": 2861,
"s": 2758,
"text": "public boolean isAfterLast (); It returns true when rs is pointing after last record otherwise false."
},
{
"code": null,
"e": 3254,
"s": 2861,
"text": "public void absolute (int); It is used for moving the ResultSet object to a particular record either in forward direction or in backward direction with respect to first record and last record respectively. If int value is positive, rs move in forward direction to that with respect to first record. If int value is negative, rs move in backward direction to that with respect to last record."
},
{
"code": null,
"e": 3408,
"s": 3254,
"text": "public void relative (int); It is used for moving rs to that record either in forward direction or in backward direction with respect to current record."
},
{
"code": null,
"e": 4834,
"s": 3408,
"text": "package com.onlinetutorialspoint.jdbc;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class ScrollResultSet {\n\n public static void main(String[] args) throws Exception {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n Connection con = DriverManager.getConnection(\n \"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\",\n \"123456\");\n Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_READ_ONLY);\n ResultSet rs = st.executeQuery(\"select * from student\");\n System.out.println(\"RECORDS IN THE TABLE...\");\n while (rs.next()) {\n System.out.println(rs.getInt(1) + \" -> \" + rs.getString(2));\n }\n rs.first();\n System.out.println(\"FIRST RECORD...\");\n System.out.println(rs.getInt(1) + \" -> \" + rs.getString(2));\n rs.absolute(3);\n System.out.println(\"THIRD RECORD...\");\n System.out.println(rs.getInt(1) + \" -> \" + rs.getString(2));\n rs.last();\n System.out.println(\"LAST RECORD...\");\n System.out.println(rs.getInt(1) + \" -> \" + rs.getString(2));\n rs.previous();\n rs.relative(-1);\n System.out.println(\"LAST TO FIRST RECORD...\");\n System.out.println(rs.getInt(1) + \" -> \" + rs.getString(2));\n con.close();\n }\n\n}"
},
{
"code": null,
"e": 4842,
"s": 4834,
"text": "Output:"
},
{
"code": null,
"e": 5209,
"s": 4842,
"text": "RECORDS IN THE TABLE...\n28 -> Chandra Shekhar\n30 -> Chandra Shekhar\n101 -> Rajesh\n102 -> rajesh\n202 -> chandrashekhar\n2002 -> Rahul\n2003 -> chandrashekhar\n2004 -> Rahul\n2005 -> chandrashekhar\n3002 -> Bhargav\n3005 -> Rahul\n3006 -> Bharat\nFIRST RECORD...\n28 -> Chandra Shekhar\nTHIRD RECORD...\n101 -> Rajesh\nLAST RECORD...\n3006 -> Bharat\nFIRST RECORD...\n3002 -> Bhargav"
},
{
"code": null,
"e": 5226,
"s": 5209,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 5728,
"s": 5226,
"text": "\nJDBC Updatable ResultSet Example\nJDBC Interview Questions and Answers\nJDBC Select Program Example\nJDBC Insert Program Example\nJDBC Update Program Example\nJDBC Delete Program Example\nJDBC PreparedStatement Example Program\nInsert an Image using JDBC in Mysql DB\nRead an Image in JDBC Example\nCallableStatement in jdbc Example\nResultSetMetaData in JDBC Example\nDatabaseMetaData in JDBC Example\nTransaction Management in JDBC Example\nBatch Processing in JDBC Example\nJDBC Connection with Properties file\n"
},
{
"code": null,
"e": 5761,
"s": 5728,
"text": "JDBC Updatable ResultSet Example"
},
{
"code": null,
"e": 5798,
"s": 5761,
"text": "JDBC Interview Questions and Answers"
},
{
"code": null,
"e": 5826,
"s": 5798,
"text": "JDBC Select Program Example"
},
{
"code": null,
"e": 5854,
"s": 5826,
"text": "JDBC Insert Program Example"
},
{
"code": null,
"e": 5882,
"s": 5854,
"text": "JDBC Update Program Example"
},
{
"code": null,
"e": 5910,
"s": 5882,
"text": "JDBC Delete Program Example"
},
{
"code": null,
"e": 5949,
"s": 5910,
"text": "JDBC PreparedStatement Example Program"
},
{
"code": null,
"e": 5988,
"s": 5949,
"text": "Insert an Image using JDBC in Mysql DB"
},
{
"code": null,
"e": 6018,
"s": 5988,
"text": "Read an Image in JDBC Example"
},
{
"code": null,
"e": 6052,
"s": 6018,
"text": "CallableStatement in jdbc Example"
},
{
"code": null,
"e": 6086,
"s": 6052,
"text": "ResultSetMetaData in JDBC Example"
},
{
"code": null,
"e": 6119,
"s": 6086,
"text": "DatabaseMetaData in JDBC Example"
},
{
"code": null,
"e": 6158,
"s": 6119,
"text": "Transaction Management in JDBC Example"
},
{
"code": null,
"e": 6191,
"s": 6158,
"text": "Batch Processing in JDBC Example"
},
{
"code": null,
"e": 6228,
"s": 6191,
"text": "JDBC Connection with Properties file"
},
{
"code": null,
"e": 6549,
"s": 6228,
"text": "\n\n\n\n\n\nSuhana\nNovember 5, 2019 at 1:19 pm - Reply \n\nIt’s too good and helpful. So, thanks sir\n\n\n\n\n\n\n\n\n\nJagadeeswaran Rangappan\nOctober 12, 2021 at 10:48 am - Reply \n\ntry to avoid using “SELECT * FROM”. It wont work for UPDATABLE resultset. In this example, it is insignificant because, it is READONLY. so no issues.\n\n\n\n\n"
},
{
"code": null,
"e": 6646,
"s": 6549,
"text": "\n\n\n\n\nSuhana\nNovember 5, 2019 at 1:19 pm - Reply \n\nIt’s too good and helpful. So, thanks sir\n\n\n\n"
},
{
"code": null,
"e": 6689,
"s": 6646,
"text": "It’s too good and helpful. So, thanks sir"
},
{
"code": null,
"e": 6911,
"s": 6689,
"text": "\n\n\n\n\nJagadeeswaran Rangappan\nOctober 12, 2021 at 10:48 am - Reply \n\ntry to avoid using “SELECT * FROM”. It wont work for UPDATABLE resultset. In this example, it is insignificant because, it is READONLY. so no issues.\n\n\n\n"
},
{
"code": null,
"e": 7061,
"s": 6911,
"text": "try to avoid using “SELECT * FROM”. It wont work for UPDATABLE resultset. In this example, it is insignificant because, it is READONLY. so no issues."
},
{
"code": null,
"e": 7067,
"s": 7065,
"text": "Δ"
},
{
"code": null,
"e": 7086,
"s": 7067,
"text": " JDBC Driver Types"
},
{
"code": null,
"e": 7113,
"s": 7086,
"text": " Step by Step JDBC Program"
},
{
"code": null,
"e": 7134,
"s": 7113,
"text": " JDBC Select Program"
},
{
"code": null,
"e": 7155,
"s": 7134,
"text": " JDBC Insert Program"
},
{
"code": null,
"e": 7176,
"s": 7155,
"text": " JDBC Update Program"
},
{
"code": null,
"e": 7197,
"s": 7176,
"text": " JDBC Delete Program"
},
{
"code": null,
"e": 7232,
"s": 7197,
"text": " JDBC Connection – Properties File"
},
{
"code": null,
"e": 7264,
"s": 7232,
"text": " JDBC PreparedStatement Program"
},
{
"code": null,
"e": 7298,
"s": 7264,
"text": " JDBC – CallableStatement Example"
},
{
"code": null,
"e": 7328,
"s": 7298,
"text": " JDBC – Read an Image from DB"
},
{
"code": null,
"e": 7358,
"s": 7328,
"text": " JDBC – Insert an Image in DB"
},
{
"code": null,
"e": 7386,
"s": 7358,
"text": " JDBC – Updatable ResultSet"
},
{
"code": null,
"e": 7415,
"s": 7386,
"text": " JDBC – Scrollable ResultSet"
},
{
"code": null,
"e": 7441,
"s": 7415,
"text": " JDBC – ResultSetMetaData"
},
{
"code": null,
"e": 7466,
"s": 7441,
"text": " JDBC – DatabaseMetaData"
},
{
"code": null,
"e": 7497,
"s": 7466,
"text": " JDBC – Transaction Management"
},
{
"code": null,
"e": 7522,
"s": 7497,
"text": " JDBC – Batch Processing"
}
] |
How to cluster similar sentences using TF-IDF and Graph partitioning in Python | by TU | Towards Data Science
|
In this series of articles we are analysing historical archives of data science publications to understand what topics are more popular with the readers. Previously we covered how to get the data that will be used for further analysis.
We will cover how to clean text data we collected earlier , group similar topics using network graphs and establish patterns within these clusters in this article.
Let’s remind ourselves how the data looks like. It is combination of articles obtained from three data sources [field: ‘Source’] — Analytics Vidhya [‘avd’], TDS [‘tds’] and Towards AI [‘tai’].
We collected titles, subtitles, claps and responses from individual articles in archives of the publications.
import pandas as pd# Reading the data obtained using code here.avd = pd.read_csv('analytics_vidhya_data.csv')tds = pd.read_csv('medium_articles.csv')tai = pd.read_csv('towards_ai_data.csv')avd['source'] = 'avd'tds['source'] = 'tds'tai['source'] = 'tai'# Create single data set, join title and subtitlesingle_matrix = pd.concat([avd, tds, tai])single_matrix['title_subtitle'] = [' '.join([str(i),str(j)]) for i, j in zip(single_matrix['Title'].fillna(''), single_matrix['Subtitle'].fillna(''))]
We added an additional column in the data set called ‘title_subtitle’ which is the join of columns ‘Title’ and ‘Subtitle’, we will mainly use this column in order to have a better view of the topic the article belongs to. Quite interestingly 39% of articles don’t have subtitles and a very small proportion (0.13%) don’t have titles.
Let’s quickly look at the claps and responses distributions for every data source. We start with box plots, we use seaborn library in Python to create our plots.
# We will use seaborn to create all plotsimport seaborn as snsimport matplotlib.pyplot as pltfig, axes = plt.subplots(1, 2, figsize=(8, 5))# Clapssns.boxplot(ax=axes[0], x="source", y="Claps", data=single_matrix)# Responsessns.boxplot(ax=axes[1], x="source", y="Responses", data=single_matrix)
We can see that Towards Data Science has not only more activity, but also quite a few outliers with individual articles gaining a lot of attraction from readers. Of course, the activity for each source depends on the size of publication, for larger publications we observe more writers and readers.
When it comes to responses, we observe far less activity in comparison to claps across all sources, although such behaviour is not very unexpected.
Next, we remove outliers and visualise distributions of the fields to have a clearer picture.
# Code to create distribution subplotsfig, axes = plt.subplots(2, 1, figsize=(8, 8))# Clapssns.distplot(avd['Claps'][avd['Claps']<10000], hist=True, rug=False, ax=axes[0])sns.distplot(tds['Claps'][tds['Claps']<10000], hist=True, rug=False, ax=axes[0])sns.distplot(tai['Claps'][tai['Claps']<10000], hist=True, rug=False, ax=axes[0])# Responsessns.distplot(avd['Responses'], hist=True, rug=False, ax=axes[1])sns.distplot(tds['Responses'], hist=True, rug=False, ax=axes[1])sns.distplot(tai['Responses'], hist=True, rug=False, ax=axes[1])
We can see that both distributions are skewed to the left, meaning that the most articles get very little claps and even less responses. Yet again this is not surprising, since the success of articles depends on many factors, such as good quality writing, relevant topics and many more. Striking a good balance is not a simple task!
Cleaning data is an important step (if not the most important part) when working with text. There are standard practices in place that one follows when dealing with such tasks. We will undertake following steps to process titles and subtitles:
remove punctuation marks and other symbols
remove stop words and digits
lemmatise words
We will use a mixture of regular expressions and nltk library to remove punctuation marks, symbols, stop words and digits.
import resingle_matrix['title_subtitle'] = [re.findall(r'\w+', i.lower()) for i in single_matrix['title_subtitle'].fillna('NONE')]
The code above matches one or more word characters, in fact r’\w+’ is the same as r’[a-zA-Z0–9_]+’. Also, when applying re.findall() and i.lower() commands, they conveniently split sentences into words and transform them into lower case. This will come very useful in next steps. So, the sentence ‘Reporting In Qlikview | Ad Hoc Reporting’ becomes [reporting, in, qlikview, ad, hoc, reporting].
Next, we will use nltk library to upload a dictionary of stop words so we can remove them from the sentences. Additionally we append words ‘use’ and ‘part ‘ to the list, since they are overused in the data set. To remove the stop words we use for loop to iterate over each sentence, when doing so we also ensure to remove the digits from the sentences.
# The code to upload list of stop words and remove them from sentencesimport nltknltk.download('stopwords') from nltk.corpus import stopwordsstopwords_eng = stopwords.words('english') stopwords_eng += ['use', 'using', 'used', 'part']new_titles_sub = []for title_sub in single_matrix['new_title_subtitle']: new_title_sub = [] for w_title in title_sub: if w_title not in stopwords_eng and not w_title.isdigit(): new_title_sub.append(w_title) new_titles_sub.append(new_title_sub) single_matrix['new_title_subtitle'] = new_titles_sub
Finally, we are going to lemmatise words in the sentences. Lemmatisation transforms the word to its meaningful root form taking into consideration the context. Frequently stemming is used as a computationally faster alternative, however less accurate one. Once again we use nltk to lemmatise words
nltk.download('wordnet')nltk.download('words')from nltk.stem import WordNetLemmatizerwordnet_lemmatizer = WordNetLemmatizer()new_titles_sub = []for title_sub in single_matrix['title_subtitle']: new_title_sub = [] for w_title in title_sub: new_title_sub.append(wordnet_lemmatizer.lemmatize(w_title, pos="v")) new_titles_sub.append(new_title_sub) single_matrix['new_title_subtitle'] = new_titles_subsingle_matrix['new_title_subtitle'] = [' '.join(i) for i in single_matrix['new_title_subtitle']]
Let’s look how the sentences look like after all the transformations
TF-IDF stands for term frequency-inverse document frequency and it is a numerical measure of how relevant a keyword is to a document in some specific set of documents. It is commonly used in text analysis, some of the examples include content ranking and information retrieval. Here is quite a useful paper that talks about the approach in more detail.
As a name suggests the measure consists of two parts, one that finds frequency of a word appearing in a document (TF) and another the extent of word uniqueness in a corpus (IDF). Let’s look at the simplified version the formula and its components:
We can see that words appearing more frequently will result in a lower TF-IDF score and for rare words the score will be higher. This weight adjustment is quite important, since overused words will have no additional meaning.
The easiest way to understand the calculations is by example, in our data set a single title is a document and all the titles form a corpus (set of documents). Consider the word ‘create’ in the title ‘use variables qlikview create powerful data stories’, the document has 7 words and ‘create’ appears only once, so TF(create) = 1/7. The total number of articles in one of the data sources is 12963 and word ‘create’ appears in 268 titles so IDF(create)=log(12963/268) =3.88. Thus, TF-IDF =0.14*3.88 = 0.55 is the score for the word ‘create’.
Now that we know how the scores are calculated for each word in a document, we can vectorise the data set with articles titles and subtitles. For this we will use sklearn library in Python, in particular TfidfVectorizer function.
Note: TfidfVectorizer uses a slightly different formula than the one specified above, it adds 1 to IDF. This is done to ensure that the words that appear in every document are not neglected.
from sklearn.feature_extraction.text import TfidfVectorizertf = TfidfVectorizer(analyzer='word', ngram_range=(1, 3), min_df=0)tfidf_matrices = []data_sets = []for source in ['avd', 'tai', 'tds']: source_data = single_matrix[single_matrix['source'] == source].drop_duplicates() data_sets.append(source_data['new_title_subtitle']) tfidf_matrices.append(tf.fit_transform(source_data['new_title_subtitle']))
We introduced the for loop that iterates through the data sources, this is done to improve computational time. This will also be needed when looking at the distances between all pairs of sentences and partitioning them into groups. The output is the sparse matrix, where rows are documents and columns all unique words in a corpus.
Now that we have vectorised titles and subtitles, we can calculate pairwise distances between all the sentences. We will use cosine similarity between pairs of vectors that represent sentences. The measure considers the angle between two vectors and commonly used in text analysis. Some good explanations of the chosen similarity measure can be found here, the paper not only provides clear definition it also discusses context based uses.
We used sklearn library to calculate pairwise cosine similarities, yet again splitting by the source.
from sklearn.metrics.pairwise import linear_kernelmatrix_with_cos_sim = []for m in tfidf_matrices: matrix_with_cos_sim.append(linear_kernel(m, m))
The output for each data source is a numpy array (NxN) with pairwise similarities between all sentences where N is number of titles/subtitles for a single data source.
Our aim is to find clusters that have articles covering similar data science topics, to achieve this we will start by building a weighted graph where nodes are articles and edges are their cosine similarity. We are then able to create clusters by applying graph partitioning with the goal to find meaningful subgraphs (also called communities) without imposing a number of communities.
We will use Python libraries networkx and community to build and partition the graph. Before we proceed with building the graph, we will only select top 15 similar titles for every document in a corpus, the number was chosen based on the measure called modularity which gives indications how good partition is. This approach not only sharpens the graph but also helps with computational speed.
import numpy as npfrom tqdm import tnrangetop_n_sentences = []for cs, t in zip(matrix_with_cos_sim, data_sets): no_dups = np.array(t) i = 0 top_frame = [] for c, z in zip(cs, tnrange(len(cs))): # Create vector of titles start_name = pd.Series([no_dups[i]]*15) # Index of top 15 similar titles ix_top_n = np.argsort(-c)[0:15] cos_sim = pd.Series(c[ix_top_n]) names = pd.Series(no_dups[ix_top_n]) i +=1 top_frame.append(pd.DataFrame([start_name, names, cos_sim]).transpose()) top_frame = pd.concat(top_frame) top_frame.columns = ['title1', 'title2', 'cos_sim'] # Remove the similarities for the same sentences top_frame['is_same'] = [bool(i==j) for i, j in zip(top_frame['title1'], top_frame['title2'])] top_frame = top_frame[top_frame['is_same'] != True] top_n_sentences.append(top_frame)
The script produces the data frame with top 15 similar titles for every title in the data set (split by source), it will be used as an input to building the graph. Let’s look at the example of the data frame for one of the sources
We will continue by building and partitioning the graph, we will do it for the source that has the second largest number of articles which is Analytics Vidhya. The snippets of code can be applied to all the sources covered in this article.
# We start by defining the structure of the graphtop_frame = top_n_sentences[2] #TDS articlesedges = list(zip(top_frame['title1'], top_frame['title2']))weighted_edges = list(zip(top_frame['title1'], top_frame['title2'], top_frame['cos_sim']))nodes = list(set(top_frame['title1']).union(set(top_frame['title2'])))
We now can use networkx to build the graph using structure defined above
import networkx as nxG = nx.Graph()G.add_nodes_from(nodes)G.add_edges_from(edges)G.add_weighted_edges_from(weighted_edges)
Next we partition the graph using community library, before module imports ensure to install python-louvain library to avoid errors.
# !pip install python-louvainimport communitypartition = community.best_partition(G)modularity = community.modularity(partition, G)
Earlier we mentioned modularity, the measure how good the partition is, the value in this case is 0.7. Usually, values above 0.6 considered to be decent enough partitioning.
# Takes some time for larger graphsimport matplotlib.pyplot as pltpos = nx.spring_layout(G, dim=2)community_id = [partition[node] for node in G.nodes()]fig = plt.figure(figsize=(10,10))nx.draw(G, pos, edge_color = ['silver']*len(G.edges()), cmap=plt.cm.tab20, node_color=community_id, node_size=150)
The code above produces the graph and communities we just found, although the plot looks quite busy we are still able to see quite a few clusters found by the approach.
Before we look into clusters in more detail, we are going to transform partition variables we created earlier to a more readable format.
title, cluster = [], []for i in partition.items(): title.append(i[0]) cluster.append(i[1]) frame_clust = pd.DataFrame([pd.Series(title), pd.Series(cluster)]).transpose()frame_clust.columns = ['Title', 'Cluster']
The output of the code above is the data frame with all the titles and subtitles and the community they belong to with 45 clusters identified by partitioning the graph.
Now that we have obtained clusters, we can create summary statistics for each of them to understand if any of them have more activity. We will merge the data set that has partitions with the data set that has claps and responses then we will calculate min, max, mean, median and number of articles for each group. Although mainly will focus on median, since we saw earlier that the data is skewed towards smaller values and has outliers present.
avd = single_matrix[single_matrix['source'] == 'avd'].drop_duplicates()frame_clust = frame_clust.merge(tds[['Title', 'new_title_subtitle', 'Claps', 'Responses']], how='left', left_on='Title', right_on='new_title_subtitle')grouped_mat = frame_clust.groupby('Cluster').agg({'Claps': ['max', 'mean', 'sum', 'median'], 'Responses': ['max', 'mean', 'sum', 'median'], 'Title_x': 'count'}).reset_index()grouped_mat.columns = ['cluster', 'claps_max', 'claps_mean', 'claps_sum', 'claps_median','responses_max', 'responses_mean', 'responses_sum', 'responses_median', 'title_count']grouped_mat = grouped_mat.sort_values(by = ['claps_median', 'title_count'])
For representation purposes will only look at three communities with lowest reader activity and three with highest. We first consider the data set and then we are going to visualise word cloud to determine the common topic in each group.
The table above shows that there groups are not very large, let’s see what are the common themes in each cluster we will use wordcloud library for this.
from wordcloud import WordCloudfig, ax = plt.subplots(1, 3, figsize=(12.5,6.5))clusters = [19, 39, 38] #lowest activity groups# clusters = [43, 28, 7] #highest activity groupsfor cluster, col in zip(clusters, [0, 1, 2]): corpus = ' '.join(frame_clust['new_title_subtitle']. [frame_clust['Cluster'] == cluster]) ax[col].imshow(WordCloud(width = 800, height = 800, background_color ='white', min_font_size = 10).generate(corpus)) ax[col].axis("off")plt.show()
We first look at the communities with lowest activity, it seems that cluster 19 has mostly articles that belong to one author which would explain lower activity. The other two clusters consist of more articles that were written by multiple authors. Quite interestingly we can observe that topics such as ‘object oriented programming in python’ and ‘fraud detection’ attracted least interest from the readers.
Moving on to the clusters with highest activity the highlighted topics that cause more interest from the readers are natural language processing, neural networks, activation functions and support vector machines.
Wrap up
Although we were able to establish common themes in low and high readers activity groups, we still observed articles that didn’t have many claps and responses as well as ones that had high activity in each group. The analysis can come handy when trying to establish general patterns of what readers are interested in, as well as the topics that have higher saturation of articles. However choosing a relevant topic doesn’t guarantee success of the article, as many other important factors contribute towards gaining attraction from the reader.
|
[
{
"code": null,
"e": 407,
"s": 171,
"text": "In this series of articles we are analysing historical archives of data science publications to understand what topics are more popular with the readers. Previously we covered how to get the data that will be used for further analysis."
},
{
"code": null,
"e": 571,
"s": 407,
"text": "We will cover how to clean text data we collected earlier , group similar topics using network graphs and establish patterns within these clusters in this article."
},
{
"code": null,
"e": 764,
"s": 571,
"text": "Let’s remind ourselves how the data looks like. It is combination of articles obtained from three data sources [field: ‘Source’] — Analytics Vidhya [‘avd’], TDS [‘tds’] and Towards AI [‘tai’]."
},
{
"code": null,
"e": 874,
"s": 764,
"text": "We collected titles, subtitles, claps and responses from individual articles in archives of the publications."
},
{
"code": null,
"e": 1368,
"s": 874,
"text": "import pandas as pd# Reading the data obtained using code here.avd = pd.read_csv('analytics_vidhya_data.csv')tds = pd.read_csv('medium_articles.csv')tai = pd.read_csv('towards_ai_data.csv')avd['source'] = 'avd'tds['source'] = 'tds'tai['source'] = 'tai'# Create single data set, join title and subtitlesingle_matrix = pd.concat([avd, tds, tai])single_matrix['title_subtitle'] = [' '.join([str(i),str(j)]) for i, j in zip(single_matrix['Title'].fillna(''), single_matrix['Subtitle'].fillna(''))]"
},
{
"code": null,
"e": 1702,
"s": 1368,
"text": "We added an additional column in the data set called ‘title_subtitle’ which is the join of columns ‘Title’ and ‘Subtitle’, we will mainly use this column in order to have a better view of the topic the article belongs to. Quite interestingly 39% of articles don’t have subtitles and a very small proportion (0.13%) don’t have titles."
},
{
"code": null,
"e": 1864,
"s": 1702,
"text": "Let’s quickly look at the claps and responses distributions for every data source. We start with box plots, we use seaborn library in Python to create our plots."
},
{
"code": null,
"e": 2158,
"s": 1864,
"text": "# We will use seaborn to create all plotsimport seaborn as snsimport matplotlib.pyplot as pltfig, axes = plt.subplots(1, 2, figsize=(8, 5))# Clapssns.boxplot(ax=axes[0], x=\"source\", y=\"Claps\", data=single_matrix)# Responsessns.boxplot(ax=axes[1], x=\"source\", y=\"Responses\", data=single_matrix)"
},
{
"code": null,
"e": 2457,
"s": 2158,
"text": "We can see that Towards Data Science has not only more activity, but also quite a few outliers with individual articles gaining a lot of attraction from readers. Of course, the activity for each source depends on the size of publication, for larger publications we observe more writers and readers."
},
{
"code": null,
"e": 2605,
"s": 2457,
"text": "When it comes to responses, we observe far less activity in comparison to claps across all sources, although such behaviour is not very unexpected."
},
{
"code": null,
"e": 2699,
"s": 2605,
"text": "Next, we remove outliers and visualise distributions of the fields to have a clearer picture."
},
{
"code": null,
"e": 3234,
"s": 2699,
"text": "# Code to create distribution subplotsfig, axes = plt.subplots(2, 1, figsize=(8, 8))# Clapssns.distplot(avd['Claps'][avd['Claps']<10000], hist=True, rug=False, ax=axes[0])sns.distplot(tds['Claps'][tds['Claps']<10000], hist=True, rug=False, ax=axes[0])sns.distplot(tai['Claps'][tai['Claps']<10000], hist=True, rug=False, ax=axes[0])# Responsessns.distplot(avd['Responses'], hist=True, rug=False, ax=axes[1])sns.distplot(tds['Responses'], hist=True, rug=False, ax=axes[1])sns.distplot(tai['Responses'], hist=True, rug=False, ax=axes[1])"
},
{
"code": null,
"e": 3567,
"s": 3234,
"text": "We can see that both distributions are skewed to the left, meaning that the most articles get very little claps and even less responses. Yet again this is not surprising, since the success of articles depends on many factors, such as good quality writing, relevant topics and many more. Striking a good balance is not a simple task!"
},
{
"code": null,
"e": 3811,
"s": 3567,
"text": "Cleaning data is an important step (if not the most important part) when working with text. There are standard practices in place that one follows when dealing with such tasks. We will undertake following steps to process titles and subtitles:"
},
{
"code": null,
"e": 3854,
"s": 3811,
"text": "remove punctuation marks and other symbols"
},
{
"code": null,
"e": 3883,
"s": 3854,
"text": "remove stop words and digits"
},
{
"code": null,
"e": 3899,
"s": 3883,
"text": "lemmatise words"
},
{
"code": null,
"e": 4022,
"s": 3899,
"text": "We will use a mixture of regular expressions and nltk library to remove punctuation marks, symbols, stop words and digits."
},
{
"code": null,
"e": 4153,
"s": 4022,
"text": "import resingle_matrix['title_subtitle'] = [re.findall(r'\\w+', i.lower()) for i in single_matrix['title_subtitle'].fillna('NONE')]"
},
{
"code": null,
"e": 4548,
"s": 4153,
"text": "The code above matches one or more word characters, in fact r’\\w+’ is the same as r’[a-zA-Z0–9_]+’. Also, when applying re.findall() and i.lower() commands, they conveniently split sentences into words and transform them into lower case. This will come very useful in next steps. So, the sentence ‘Reporting In Qlikview | Ad Hoc Reporting’ becomes [reporting, in, qlikview, ad, hoc, reporting]."
},
{
"code": null,
"e": 4901,
"s": 4548,
"text": "Next, we will use nltk library to upload a dictionary of stop words so we can remove them from the sentences. Additionally we append words ‘use’ and ‘part ‘ to the list, since they are overused in the data set. To remove the stop words we use for loop to iterate over each sentence, when doing so we also ensure to remove the digits from the sentences."
},
{
"code": null,
"e": 5467,
"s": 4901,
"text": "# The code to upload list of stop words and remove them from sentencesimport nltknltk.download('stopwords') from nltk.corpus import stopwordsstopwords_eng = stopwords.words('english') stopwords_eng += ['use', 'using', 'used', 'part']new_titles_sub = []for title_sub in single_matrix['new_title_subtitle']: new_title_sub = [] for w_title in title_sub: if w_title not in stopwords_eng and not w_title.isdigit(): new_title_sub.append(w_title) new_titles_sub.append(new_title_sub) single_matrix['new_title_subtitle'] = new_titles_sub"
},
{
"code": null,
"e": 5765,
"s": 5467,
"text": "Finally, we are going to lemmatise words in the sentences. Lemmatisation transforms the word to its meaningful root form taking into consideration the context. Frequently stemming is used as a computationally faster alternative, however less accurate one. Once again we use nltk to lemmatise words"
},
{
"code": null,
"e": 6279,
"s": 5765,
"text": "nltk.download('wordnet')nltk.download('words')from nltk.stem import WordNetLemmatizerwordnet_lemmatizer = WordNetLemmatizer()new_titles_sub = []for title_sub in single_matrix['title_subtitle']: new_title_sub = [] for w_title in title_sub: new_title_sub.append(wordnet_lemmatizer.lemmatize(w_title, pos=\"v\")) new_titles_sub.append(new_title_sub) single_matrix['new_title_subtitle'] = new_titles_subsingle_matrix['new_title_subtitle'] = [' '.join(i) for i in single_matrix['new_title_subtitle']]"
},
{
"code": null,
"e": 6348,
"s": 6279,
"text": "Let’s look how the sentences look like after all the transformations"
},
{
"code": null,
"e": 6701,
"s": 6348,
"text": "TF-IDF stands for term frequency-inverse document frequency and it is a numerical measure of how relevant a keyword is to a document in some specific set of documents. It is commonly used in text analysis, some of the examples include content ranking and information retrieval. Here is quite a useful paper that talks about the approach in more detail."
},
{
"code": null,
"e": 6949,
"s": 6701,
"text": "As a name suggests the measure consists of two parts, one that finds frequency of a word appearing in a document (TF) and another the extent of word uniqueness in a corpus (IDF). Let’s look at the simplified version the formula and its components:"
},
{
"code": null,
"e": 7175,
"s": 6949,
"text": "We can see that words appearing more frequently will result in a lower TF-IDF score and for rare words the score will be higher. This weight adjustment is quite important, since overused words will have no additional meaning."
},
{
"code": null,
"e": 7717,
"s": 7175,
"text": "The easiest way to understand the calculations is by example, in our data set a single title is a document and all the titles form a corpus (set of documents). Consider the word ‘create’ in the title ‘use variables qlikview create powerful data stories’, the document has 7 words and ‘create’ appears only once, so TF(create) = 1/7. The total number of articles in one of the data sources is 12963 and word ‘create’ appears in 268 titles so IDF(create)=log(12963/268) =3.88. Thus, TF-IDF =0.14*3.88 = 0.55 is the score for the word ‘create’."
},
{
"code": null,
"e": 7947,
"s": 7717,
"text": "Now that we know how the scores are calculated for each word in a document, we can vectorise the data set with articles titles and subtitles. For this we will use sklearn library in Python, in particular TfidfVectorizer function."
},
{
"code": null,
"e": 8138,
"s": 7947,
"text": "Note: TfidfVectorizer uses a slightly different formula than the one specified above, it adds 1 to IDF. This is done to ensure that the words that appear in every document are not neglected."
},
{
"code": null,
"e": 8551,
"s": 8138,
"text": "from sklearn.feature_extraction.text import TfidfVectorizertf = TfidfVectorizer(analyzer='word', ngram_range=(1, 3), min_df=0)tfidf_matrices = []data_sets = []for source in ['avd', 'tai', 'tds']: source_data = single_matrix[single_matrix['source'] == source].drop_duplicates() data_sets.append(source_data['new_title_subtitle']) tfidf_matrices.append(tf.fit_transform(source_data['new_title_subtitle']))"
},
{
"code": null,
"e": 8883,
"s": 8551,
"text": "We introduced the for loop that iterates through the data sources, this is done to improve computational time. This will also be needed when looking at the distances between all pairs of sentences and partitioning them into groups. The output is the sparse matrix, where rows are documents and columns all unique words in a corpus."
},
{
"code": null,
"e": 9323,
"s": 8883,
"text": "Now that we have vectorised titles and subtitles, we can calculate pairwise distances between all the sentences. We will use cosine similarity between pairs of vectors that represent sentences. The measure considers the angle between two vectors and commonly used in text analysis. Some good explanations of the chosen similarity measure can be found here, the paper not only provides clear definition it also discusses context based uses."
},
{
"code": null,
"e": 9425,
"s": 9323,
"text": "We used sklearn library to calculate pairwise cosine similarities, yet again splitting by the source."
},
{
"code": null,
"e": 9575,
"s": 9425,
"text": "from sklearn.metrics.pairwise import linear_kernelmatrix_with_cos_sim = []for m in tfidf_matrices: matrix_with_cos_sim.append(linear_kernel(m, m))"
},
{
"code": null,
"e": 9743,
"s": 9575,
"text": "The output for each data source is a numpy array (NxN) with pairwise similarities between all sentences where N is number of titles/subtitles for a single data source."
},
{
"code": null,
"e": 10129,
"s": 9743,
"text": "Our aim is to find clusters that have articles covering similar data science topics, to achieve this we will start by building a weighted graph where nodes are articles and edges are their cosine similarity. We are then able to create clusters by applying graph partitioning with the goal to find meaningful subgraphs (also called communities) without imposing a number of communities."
},
{
"code": null,
"e": 10523,
"s": 10129,
"text": "We will use Python libraries networkx and community to build and partition the graph. Before we proceed with building the graph, we will only select top 15 similar titles for every document in a corpus, the number was chosen based on the measure called modularity which gives indications how good partition is. This approach not only sharpens the graph but also helps with computational speed."
},
{
"code": null,
"e": 11410,
"s": 10523,
"text": "import numpy as npfrom tqdm import tnrangetop_n_sentences = []for cs, t in zip(matrix_with_cos_sim, data_sets): no_dups = np.array(t) i = 0 top_frame = [] for c, z in zip(cs, tnrange(len(cs))): # Create vector of titles start_name = pd.Series([no_dups[i]]*15) # Index of top 15 similar titles ix_top_n = np.argsort(-c)[0:15] cos_sim = pd.Series(c[ix_top_n]) names = pd.Series(no_dups[ix_top_n]) i +=1 top_frame.append(pd.DataFrame([start_name, names, cos_sim]).transpose()) top_frame = pd.concat(top_frame) top_frame.columns = ['title1', 'title2', 'cos_sim'] # Remove the similarities for the same sentences top_frame['is_same'] = [bool(i==j) for i, j in zip(top_frame['title1'], top_frame['title2'])] top_frame = top_frame[top_frame['is_same'] != True] top_n_sentences.append(top_frame)"
},
{
"code": null,
"e": 11641,
"s": 11410,
"text": "The script produces the data frame with top 15 similar titles for every title in the data set (split by source), it will be used as an input to building the graph. Let’s look at the example of the data frame for one of the sources"
},
{
"code": null,
"e": 11881,
"s": 11641,
"text": "We will continue by building and partitioning the graph, we will do it for the source that has the second largest number of articles which is Analytics Vidhya. The snippets of code can be applied to all the sources covered in this article."
},
{
"code": null,
"e": 12194,
"s": 11881,
"text": "# We start by defining the structure of the graphtop_frame = top_n_sentences[2] #TDS articlesedges = list(zip(top_frame['title1'], top_frame['title2']))weighted_edges = list(zip(top_frame['title1'], top_frame['title2'], top_frame['cos_sim']))nodes = list(set(top_frame['title1']).union(set(top_frame['title2'])))"
},
{
"code": null,
"e": 12267,
"s": 12194,
"text": "We now can use networkx to build the graph using structure defined above"
},
{
"code": null,
"e": 12390,
"s": 12267,
"text": "import networkx as nxG = nx.Graph()G.add_nodes_from(nodes)G.add_edges_from(edges)G.add_weighted_edges_from(weighted_edges)"
},
{
"code": null,
"e": 12523,
"s": 12390,
"text": "Next we partition the graph using community library, before module imports ensure to install python-louvain library to avoid errors."
},
{
"code": null,
"e": 12655,
"s": 12523,
"text": "# !pip install python-louvainimport communitypartition = community.best_partition(G)modularity = community.modularity(partition, G)"
},
{
"code": null,
"e": 12829,
"s": 12655,
"text": "Earlier we mentioned modularity, the measure how good the partition is, the value in this case is 0.7. Usually, values above 0.6 considered to be decent enough partitioning."
},
{
"code": null,
"e": 13136,
"s": 12829,
"text": "# Takes some time for larger graphsimport matplotlib.pyplot as pltpos = nx.spring_layout(G, dim=2)community_id = [partition[node] for node in G.nodes()]fig = plt.figure(figsize=(10,10))nx.draw(G, pos, edge_color = ['silver']*len(G.edges()), cmap=plt.cm.tab20, node_color=community_id, node_size=150)"
},
{
"code": null,
"e": 13305,
"s": 13136,
"text": "The code above produces the graph and communities we just found, although the plot looks quite busy we are still able to see quite a few clusters found by the approach."
},
{
"code": null,
"e": 13442,
"s": 13305,
"text": "Before we look into clusters in more detail, we are going to transform partition variables we created earlier to a more readable format."
},
{
"code": null,
"e": 13663,
"s": 13442,
"text": "title, cluster = [], []for i in partition.items(): title.append(i[0]) cluster.append(i[1]) frame_clust = pd.DataFrame([pd.Series(title), pd.Series(cluster)]).transpose()frame_clust.columns = ['Title', 'Cluster']"
},
{
"code": null,
"e": 13832,
"s": 13663,
"text": "The output of the code above is the data frame with all the titles and subtitles and the community they belong to with 45 clusters identified by partitioning the graph."
},
{
"code": null,
"e": 14278,
"s": 13832,
"text": "Now that we have obtained clusters, we can create summary statistics for each of them to understand if any of them have more activity. We will merge the data set that has partitions with the data set that has claps and responses then we will calculate min, max, mean, median and number of articles for each group. Although mainly will focus on median, since we saw earlier that the data is skewed towards smaller values and has outliers present."
},
{
"code": null,
"e": 14937,
"s": 14278,
"text": "avd = single_matrix[single_matrix['source'] == 'avd'].drop_duplicates()frame_clust = frame_clust.merge(tds[['Title', 'new_title_subtitle', 'Claps', 'Responses']], how='left', left_on='Title', right_on='new_title_subtitle')grouped_mat = frame_clust.groupby('Cluster').agg({'Claps': ['max', 'mean', 'sum', 'median'], 'Responses': ['max', 'mean', 'sum', 'median'], 'Title_x': 'count'}).reset_index()grouped_mat.columns = ['cluster', 'claps_max', 'claps_mean', 'claps_sum', 'claps_median','responses_max', 'responses_mean', 'responses_sum', 'responses_median', 'title_count']grouped_mat = grouped_mat.sort_values(by = ['claps_median', 'title_count'])"
},
{
"code": null,
"e": 15175,
"s": 14937,
"text": "For representation purposes will only look at three communities with lowest reader activity and three with highest. We first consider the data set and then we are going to visualise word cloud to determine the common topic in each group."
},
{
"code": null,
"e": 15328,
"s": 15175,
"text": "The table above shows that there groups are not very large, let’s see what are the common themes in each cluster we will use wordcloud library for this."
},
{
"code": null,
"e": 15881,
"s": 15328,
"text": "from wordcloud import WordCloudfig, ax = plt.subplots(1, 3, figsize=(12.5,6.5))clusters = [19, 39, 38] #lowest activity groups# clusters = [43, 28, 7] #highest activity groupsfor cluster, col in zip(clusters, [0, 1, 2]): corpus = ' '.join(frame_clust['new_title_subtitle']. [frame_clust['Cluster'] == cluster]) ax[col].imshow(WordCloud(width = 800, height = 800, background_color ='white', min_font_size = 10).generate(corpus)) ax[col].axis(\"off\")plt.show()"
},
{
"code": null,
"e": 16290,
"s": 15881,
"text": "We first look at the communities with lowest activity, it seems that cluster 19 has mostly articles that belong to one author which would explain lower activity. The other two clusters consist of more articles that were written by multiple authors. Quite interestingly we can observe that topics such as ‘object oriented programming in python’ and ‘fraud detection’ attracted least interest from the readers."
},
{
"code": null,
"e": 16503,
"s": 16290,
"text": "Moving on to the clusters with highest activity the highlighted topics that cause more interest from the readers are natural language processing, neural networks, activation functions and support vector machines."
},
{
"code": null,
"e": 16511,
"s": 16503,
"text": "Wrap up"
}
] |
Unleash the power of Visual Studio Code (VSCode) on Google Cloud Platform Virtual Machine | by Marie Stephen Leo | Towards Data Science
|
Visual Studio Code (or VSCode for short) is a powerful, multi-platform, free code editor that supports multiple programming languages [1]. Over the past two years, it has tremendously grown in popularity, as can be noticed from the meteoric rise in its Google search trends. In this post, I will share a method to use VSCode installed on your local computer to edit and run code located on a Google Cloud Virtual Machine. But first...
As a Data Scientist, why should you use VSCode when you have the convenience of the Jupyter notebook[2]? Well, if you are like me, then your typical day to day Data Science job involves two aspects. The first aspect is to run experiments for which you use the (in)famous Jupyter notebook. Jupyter is highly suitable for the kind of iterative, experimental workflow involved in the early phases of a Data Science project. The second aspect of a Data Scientist’s job starts once you have a product that you want to run in production (run for thousands or millions of times every day). In many organizations, you do not have the luxury of a dedicated production team. Even if you do have that luxury, it is good practice to refactor your code before passing it to the production team to ensure the product works as expected once deployed. This is where VSCode shines in the Data Science workflow! The details of using VSCode to refactor code from a Jupyter notebook deserve a standalone post to do it justice. However, [3] provides an excellent overview of the refactoring tools available in VSCode. A simple example is “Rename Symbol,” which allows you to rename a variable just once but automatically updates everywhere the variable appears in your code! Super handy!
Let’s now get into the details of this post. Since you are reading this post, I assume you already have a GCP Compute Engine VM running, and you also have VSCode installed on your personal computer. If you don’t have both of these, then refer to [4] on how to set up a GCP Compute Engine VM and [1] to download and install VSCode on your local computer. Update: You must also have gcloud sdk installed and run gcloud init on your system following instructions from [9]
Mac and Linux users can directly jump to the For All Users section of this post and follow from step #1 using the built-in terminal. Windows users need to take note of the below:
For Windows Users only:
From your start menu, startup Windows Powershell
For all remaining steps under the For All Users section of this post, please follow the instructions under the Linux and MACOS section on the reference webpage. However, remember to remove the following wherever it appears: ~/.ssh/
For example, if the Linux and MACOS section of the reference webpage says:
ssh-keygen -t rsa -f ~/.ssh/[KEY_FILENAME] -C [USERNAME]
Type this in Windows Powershell instead:
ssh-keygen -t rsa -f [KEY_FILENAME] -C [USERNAME]
Important! Do NOT follow the instructions under the Windows section of the webpage as I have not been able to get it to work on my Windows10 desktop.
For All Users:Follow the instructions under the Linux and MACOS sections of the webpages below, even if you are a Windows user (read the above section on For Windows Users only)
Setup SSH keys on your local computer following instructions from [5]. Windows users, remember to remove ~/.ssh/Locate and copy your SSH keys on your local computer following instructions from [6]. Windows users, by default your keys are saved at C:\Users\your-windows-usernameYou must add this SSH key (from your computer) to your Google cloud platform account. You can either insert the key to the whole project following instructions from [7] or just for a particular VM following instructions from [8]. My personal preference is to add it to the specific VM just to be organized. Remember, the public SSH key that you need to copy is the contents of the .pub file. Windows users, it’s best if you open this file in Notepad and copy its contents.Now, open VSCode on your local computer. Press Ctrl+Shift+x on Windows to open the Extension manager in VSCode. In the search box, type remote-ssh, and install this extension.
Setup SSH keys on your local computer following instructions from [5]. Windows users, remember to remove ~/.ssh/
Locate and copy your SSH keys on your local computer following instructions from [6]. Windows users, by default your keys are saved at C:\Users\your-windows-username
You must add this SSH key (from your computer) to your Google cloud platform account. You can either insert the key to the whole project following instructions from [7] or just for a particular VM following instructions from [8]. My personal preference is to add it to the specific VM just to be organized. Remember, the public SSH key that you need to copy is the contents of the .pub file. Windows users, it’s best if you open this file in Notepad and copy its contents.
Now, open VSCode on your local computer. Press Ctrl+Shift+x on Windows to open the Extension manager in VSCode. In the search box, type remote-ssh, and install this extension.
5. Once the installation completes, press Ctrl+Shift+p (or Cmd+Shift+p on Mac) on your computer to bring up the Command Palette and type remote-ssh. A bunch of options should appear, as shown in the below image. Click the Add New SSH Host... option.
6. In the Enter SSH Connection Command prompt that pops up, type : ssh -i ~/.ssh/[KEY_FILENAME] [USERNAME]@[External IP] and press Enter. KEY_FILENAME and USERNAME are what you typed in step #1. External IP can be found from your GCP Compute Engine VM Instances page and is unique to each VM. Another prompt pops up, asking you to Select SSH configuration file to update. Just click the first one, and you should see Host Added! at the bottom right-hand corner of your VSCode window.
Important for Windows users!, instead of ~/.ssh/[KEY_FILENAME], you must type in the full path with \\. For example,ssh -i C:\\Users\\your-windows-username\\[KEY_FILENAME] [USERNAME]@[External IP]
7. Press Ctrl+Shift+p (or Cmd+Shift+p on Mac) to open up the Command Palette and type remote-ssh again. This time click on Connect to Host. Then select the IP address of your VM from the list that pops up. If you get another pop up about fingerprint, click Continue.
8. That’s it! Your local Visual Studio Code is now connected to your GCP VM! You can go ahead and click Open Folder or Open File, which will now display your files from the VM that can be edited directly from VSCode running locally on your computer.
I have tested the above steps on a Mac, Linux, and a Windows10 desktop. So, if you encountered any errors along the way, it’s most likely that you made one of the below common mistakes:
Your GCP VM is stopped. Startup your GCP VM and try again.
In Step# 6, you either provided the wrong KEY_FILENAME location or the incorrect USERNAME or the wrong External IP. Remember that if you don’t set Static IP for your GCP VM, then you potentially need to perform Step# 6 each time you stop and start your VM as the External IP address could change. Always provide the current External IP of your running VM.
You followed the Windows instructions from the webpages under [5], [6], [7], and [8]. DONT! Go back and redo all the steps following the Instructions under Linux and MACOS with the small modification I mentioned above
I hope you found this post helpful. If it did, please let me know below. Happy Coding!
References:[1] Download VSCode: https://code.visualstudio.com/[2] Download Anaconda to use Jupyter notebooks: https://www.anaconda.com/distribution/[3] Refactoring options in VSCode: https://code.visualstudio.com/docs/editor/refactoring[4] Start a GCP Compute Instance VM: https://cloud.google.com/compute/docs/quickstart-linux[5] Create SSH keys on your local computer: https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#createsshkeys[6] Locate and copy the SSH key from on local computer: https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#locatesshkeys[7] Adding project-wide SSH keys: https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#project-wide[8] Adding instance-level SSH keys: https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#instance-only[9] https://cloud.google.com/sdk/install
|
[
{
"code": null,
"e": 607,
"s": 172,
"text": "Visual Studio Code (or VSCode for short) is a powerful, multi-platform, free code editor that supports multiple programming languages [1]. Over the past two years, it has tremendously grown in popularity, as can be noticed from the meteoric rise in its Google search trends. In this post, I will share a method to use VSCode installed on your local computer to edit and run code located on a Google Cloud Virtual Machine. But first..."
},
{
"code": null,
"e": 1874,
"s": 607,
"text": "As a Data Scientist, why should you use VSCode when you have the convenience of the Jupyter notebook[2]? Well, if you are like me, then your typical day to day Data Science job involves two aspects. The first aspect is to run experiments for which you use the (in)famous Jupyter notebook. Jupyter is highly suitable for the kind of iterative, experimental workflow involved in the early phases of a Data Science project. The second aspect of a Data Scientist’s job starts once you have a product that you want to run in production (run for thousands or millions of times every day). In many organizations, you do not have the luxury of a dedicated production team. Even if you do have that luxury, it is good practice to refactor your code before passing it to the production team to ensure the product works as expected once deployed. This is where VSCode shines in the Data Science workflow! The details of using VSCode to refactor code from a Jupyter notebook deserve a standalone post to do it justice. However, [3] provides an excellent overview of the refactoring tools available in VSCode. A simple example is “Rename Symbol,” which allows you to rename a variable just once but automatically updates everywhere the variable appears in your code! Super handy!"
},
{
"code": null,
"e": 2343,
"s": 1874,
"text": "Let’s now get into the details of this post. Since you are reading this post, I assume you already have a GCP Compute Engine VM running, and you also have VSCode installed on your personal computer. If you don’t have both of these, then refer to [4] on how to set up a GCP Compute Engine VM and [1] to download and install VSCode on your local computer. Update: You must also have gcloud sdk installed and run gcloud init on your system following instructions from [9]"
},
{
"code": null,
"e": 2522,
"s": 2343,
"text": "Mac and Linux users can directly jump to the For All Users section of this post and follow from step #1 using the built-in terminal. Windows users need to take note of the below:"
},
{
"code": null,
"e": 2546,
"s": 2522,
"text": "For Windows Users only:"
},
{
"code": null,
"e": 2595,
"s": 2546,
"text": "From your start menu, startup Windows Powershell"
},
{
"code": null,
"e": 2827,
"s": 2595,
"text": "For all remaining steps under the For All Users section of this post, please follow the instructions under the Linux and MACOS section on the reference webpage. However, remember to remove the following wherever it appears: ~/.ssh/"
},
{
"code": null,
"e": 2902,
"s": 2827,
"text": "For example, if the Linux and MACOS section of the reference webpage says:"
},
{
"code": null,
"e": 2959,
"s": 2902,
"text": "ssh-keygen -t rsa -f ~/.ssh/[KEY_FILENAME] -C [USERNAME]"
},
{
"code": null,
"e": 3000,
"s": 2959,
"text": "Type this in Windows Powershell instead:"
},
{
"code": null,
"e": 3050,
"s": 3000,
"text": "ssh-keygen -t rsa -f [KEY_FILENAME] -C [USERNAME]"
},
{
"code": null,
"e": 3200,
"s": 3050,
"text": "Important! Do NOT follow the instructions under the Windows section of the webpage as I have not been able to get it to work on my Windows10 desktop."
},
{
"code": null,
"e": 3378,
"s": 3200,
"text": "For All Users:Follow the instructions under the Linux and MACOS sections of the webpages below, even if you are a Windows user (read the above section on For Windows Users only)"
},
{
"code": null,
"e": 4303,
"s": 3378,
"text": "Setup SSH keys on your local computer following instructions from [5]. Windows users, remember to remove ~/.ssh/Locate and copy your SSH keys on your local computer following instructions from [6]. Windows users, by default your keys are saved at C:\\Users\\your-windows-usernameYou must add this SSH key (from your computer) to your Google cloud platform account. You can either insert the key to the whole project following instructions from [7] or just for a particular VM following instructions from [8]. My personal preference is to add it to the specific VM just to be organized. Remember, the public SSH key that you need to copy is the contents of the .pub file. Windows users, it’s best if you open this file in Notepad and copy its contents.Now, open VSCode on your local computer. Press Ctrl+Shift+x on Windows to open the Extension manager in VSCode. In the search box, type remote-ssh, and install this extension."
},
{
"code": null,
"e": 4416,
"s": 4303,
"text": "Setup SSH keys on your local computer following instructions from [5]. Windows users, remember to remove ~/.ssh/"
},
{
"code": null,
"e": 4582,
"s": 4416,
"text": "Locate and copy your SSH keys on your local computer following instructions from [6]. Windows users, by default your keys are saved at C:\\Users\\your-windows-username"
},
{
"code": null,
"e": 5055,
"s": 4582,
"text": "You must add this SSH key (from your computer) to your Google cloud platform account. You can either insert the key to the whole project following instructions from [7] or just for a particular VM following instructions from [8]. My personal preference is to add it to the specific VM just to be organized. Remember, the public SSH key that you need to copy is the contents of the .pub file. Windows users, it’s best if you open this file in Notepad and copy its contents."
},
{
"code": null,
"e": 5231,
"s": 5055,
"text": "Now, open VSCode on your local computer. Press Ctrl+Shift+x on Windows to open the Extension manager in VSCode. In the search box, type remote-ssh, and install this extension."
},
{
"code": null,
"e": 5481,
"s": 5231,
"text": "5. Once the installation completes, press Ctrl+Shift+p (or Cmd+Shift+p on Mac) on your computer to bring up the Command Palette and type remote-ssh. A bunch of options should appear, as shown in the below image. Click the Add New SSH Host... option."
},
{
"code": null,
"e": 5965,
"s": 5481,
"text": "6. In the Enter SSH Connection Command prompt that pops up, type : ssh -i ~/.ssh/[KEY_FILENAME] [USERNAME]@[External IP] and press Enter. KEY_FILENAME and USERNAME are what you typed in step #1. External IP can be found from your GCP Compute Engine VM Instances page and is unique to each VM. Another prompt pops up, asking you to Select SSH configuration file to update. Just click the first one, and you should see Host Added! at the bottom right-hand corner of your VSCode window."
},
{
"code": null,
"e": 6162,
"s": 5965,
"text": "Important for Windows users!, instead of ~/.ssh/[KEY_FILENAME], you must type in the full path with \\\\. For example,ssh -i C:\\\\Users\\\\your-windows-username\\\\[KEY_FILENAME] [USERNAME]@[External IP]"
},
{
"code": null,
"e": 6429,
"s": 6162,
"text": "7. Press Ctrl+Shift+p (or Cmd+Shift+p on Mac) to open up the Command Palette and type remote-ssh again. This time click on Connect to Host. Then select the IP address of your VM from the list that pops up. If you get another pop up about fingerprint, click Continue."
},
{
"code": null,
"e": 6679,
"s": 6429,
"text": "8. That’s it! Your local Visual Studio Code is now connected to your GCP VM! You can go ahead and click Open Folder or Open File, which will now display your files from the VM that can be edited directly from VSCode running locally on your computer."
},
{
"code": null,
"e": 6865,
"s": 6679,
"text": "I have tested the above steps on a Mac, Linux, and a Windows10 desktop. So, if you encountered any errors along the way, it’s most likely that you made one of the below common mistakes:"
},
{
"code": null,
"e": 6924,
"s": 6865,
"text": "Your GCP VM is stopped. Startup your GCP VM and try again."
},
{
"code": null,
"e": 7280,
"s": 6924,
"text": "In Step# 6, you either provided the wrong KEY_FILENAME location or the incorrect USERNAME or the wrong External IP. Remember that if you don’t set Static IP for your GCP VM, then you potentially need to perform Step# 6 each time you stop and start your VM as the External IP address could change. Always provide the current External IP of your running VM."
},
{
"code": null,
"e": 7498,
"s": 7280,
"text": "You followed the Windows instructions from the webpages under [5], [6], [7], and [8]. DONT! Go back and redo all the steps following the Instructions under Linux and MACOS with the small modification I mentioned above"
},
{
"code": null,
"e": 7585,
"s": 7498,
"text": "I hope you found this post helpful. If it did, please let me know below. Happy Coding!"
}
] |
How to Convert SQL Query Results to a Pandas Dataframe | by Matt Przybyla | Towards Data Science
|
IntroductionToolsExampleSummaryReferences
Introduction
Tools
Example
Summary
References
As a data scientist, you may oftentimes have to pull data from a database table. This first step in gathering your dataset in the modeling process is commonly acquired from the results of SQL code. SQL is not usually the main language required to be a data scientist; however, it is important to practice and utilize for obtaining your dataset in some scenarios. There are some problems, though — going back and forth with your Python code, SQL, and sometimes, Jupyter Notebook, can be aggravating. There is a very simple process that helps to solve this issue. The solution is to write your SQL query in your Jupyter Notebook, then save that output by converting it to a pandas dataframe. Below, I will supply code and an example that displays this easy and beneficial process.
There are several key tools that make up this process. First, you will use the SQL query that you already originally had, then, using Python, will reference the pandas library for converting the output into a dataframe, all in your Jupyter Notebook.
SQL — Structured query language, most data analysts and data warehouse/database engineers use this language to pull data for reports and dataset development.
--return all columns from tableSELECT * FROM TABLE
Python — one of the main programming languages used by data scientists.
# display textprint('Hello, world!')
Pandas — a popular library used by data scientists to read in data from various sources. Static data can be read in as a CSV file. A live SQL connection can also be connected using pandas that will then be converted in a dataframe from its output. It is explained below in the example.
# creating and renaming a new a pandas dataframe columndf['new_column_name'] = df['original_column_name']
Jupyter Notebook — a platform/environment to run your Python code (as well as SQL) for your data science model.
In this example, I will be using a mock database to serve as a storage environment that a SQL query will reference.
First, import the pandas library and if you desire, create an alias ‘pd’ for shorthand notation. Next, create a credentials variable that stores:
database/SQL environment — PostgreSQL
username:password
data warehouse: database URL (IP address)
port number
database name
This variable will be a long string that is wrapped in quotation marks. The next cell in your Jupyter Notebook will be the SQL query itself. Pandas will be utilized to execute the query while also converting the output into a dataframe. The query is formatted by containing the statement with triple quotation marks. After the last quotation, a comma will be followed by the connection parameter that will equal your credentials variable.
Here is the code for this example (you will have to use your own credentials):
# import python libraryimport pandas as pd# assign a variable that contains a string of your credentialscredentials = "postgresql://username:password@your_sql_connection_url:port_number/database_name"# read in your SQL query results using pandasdataframe = pd.read_sql(""" SELECT column_1, column_2 FROM Table WHERE column_1 > number ORDER BY column_1 """, con = credentials)# return your first five rowsdataframe.head()
A closer look at how the code looks like in your Jupyter Notebook:
For more documentation on this pandas function, click here [4]. You can find more beneficial information regarding parameters there as well.
When creating a dataframe that will be used as your dataset, there are plenty of options to gather that data. Sometimes a CSV is read in, while a dataframe can be made by defining columns and values. However, in this case, we saw that you can query using SQL from your database and return those results as your data that is ultimately read in as your new dataframe. From there, you can follow your normal process in data science now that you have your dataframe. I hope you found this article helpful, thank you for reading!
[1] Photo by Tobias Fischer on Unsplash, (2017)
[2] Photo by Chris Ried on Unsplash, (2018)
[3] M.Przybyla, Jupyter Notebook screenshot, (2020)
[4] Pandas, pandas.read_sql, (2008–2014)
|
[
{
"code": null,
"e": 214,
"s": 172,
"text": "IntroductionToolsExampleSummaryReferences"
},
{
"code": null,
"e": 227,
"s": 214,
"text": "Introduction"
},
{
"code": null,
"e": 233,
"s": 227,
"text": "Tools"
},
{
"code": null,
"e": 241,
"s": 233,
"text": "Example"
},
{
"code": null,
"e": 249,
"s": 241,
"text": "Summary"
},
{
"code": null,
"e": 260,
"s": 249,
"text": "References"
},
{
"code": null,
"e": 1039,
"s": 260,
"text": "As a data scientist, you may oftentimes have to pull data from a database table. This first step in gathering your dataset in the modeling process is commonly acquired from the results of SQL code. SQL is not usually the main language required to be a data scientist; however, it is important to practice and utilize for obtaining your dataset in some scenarios. There are some problems, though — going back and forth with your Python code, SQL, and sometimes, Jupyter Notebook, can be aggravating. There is a very simple process that helps to solve this issue. The solution is to write your SQL query in your Jupyter Notebook, then save that output by converting it to a pandas dataframe. Below, I will supply code and an example that displays this easy and beneficial process."
},
{
"code": null,
"e": 1289,
"s": 1039,
"text": "There are several key tools that make up this process. First, you will use the SQL query that you already originally had, then, using Python, will reference the pandas library for converting the output into a dataframe, all in your Jupyter Notebook."
},
{
"code": null,
"e": 1447,
"s": 1289,
"text": "SQL — Structured query language, most data analysts and data warehouse/database engineers use this language to pull data for reports and dataset development."
},
{
"code": null,
"e": 1498,
"s": 1447,
"text": "--return all columns from tableSELECT * FROM TABLE"
},
{
"code": null,
"e": 1570,
"s": 1498,
"text": "Python — one of the main programming languages used by data scientists."
},
{
"code": null,
"e": 1607,
"s": 1570,
"text": "# display textprint('Hello, world!')"
},
{
"code": null,
"e": 1893,
"s": 1607,
"text": "Pandas — a popular library used by data scientists to read in data from various sources. Static data can be read in as a CSV file. A live SQL connection can also be connected using pandas that will then be converted in a dataframe from its output. It is explained below in the example."
},
{
"code": null,
"e": 1999,
"s": 1893,
"text": "# creating and renaming a new a pandas dataframe columndf['new_column_name'] = df['original_column_name']"
},
{
"code": null,
"e": 2111,
"s": 1999,
"text": "Jupyter Notebook — a platform/environment to run your Python code (as well as SQL) for your data science model."
},
{
"code": null,
"e": 2227,
"s": 2111,
"text": "In this example, I will be using a mock database to serve as a storage environment that a SQL query will reference."
},
{
"code": null,
"e": 2373,
"s": 2227,
"text": "First, import the pandas library and if you desire, create an alias ‘pd’ for shorthand notation. Next, create a credentials variable that stores:"
},
{
"code": null,
"e": 2411,
"s": 2373,
"text": "database/SQL environment — PostgreSQL"
},
{
"code": null,
"e": 2429,
"s": 2411,
"text": "username:password"
},
{
"code": null,
"e": 2471,
"s": 2429,
"text": "data warehouse: database URL (IP address)"
},
{
"code": null,
"e": 2483,
"s": 2471,
"text": "port number"
},
{
"code": null,
"e": 2497,
"s": 2483,
"text": "database name"
},
{
"code": null,
"e": 2936,
"s": 2497,
"text": "This variable will be a long string that is wrapped in quotation marks. The next cell in your Jupyter Notebook will be the SQL query itself. Pandas will be utilized to execute the query while also converting the output into a dataframe. The query is formatted by containing the statement with triple quotation marks. After the last quotation, a comma will be followed by the connection parameter that will equal your credentials variable."
},
{
"code": null,
"e": 3015,
"s": 2936,
"text": "Here is the code for this example (you will have to use your own credentials):"
},
{
"code": null,
"e": 3491,
"s": 3015,
"text": "# import python libraryimport pandas as pd# assign a variable that contains a string of your credentialscredentials = \"postgresql://username:password@your_sql_connection_url:port_number/database_name\"# read in your SQL query results using pandasdataframe = pd.read_sql(\"\"\" SELECT column_1, column_2 FROM Table WHERE column_1 > number ORDER BY column_1 \"\"\", con = credentials)# return your first five rowsdataframe.head()"
},
{
"code": null,
"e": 3558,
"s": 3491,
"text": "A closer look at how the code looks like in your Jupyter Notebook:"
},
{
"code": null,
"e": 3699,
"s": 3558,
"text": "For more documentation on this pandas function, click here [4]. You can find more beneficial information regarding parameters there as well."
},
{
"code": null,
"e": 4224,
"s": 3699,
"text": "When creating a dataframe that will be used as your dataset, there are plenty of options to gather that data. Sometimes a CSV is read in, while a dataframe can be made by defining columns and values. However, in this case, we saw that you can query using SQL from your database and return those results as your data that is ultimately read in as your new dataframe. From there, you can follow your normal process in data science now that you have your dataframe. I hope you found this article helpful, thank you for reading!"
},
{
"code": null,
"e": 4272,
"s": 4224,
"text": "[1] Photo by Tobias Fischer on Unsplash, (2017)"
},
{
"code": null,
"e": 4316,
"s": 4272,
"text": "[2] Photo by Chris Ried on Unsplash, (2018)"
},
{
"code": null,
"e": 4368,
"s": 4316,
"text": "[3] M.Przybyla, Jupyter Notebook screenshot, (2020)"
}
] |
Enumerate() in Python - GeeksforGeeks
|
11 Apr, 2022
Often, when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method.
Syntax:
enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is
to be started, by default it is 0
Python3
# python# Python program to illustrate# enumerate functionl1 = ["eat", "sleep", "repeat"]s1 = "geek" # creating enumerate objectsobj1 = enumerate(l1)obj2 = enumerate(s1) print ("Return type:", type(obj1))print (list(enumerate(l1))) # changing start index to 2 from 0print (list(enumerate(s1, 2)))
Return type:
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]
Using Enumerate object in loops:
Python3
# Python program to illustrate# enumerate function in loopsl1 = ["eat", "sleep", "repeat"] # printing the tuples in object directlyfor ele in enumerate(l1): print (ele) # changing index and printing separatelyfor count, ele in enumerate(l1, 100): print (count, ele) # getting desired output from tuplefor count, ele in enumerate(l1): print(count) print(ele)
(0, 'eat')
(1, 'sleep')
(2, 'repeat')
100 eat
101 sleep
102 repeat
0
eat
1
sleep
2
repeat
This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or have more information about the topic discussed above.
Rounak_agarwal
yashsanghvi301
devpagare002
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
Defaultdict in Python
Bar Plot in Matplotlib
How to Install PIP on Windows ?
Stack in Python
Deque in Python
Graph Plotting in Python | Set 1
Check if element exists in list in Python
Convert integer to string in Python
Python Classes and Objects
|
[
{
"code": null,
"e": 24072,
"s": 24044,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 24470,
"s": 24072,
"text": "Often, when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method. "
},
{
"code": null,
"e": 24479,
"s": 24470,
"text": "Syntax: "
},
{
"code": null,
"e": 24664,
"s": 24479,
"text": "enumerate(iterable, start=0)\n\nParameters:\nIterable: any object that supports iteration\nStart: the index value from which the counter is \n to be started, by default it is 0"
},
{
"code": null,
"e": 24674,
"s": 24666,
"text": "Python3"
},
{
"code": "# python# Python program to illustrate# enumerate functionl1 = [\"eat\", \"sleep\", \"repeat\"]s1 = \"geek\" # creating enumerate objectsobj1 = enumerate(l1)obj2 = enumerate(s1) print (\"Return type:\", type(obj1))print (list(enumerate(l1))) # changing start index to 2 from 0print (list(enumerate(s1, 2)))",
"e": 24974,
"s": 24674,
"text": null
},
{
"code": null,
"e": 25072,
"s": 24974,
"text": "Return type: \n[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]\n[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]\n"
},
{
"code": null,
"e": 25105,
"s": 25072,
"text": "Using Enumerate object in loops:"
},
{
"code": null,
"e": 25113,
"s": 25105,
"text": "Python3"
},
{
"code": "# Python program to illustrate# enumerate function in loopsl1 = [\"eat\", \"sleep\", \"repeat\"] # printing the tuples in object directlyfor ele in enumerate(l1): print (ele) # changing index and printing separatelyfor count, ele in enumerate(l1, 100): print (count, ele) # getting desired output from tuplefor count, ele in enumerate(l1): print(count) print(ele)",
"e": 25486,
"s": 25113,
"text": null
},
{
"code": null,
"e": 25577,
"s": 25486,
"text": "(0, 'eat')\n(1, 'sleep')\n(2, 'repeat')\n100 eat\n101 sleep\n102 repeat\n0\neat\n1\nsleep\n2\nrepeat\n"
},
{
"code": null,
"e": 25988,
"s": 25577,
"text": "This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or have more information about the topic discussed above. "
},
{
"code": null,
"e": 26003,
"s": 25988,
"text": "Rounak_agarwal"
},
{
"code": null,
"e": 26018,
"s": 26003,
"text": "yashsanghvi301"
},
{
"code": null,
"e": 26031,
"s": 26018,
"text": "devpagare002"
},
{
"code": null,
"e": 26057,
"s": 26031,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 26064,
"s": 26057,
"text": "Python"
},
{
"code": null,
"e": 26162,
"s": 26064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26171,
"s": 26162,
"text": "Comments"
},
{
"code": null,
"e": 26184,
"s": 26171,
"text": "Old Comments"
},
{
"code": null,
"e": 26205,
"s": 26184,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26227,
"s": 26205,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26250,
"s": 26227,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26282,
"s": 26250,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26298,
"s": 26282,
"text": "Stack in Python"
},
{
"code": null,
"e": 26314,
"s": 26298,
"text": "Deque in Python"
},
{
"code": null,
"e": 26347,
"s": 26314,
"text": "Graph Plotting in Python | Set 1"
},
{
"code": null,
"e": 26389,
"s": 26347,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26425,
"s": 26389,
"text": "Convert integer to string in Python"
}
] |
How to make your machine learning models more explainable | by Amol Mavuduru | Towards Data Science
|
One of the biggest challenges involved in solving business problems using machine learning is effectively explaining your model to a non-technical audience.
For example, if you work as a data scientist in an internship or a full-time position at a company, at some point you may have to present the results of your work to management. Similarly, if you decide to start a business based on machine learning, you will have to explain your models to stakeholders and investors in a way that makes sense. In both situations, your audience may lack a detailed understanding of machine learning algorithms. They probably aren’t concerned with the number of layers in your neural network or the number of trees in your random forest. These are the questions that really matter to them:
What business value does your model potentially add?
How well is your model performing?
Why should we trust your model?
If you can answer these questions, your audience will have a better understanding of your work as a data scientist and how it can provide tangible value.
The goal of this article is to demonstrate how you can answer these questions and leverage frameworks such as yellowbrick, LIME, and SHAP to provide visual explanations of your model’s performance and behavior regardless of how complex it is.
As data scientists and machine learning practitioners, we take pride in our models and the technical aspects of our work. If you have a really solid understanding of the statistics and math behind your work and the algorithms that you chose or the flashy Python libraries that you used, you may be tempted to impress your stakeholders by making these details the focus of your presentation. By doing this, you are essentially trying to sell the technology first, which is a great strategy for a technical conference, but not a very good strategy for a business pitch or a presentation to management.
“You’ve got to start with the customer experience and work backward to the technology. You can’t start with the technology then try to figure out where to sell it.” — Steve Jobs, Apple’s Worldwide Developers Conference, 1997.
Instead, you need to sell the business value of your work. In order to do this, think about how you can answer some of the following questions:
What problem is your machine learning model aimed at solving?
How can your machine learning model benefit the company?
How will your machine learning model benefit the company’s customers?
By answering these questions, you are making your work relevant to your audience.
There are two types of information that you should use when demonstrating your model’s performance to a general audience — performance metrics and visualizations. Performance metrics will summarize and quantify your model’s performance while visualizations will give your audience the bigger picture including little details that could have been missed when only looking at numerical metrics.
There are many performance metrics that data scientists like to use, ranging from simple and intuitive metrics like accuracy to more complex metrics like the root-mean-squared logarithmic error (RMSLE) or the weighted F1 score.
The most important thing to consider when choosing a metric is making sure that it is relevant in the context of the real-world problem that your model is trying to solve. To demonstrate this idea, consider the examples of real-world classification and regression problems listed below.
Determining whether or not a patient has diabetes (classification).
Predicting how many units of a product will be purchased by consumers (regression).
For the first problem, the consequences of a false positive (diagnosing someone who doesn’t have diabetes with diabetes) are not as serious as those of a false negative (failing to diagnose someone with diabetes). In this case, metrics such as accuracy and precision may be useful, but the one that is the most important is recall — which in this case measures the proportion of people with diabetes who were correctly diagnosed with diabetes. A model with a low recall will fail to diagnose many patients who actually have diabetes, leading to delays in treatment and further complications in patients. A model with a high recall will help prevent these negative outcomes.
For the second problem, let’s make the following assumptions (keep in mind this is a simplified example):
It costs $4 for the company to produce a unit of the product.
The company makes $6 when it sells a unit of the product.
If the company produces fewer units than the actual demand from customers, the product will go out of stock and it will only make money from the units that were produced.
In this situation, we might be tempted to use a typical regression metric like the R2 coefficient or the mean absolute error (MAE). But both metrics fail to answer the question that truly matters to the company — how much will they profit from producing the number of units that your model predicts they will need? We can use the equation below to compute the net profit that the model would produce for a given prediction:
Obviously, producing only 10 units has less potential for profit than producing 1000 units. For this reason, it might actually be better to scale this metric by computing the net profit margin or the ratio of the net profit to the initial profit generated by selling each unit of the product before taking costs into account:
This metric is something that company executives and stakeholders can easily interpret because it is relevant to the real-world problem that your model is trying to solve and it provides a clear picture of the value delivered by your model.
A visualization can often tell you much more than a single metric that summarizes the model’s performance across thousands of data points. While a picture is worth a thousand words, in data science a visualization may literally be worth a thousand numbers.
You can easily visualize your model’s performance using yellowbrick, a library that extends the Scikit-learn API and allows you to create performance visualizations. I have listed two examples of visualizations (one for classification, and one for regression) that can give your audience a more holistic picture of your model’s performance. You can find the code I used to create these visualizations on GitHub.
The class prediction error plot, which can be created using the yellowbrick API, is a bar graph with stacked bars showing the classes that were predicted for each actual class in the testing data. This plot is especially useful in multi-class classification problems and allows the audience to get a better view of the classification errors made by your model. In the example below, I created a class prediction error plot for a logistic regression model trained to predict the sentiment (positive or negative) of movie reviews using the famous IMDB Movie Review Dataset.
A residual plot is basically a scatterplot that shows the range of prediction errors (residuals) for your model for different predicted values. The yellowbrick API allows you to create a residual plot that also plots the distribution of the residuals for both the training and testing set. In the figure below, I created a residual plot for a neural network trained to predict housing prices using the California Housing Prices Dataset.
To answer this question, especially when dealing with a non-technical audience, you need to explain your model’s predictions in a way that doesn’t involve diving into complex mathematical details about your model.
LIME and SHAP are two useful Python libraries that you can use to visually explain the predictions generated by your model, which allows your audience to trust the logic that your model is using. In the sections below, I have provided visualizations and the code segments used to produce them. You can find the full code for these examples on GitHub.
LIME, a Python library created by researchers at the University of Washington, stands for Local Interpretable Model-agnostic Explanations. What this means is that LIME can provide understandable explanations of your model’s predictions on specific instances regardless of how complex the model is.
In the example below, I used the same neural network previously used to predict housing prices using the California Housing Prices Dataset and visualized the explanations for one particular prediction.
import limefrom lime.lime_tabular import LimeTabularExplainerexplainer = LimeTabularExplainer(X_train, feature_names=boston.feature_names, class_names=['price'], categorical_features=categorical_features, verbose=True, mode='regression')i = 25exp = explainer.explain_instance(X_test[i], neural_network_pipeline.predict, num_features=8)exp.show_in_notebook(show_table=True)
Here are some of the key features in the visualization above:
It provides the values of the eight most important features that influenced the model’s predictions.
It measures the impact of each feature on the prediction.
Features that contributed to an increase in the house price are in orange and those that contributed to a decrease are in blue.
It also gives us a general range of probable values for the target variable based on the model’s local behavior and shows us where the predicted value falls in this range.
We can also use LIME to explain the predictions of models that work with text data. In the example below, I visualized the explanations for a prediction generated by a logistic regression model used for classifying the sentiment of movie reviews.
from lime.lime_text import LimeTextExplaineri = 5class_names = ['negative', 'positive']explainer = LimeTextExplainer(class_names=class_names)exp = explainer.explain_instance(X_test[i], logistic_reg_pipeline.predict_proba, num_features=10)exp.show_in_notebook(text=True)
Based on the visualization above we can easily notice the following details:
The model clearly thinks the movie review is positive (with a 95 percent probability).
Words such as delightful, cool, hilarious, and awesome contributed to a higher probability of the review being positive.
Words such as poor, simply, and material contributed slightly to a higher probability of the review being negative.
These details align with our human expectations of what the model should be doing which allows us to trust it even if we don’t fully understand the math behind it.
SHAP (SHapley Additive exPlanations) is a similar Python library for model explanations, but it is a bit more complex than LIME both in terms of its usage and the information provided in its visualizations. SHAP borrows ideas from game theory, using the Shapley values defined in this paper to explain the output of machine learning models. Unlike LIME, SHAP also has specific modules for explaining different types of models but it also features model-agnostic explainers that work on all types of categories of models.
The code below demonstrates how to visualize the predictions of the same neural network in the previous example using the KernelExplainer module, which is designed to explain the output of any function.
import shapshap.initjs()explainer = shap.KernelExplainer(neural_network_pipeline.predict, X_train)shap_values = explainer.shap_values(X_test.iloc[25,:], nsamples=200)shap.force_plot(explainer.expected_value, shap_values, X_test.iloc[25,:])
The visualization above is interesting because it not only provides the value predicted by the model but also presents the competing influences of different features as arrows of different directions and lengths pushing the model’s prediction further from a base value.
SHAP can also be used on text data, but the process is a bit more complicated and the visual explanations for a single prediction are not as intuitive as those that can be created with LIME. The SHAP Explainer module can explain text-classification results by treating the text data as tabular data in the form of word counts or TF-IDF statistics for each word in a text document. In the example below, I used SHAP to create a visualization explaining the previous sentiment prediction generated by the logistic regression model.
X_train_processed = vectorizer.transform(X_train).toarray()X_test_processed = vectorizer.transform(X_test).toarray()explainer = shap.Explainer(logistic_reg_pipeline.steps[1][1], X_train_processed, feature_names=vectorizer.get_feature_names())shap_values = explainer(X_test_processed)i = 5shap.plots.force(shap_values[i])
If we compare this visualization to the one produced by LIME for the same movie review, we can see that it gives us similar information, but is less intuitive because it doesn’t highlight words in the text of the movie review. However, it still helps us see the influence of specific words on the model’s prediction.
SHAP also allows us to view the influence of individual words on the model’s predictions using a bee swarm plot as demonstrated below.
shap.plots.beeswarm(shap_values)
Based on this plot, we can tell that words such as great, best, and excellent in a movie review cause the model to conclude that a review is positive while words such as worst, bad, awful, waste, and boring cause the model to conclude that a review is negative. This visualization gives us more confidence in this model because it demonstrates that the model is using the same logic that we as humans would likely use when determining if a movie review is positive or negative. This is the key to building trust in machine learning models.
When explaining a machine learning model to an audience that is unfamiliar with the technical details of machine learning, always start by explaining the business value that your model can offer.
To explain your model’s performance results to your audience, use metrics that are meaningful in the context of the problem, and create visualizations that show the big picture of your model’s performance.
You can use LIME and SHAP to explain your model’s predictions in a way that allows your non-technical audience to trust your model.
As I mentioned earlier, please refer to this GitHub repository to find the full code that I used to train the models and create the corresponding visualizations used in this article.
B. Bengfort and R. Bilbro, Yellowbrick: Visualizing the Scikit-Learn Model Selection Process, (2019), Journal of Open Source Software.M. T. Ribeiro, S. Singh, and C. Guestrin, Why should I trust you?: Explaining the predictions of any classifier, (2016), 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining.S. M. Lundberg, S. Lee, A Unified Approach to Interpreting Model Predictions, (2017), Advances in Neural Information Processing Systems 30 (NIPS 2017).A. L. Maas, R. E. Daly, P. T. Pham, D. Huang, A. Y. Ng, and C. Potts, Learning Word Vectors for Sentiment Analysis, (2011), The 49th Annual Meeting of the Association for Computational Linguistics.R.K. Pace and R. Barry, Sparse Spatial Autoregressions, (1997), Statistics and Probability Letters.
B. Bengfort and R. Bilbro, Yellowbrick: Visualizing the Scikit-Learn Model Selection Process, (2019), Journal of Open Source Software.
M. T. Ribeiro, S. Singh, and C. Guestrin, Why should I trust you?: Explaining the predictions of any classifier, (2016), 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining.
S. M. Lundberg, S. Lee, A Unified Approach to Interpreting Model Predictions, (2017), Advances in Neural Information Processing Systems 30 (NIPS 2017).
A. L. Maas, R. E. Daly, P. T. Pham, D. Huang, A. Y. Ng, and C. Potts, Learning Word Vectors for Sentiment Analysis, (2011), The 49th Annual Meeting of the Association for Computational Linguistics.
R.K. Pace and R. Barry, Sparse Spatial Autoregressions, (1997), Statistics and Probability Letters.
|
[
{
"code": null,
"e": 329,
"s": 172,
"text": "One of the biggest challenges involved in solving business problems using machine learning is effectively explaining your model to a non-technical audience."
},
{
"code": null,
"e": 951,
"s": 329,
"text": "For example, if you work as a data scientist in an internship or a full-time position at a company, at some point you may have to present the results of your work to management. Similarly, if you decide to start a business based on machine learning, you will have to explain your models to stakeholders and investors in a way that makes sense. In both situations, your audience may lack a detailed understanding of machine learning algorithms. They probably aren’t concerned with the number of layers in your neural network or the number of trees in your random forest. These are the questions that really matter to them:"
},
{
"code": null,
"e": 1004,
"s": 951,
"text": "What business value does your model potentially add?"
},
{
"code": null,
"e": 1039,
"s": 1004,
"text": "How well is your model performing?"
},
{
"code": null,
"e": 1071,
"s": 1039,
"text": "Why should we trust your model?"
},
{
"code": null,
"e": 1225,
"s": 1071,
"text": "If you can answer these questions, your audience will have a better understanding of your work as a data scientist and how it can provide tangible value."
},
{
"code": null,
"e": 1468,
"s": 1225,
"text": "The goal of this article is to demonstrate how you can answer these questions and leverage frameworks such as yellowbrick, LIME, and SHAP to provide visual explanations of your model’s performance and behavior regardless of how complex it is."
},
{
"code": null,
"e": 2068,
"s": 1468,
"text": "As data scientists and machine learning practitioners, we take pride in our models and the technical aspects of our work. If you have a really solid understanding of the statistics and math behind your work and the algorithms that you chose or the flashy Python libraries that you used, you may be tempted to impress your stakeholders by making these details the focus of your presentation. By doing this, you are essentially trying to sell the technology first, which is a great strategy for a technical conference, but not a very good strategy for a business pitch or a presentation to management."
},
{
"code": null,
"e": 2294,
"s": 2068,
"text": "“You’ve got to start with the customer experience and work backward to the technology. You can’t start with the technology then try to figure out where to sell it.” — Steve Jobs, Apple’s Worldwide Developers Conference, 1997."
},
{
"code": null,
"e": 2438,
"s": 2294,
"text": "Instead, you need to sell the business value of your work. In order to do this, think about how you can answer some of the following questions:"
},
{
"code": null,
"e": 2500,
"s": 2438,
"text": "What problem is your machine learning model aimed at solving?"
},
{
"code": null,
"e": 2557,
"s": 2500,
"text": "How can your machine learning model benefit the company?"
},
{
"code": null,
"e": 2627,
"s": 2557,
"text": "How will your machine learning model benefit the company’s customers?"
},
{
"code": null,
"e": 2709,
"s": 2627,
"text": "By answering these questions, you are making your work relevant to your audience."
},
{
"code": null,
"e": 3102,
"s": 2709,
"text": "There are two types of information that you should use when demonstrating your model’s performance to a general audience — performance metrics and visualizations. Performance metrics will summarize and quantify your model’s performance while visualizations will give your audience the bigger picture including little details that could have been missed when only looking at numerical metrics."
},
{
"code": null,
"e": 3330,
"s": 3102,
"text": "There are many performance metrics that data scientists like to use, ranging from simple and intuitive metrics like accuracy to more complex metrics like the root-mean-squared logarithmic error (RMSLE) or the weighted F1 score."
},
{
"code": null,
"e": 3617,
"s": 3330,
"text": "The most important thing to consider when choosing a metric is making sure that it is relevant in the context of the real-world problem that your model is trying to solve. To demonstrate this idea, consider the examples of real-world classification and regression problems listed below."
},
{
"code": null,
"e": 3685,
"s": 3617,
"text": "Determining whether or not a patient has diabetes (classification)."
},
{
"code": null,
"e": 3769,
"s": 3685,
"text": "Predicting how many units of a product will be purchased by consumers (regression)."
},
{
"code": null,
"e": 4443,
"s": 3769,
"text": "For the first problem, the consequences of a false positive (diagnosing someone who doesn’t have diabetes with diabetes) are not as serious as those of a false negative (failing to diagnose someone with diabetes). In this case, metrics such as accuracy and precision may be useful, but the one that is the most important is recall — which in this case measures the proportion of people with diabetes who were correctly diagnosed with diabetes. A model with a low recall will fail to diagnose many patients who actually have diabetes, leading to delays in treatment and further complications in patients. A model with a high recall will help prevent these negative outcomes."
},
{
"code": null,
"e": 4549,
"s": 4443,
"text": "For the second problem, let’s make the following assumptions (keep in mind this is a simplified example):"
},
{
"code": null,
"e": 4611,
"s": 4549,
"text": "It costs $4 for the company to produce a unit of the product."
},
{
"code": null,
"e": 4669,
"s": 4611,
"text": "The company makes $6 when it sells a unit of the product."
},
{
"code": null,
"e": 4840,
"s": 4669,
"text": "If the company produces fewer units than the actual demand from customers, the product will go out of stock and it will only make money from the units that were produced."
},
{
"code": null,
"e": 5264,
"s": 4840,
"text": "In this situation, we might be tempted to use a typical regression metric like the R2 coefficient or the mean absolute error (MAE). But both metrics fail to answer the question that truly matters to the company — how much will they profit from producing the number of units that your model predicts they will need? We can use the equation below to compute the net profit that the model would produce for a given prediction:"
},
{
"code": null,
"e": 5590,
"s": 5264,
"text": "Obviously, producing only 10 units has less potential for profit than producing 1000 units. For this reason, it might actually be better to scale this metric by computing the net profit margin or the ratio of the net profit to the initial profit generated by selling each unit of the product before taking costs into account:"
},
{
"code": null,
"e": 5831,
"s": 5590,
"text": "This metric is something that company executives and stakeholders can easily interpret because it is relevant to the real-world problem that your model is trying to solve and it provides a clear picture of the value delivered by your model."
},
{
"code": null,
"e": 6088,
"s": 5831,
"text": "A visualization can often tell you much more than a single metric that summarizes the model’s performance across thousands of data points. While a picture is worth a thousand words, in data science a visualization may literally be worth a thousand numbers."
},
{
"code": null,
"e": 6500,
"s": 6088,
"text": "You can easily visualize your model’s performance using yellowbrick, a library that extends the Scikit-learn API and allows you to create performance visualizations. I have listed two examples of visualizations (one for classification, and one for regression) that can give your audience a more holistic picture of your model’s performance. You can find the code I used to create these visualizations on GitHub."
},
{
"code": null,
"e": 7072,
"s": 6500,
"text": "The class prediction error plot, which can be created using the yellowbrick API, is a bar graph with stacked bars showing the classes that were predicted for each actual class in the testing data. This plot is especially useful in multi-class classification problems and allows the audience to get a better view of the classification errors made by your model. In the example below, I created a class prediction error plot for a logistic regression model trained to predict the sentiment (positive or negative) of movie reviews using the famous IMDB Movie Review Dataset."
},
{
"code": null,
"e": 7509,
"s": 7072,
"text": "A residual plot is basically a scatterplot that shows the range of prediction errors (residuals) for your model for different predicted values. The yellowbrick API allows you to create a residual plot that also plots the distribution of the residuals for both the training and testing set. In the figure below, I created a residual plot for a neural network trained to predict housing prices using the California Housing Prices Dataset."
},
{
"code": null,
"e": 7723,
"s": 7509,
"text": "To answer this question, especially when dealing with a non-technical audience, you need to explain your model’s predictions in a way that doesn’t involve diving into complex mathematical details about your model."
},
{
"code": null,
"e": 8074,
"s": 7723,
"text": "LIME and SHAP are two useful Python libraries that you can use to visually explain the predictions generated by your model, which allows your audience to trust the logic that your model is using. In the sections below, I have provided visualizations and the code segments used to produce them. You can find the full code for these examples on GitHub."
},
{
"code": null,
"e": 8372,
"s": 8074,
"text": "LIME, a Python library created by researchers at the University of Washington, stands for Local Interpretable Model-agnostic Explanations. What this means is that LIME can provide understandable explanations of your model’s predictions on specific instances regardless of how complex the model is."
},
{
"code": null,
"e": 8574,
"s": 8372,
"text": "In the example below, I used the same neural network previously used to predict housing prices using the California Housing Prices Dataset and visualized the explanations for one particular prediction."
},
{
"code": null,
"e": 8974,
"s": 8574,
"text": "import limefrom lime.lime_tabular import LimeTabularExplainerexplainer = LimeTabularExplainer(X_train, feature_names=boston.feature_names, class_names=['price'], categorical_features=categorical_features, verbose=True, mode='regression')i = 25exp = explainer.explain_instance(X_test[i], neural_network_pipeline.predict, num_features=8)exp.show_in_notebook(show_table=True)"
},
{
"code": null,
"e": 9036,
"s": 8974,
"text": "Here are some of the key features in the visualization above:"
},
{
"code": null,
"e": 9137,
"s": 9036,
"text": "It provides the values of the eight most important features that influenced the model’s predictions."
},
{
"code": null,
"e": 9195,
"s": 9137,
"text": "It measures the impact of each feature on the prediction."
},
{
"code": null,
"e": 9323,
"s": 9195,
"text": "Features that contributed to an increase in the house price are in orange and those that contributed to a decrease are in blue."
},
{
"code": null,
"e": 9495,
"s": 9323,
"text": "It also gives us a general range of probable values for the target variable based on the model’s local behavior and shows us where the predicted value falls in this range."
},
{
"code": null,
"e": 9742,
"s": 9495,
"text": "We can also use LIME to explain the predictions of models that work with text data. In the example below, I visualized the explanations for a prediction generated by a logistic regression model used for classifying the sentiment of movie reviews."
},
{
"code": null,
"e": 10012,
"s": 9742,
"text": "from lime.lime_text import LimeTextExplaineri = 5class_names = ['negative', 'positive']explainer = LimeTextExplainer(class_names=class_names)exp = explainer.explain_instance(X_test[i], logistic_reg_pipeline.predict_proba, num_features=10)exp.show_in_notebook(text=True)"
},
{
"code": null,
"e": 10089,
"s": 10012,
"text": "Based on the visualization above we can easily notice the following details:"
},
{
"code": null,
"e": 10176,
"s": 10089,
"text": "The model clearly thinks the movie review is positive (with a 95 percent probability)."
},
{
"code": null,
"e": 10297,
"s": 10176,
"text": "Words such as delightful, cool, hilarious, and awesome contributed to a higher probability of the review being positive."
},
{
"code": null,
"e": 10413,
"s": 10297,
"text": "Words such as poor, simply, and material contributed slightly to a higher probability of the review being negative."
},
{
"code": null,
"e": 10577,
"s": 10413,
"text": "These details align with our human expectations of what the model should be doing which allows us to trust it even if we don’t fully understand the math behind it."
},
{
"code": null,
"e": 11098,
"s": 10577,
"text": "SHAP (SHapley Additive exPlanations) is a similar Python library for model explanations, but it is a bit more complex than LIME both in terms of its usage and the information provided in its visualizations. SHAP borrows ideas from game theory, using the Shapley values defined in this paper to explain the output of machine learning models. Unlike LIME, SHAP also has specific modules for explaining different types of models but it also features model-agnostic explainers that work on all types of categories of models."
},
{
"code": null,
"e": 11301,
"s": 11098,
"text": "The code below demonstrates how to visualize the predictions of the same neural network in the previous example using the KernelExplainer module, which is designed to explain the output of any function."
},
{
"code": null,
"e": 11541,
"s": 11301,
"text": "import shapshap.initjs()explainer = shap.KernelExplainer(neural_network_pipeline.predict, X_train)shap_values = explainer.shap_values(X_test.iloc[25,:], nsamples=200)shap.force_plot(explainer.expected_value, shap_values, X_test.iloc[25,:])"
},
{
"code": null,
"e": 11811,
"s": 11541,
"text": "The visualization above is interesting because it not only provides the value predicted by the model but also presents the competing influences of different features as arrows of different directions and lengths pushing the model’s prediction further from a base value."
},
{
"code": null,
"e": 12341,
"s": 11811,
"text": "SHAP can also be used on text data, but the process is a bit more complicated and the visual explanations for a single prediction are not as intuitive as those that can be created with LIME. The SHAP Explainer module can explain text-classification results by treating the text data as tabular data in the form of word counts or TF-IDF statistics for each word in a text document. In the example below, I used SHAP to create a visualization explaining the previous sentiment prediction generated by the logistic regression model."
},
{
"code": null,
"e": 12719,
"s": 12341,
"text": "X_train_processed = vectorizer.transform(X_train).toarray()X_test_processed = vectorizer.transform(X_test).toarray()explainer = shap.Explainer(logistic_reg_pipeline.steps[1][1], X_train_processed, feature_names=vectorizer.get_feature_names())shap_values = explainer(X_test_processed)i = 5shap.plots.force(shap_values[i])"
},
{
"code": null,
"e": 13036,
"s": 12719,
"text": "If we compare this visualization to the one produced by LIME for the same movie review, we can see that it gives us similar information, but is less intuitive because it doesn’t highlight words in the text of the movie review. However, it still helps us see the influence of specific words on the model’s prediction."
},
{
"code": null,
"e": 13171,
"s": 13036,
"text": "SHAP also allows us to view the influence of individual words on the model’s predictions using a bee swarm plot as demonstrated below."
},
{
"code": null,
"e": 13204,
"s": 13171,
"text": "shap.plots.beeswarm(shap_values)"
},
{
"code": null,
"e": 13744,
"s": 13204,
"text": "Based on this plot, we can tell that words such as great, best, and excellent in a movie review cause the model to conclude that a review is positive while words such as worst, bad, awful, waste, and boring cause the model to conclude that a review is negative. This visualization gives us more confidence in this model because it demonstrates that the model is using the same logic that we as humans would likely use when determining if a movie review is positive or negative. This is the key to building trust in machine learning models."
},
{
"code": null,
"e": 13940,
"s": 13744,
"text": "When explaining a machine learning model to an audience that is unfamiliar with the technical details of machine learning, always start by explaining the business value that your model can offer."
},
{
"code": null,
"e": 14146,
"s": 13940,
"text": "To explain your model’s performance results to your audience, use metrics that are meaningful in the context of the problem, and create visualizations that show the big picture of your model’s performance."
},
{
"code": null,
"e": 14278,
"s": 14146,
"text": "You can use LIME and SHAP to explain your model’s predictions in a way that allows your non-technical audience to trust your model."
},
{
"code": null,
"e": 14461,
"s": 14278,
"text": "As I mentioned earlier, please refer to this GitHub repository to find the full code that I used to train the models and create the corresponding visualizations used in this article."
},
{
"code": null,
"e": 15244,
"s": 14461,
"text": "B. Bengfort and R. Bilbro, Yellowbrick: Visualizing the Scikit-Learn Model Selection Process, (2019), Journal of Open Source Software.M. T. Ribeiro, S. Singh, and C. Guestrin, Why should I trust you?: Explaining the predictions of any classifier, (2016), 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining.S. M. Lundberg, S. Lee, A Unified Approach to Interpreting Model Predictions, (2017), Advances in Neural Information Processing Systems 30 (NIPS 2017).A. L. Maas, R. E. Daly, P. T. Pham, D. Huang, A. Y. Ng, and C. Potts, Learning Word Vectors for Sentiment Analysis, (2011), The 49th Annual Meeting of the Association for Computational Linguistics.R.K. Pace and R. Barry, Sparse Spatial Autoregressions, (1997), Statistics and Probability Letters."
},
{
"code": null,
"e": 15379,
"s": 15244,
"text": "B. Bengfort and R. Bilbro, Yellowbrick: Visualizing the Scikit-Learn Model Selection Process, (2019), Journal of Open Source Software."
},
{
"code": null,
"e": 15581,
"s": 15379,
"text": "M. T. Ribeiro, S. Singh, and C. Guestrin, Why should I trust you?: Explaining the predictions of any classifier, (2016), 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining."
},
{
"code": null,
"e": 15733,
"s": 15581,
"text": "S. M. Lundberg, S. Lee, A Unified Approach to Interpreting Model Predictions, (2017), Advances in Neural Information Processing Systems 30 (NIPS 2017)."
},
{
"code": null,
"e": 15931,
"s": 15733,
"text": "A. L. Maas, R. E. Daly, P. T. Pham, D. Huang, A. Y. Ng, and C. Potts, Learning Word Vectors for Sentiment Analysis, (2011), The 49th Annual Meeting of the Association for Computational Linguistics."
}
] |
JUnit - Plug with ANT
|
We will have an example to demonstrate how to run JUnit using ANT. Follow the steps given below.
Download Apache Ant based on the operating system you are working on.
Set the ANT_HOME environment variable to point to the base directory location, where the ANT libraries are stored on your machine. Let us assume the Ant libraries are stored in the folder apache-ant-1.8.4.
Windows
Set the environment variable ANT_HOME to C:\Program Files\Apache Software Foundation\apache-ant-1.8.4
Linux
export ANT_HOME = /usr/local/apache-ant-1.8.4
Mac
export ANT_HOME = /Library/apache-ant-1.8.4
Append Ant compiler location to the System Path as follows −
Download a JUnit Archive that suits your operating system.
Create a folder TestJunitWithAnt in C:\>JUNIT_WORKSPACE.
Create a folder TestJunitWithAnt in C:\>JUNIT_WORKSPACE.
Create a folder src in C:\>JUNIT_WORKSPACE>TestJunitWithAnt.
Create a folder src in C:\>JUNIT_WORKSPACE>TestJunitWithAnt.
Create a folder test in C:\>JUNIT_WORKSPACE>TestJunitWithAnt.
Create a folder test in C:\>JUNIT_WORKSPACE>TestJunitWithAnt.
Create a folder lib in C:\>JUNIT_WORKSPACE>TestJunitWithAnt.
Create a folder lib in C:\>JUNIT_WORKSPACE>TestJunitWithAnt.
Create MessageUtil class in C:\>JUNIT_WORKSPACE>TestJunitWithAnt> srcfolder.
Create MessageUtil class in C:\>JUNIT_WORKSPACE>TestJunitWithAnt> srcfolder.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
// prints the message
public String printMessage(){
System.out.println(message);
return message;
}
// add "Hi!" to the message
public String salutationMessage(){
message = "Hi!" + message;
System.out.println(message);
return message;
}
}
Create TestMessageUtil class in the folder C:\>JUNIT_WORKSPACE>TestJunitWithAnt>src.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
public class TestMessageUtil {
String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
assertEquals(message,messageUtil.printMessage());
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
Copy junit-4.10.jar onto the folder C:\>JUNIT_WORKSPACE>TestJunitWithAnt>lib.
We'll be using <junit> task in Ant to execute our JUnit test cases.
<project name = "JunitTest" default = "test" basedir = ".">
<property name = "testdir" location = "test" />
<property name = "srcdir" location = "src" />
<property name = "full-compile" value = "true" />
<path id = "classpath.base"/>
<path id = "classpath.test">
<pathelement location = "lib/junit-4.10.jar" />
<pathelement location = "${testdir}" />
<pathelement location = "${srcdir}" />
<path refid = "classpath.base" />
</path>
<target name = "clean" >
<delete verbose = "${full-compile}">
<fileset dir = "${testdir}" includes = "**/*.class" />
</delete>
</target>
<target name = "compile" depends = "clean">
<javac srcdir = "${srcdir}" destdir = "${testdir}"
verbose = "${full-compile}">
<classpath refid = "classpath.test"/>
</javac>
</target>
<target name = "test" depends = "compile">
<junit>
<classpath refid = "classpath.test" />
<formatter type = "brief" usefile = "false" />
<test name = "TestMessageUtil" />
</junit>
</target>
</project>
Run the following Ant command.
C:\JUNIT_WORKSPACE\TestJunitWithAnt>ant
Verify the output.
Buildfile: C:\JUNIT_WORKSPACE\TestJunitWithAnt\build.xml
clean:
compile:
[javac] Compiling 2 source files to C:\JUNIT_WORKSPACE\TestJunitWithAnt\test
[javac] [parsing started C:\JUNIT_WORKSPACE\TestJunitWithAnt\src\
MessageUtil.java]
[javac] [parsing completed 18ms]
[javac] [parsing started C:\JUNIT_WORKSPACE\TestJunitWithAnt\src\
TestMessageUtil.java]
[javac] [parsing completed 2ms]
[javac] [search path for source files: C:\JUNIT_WORKSPACE\
TestJunitWithAnt\src]
[javac] [loading java\lang\Object.class(java\lang:Object.class)]
[javac] [loading java\lang\String.class(java\lang:String.class)]
[javac] [loading org\junit\Test.class(org\junit:Test.class)]
[javac] [loading org\junit\Ignore.class(org\junit:Ignore.class)]
[javac] [loading org\junit\Assert.class(org\junit:Assert.class)]
[javac] [loading java\lang\annotation\Retention.class
(java\lang\annotation:Retention.class)]
[javac] [loading java\lang\annotation\RetentionPolicy.class
(java\lang\annotation:RetentionPolicy.class)]
[javac] [loading java\lang\annotation\Target.class
(java\lang\annotation:Target.class)]
[javac] [loading java\lang\annotation\ElementType.class
(java\lang\annotation:ElementType.class)]
[javac] [loading java\lang\annotation\Annotation.class
(java\lang\annotation:Annotation.class)]
[javac] [checking MessageUtil]
[javac] [loading java\lang\System.class(java\lang:System.class)]
[javac] [loading java\io\PrintStream.class(java\io:PrintStream.class)]
[javac] [loading java\io\FilterOutputStream.class
(java\io:FilterOutputStream.class)]
[javac] [loading java\io\OutputStream.class(java\io:OutputStream.class)]
[javac] [loading java\lang\StringBuilder.class
(java\lang:StringBuilder.class)]
[javac] [loading java\lang\AbstractStringBuilder.class
(java\lang:AbstractStringBuilder.class)]
[javac] [loading java\lang\CharSequence.class(java\lang:CharSequence.class)]
[javac] [loading java\io\Serializable.class(java\io:Serializable.class)]
[javac] [loading java\lang\Comparable.class(java\lang:Comparable.class)]
[javac] [loading java\lang\StringBuffer.class(java\lang:StringBuffer.class)]
[javac] [wrote C:\JUNIT_WORKSPACE\TestJunitWithAnt\test\MessageUtil.class]
[javac] [checking TestMessageUtil]
[javac] [wrote C:\JUNIT_WORKSPACE\TestJunitWithAnt\test\TestMessageUtil.class]
[javac] [total 281ms]
test:
[junit] Testsuite: TestMessageUtil
[junit] Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 0.008 sec
[junit]
[junit] ------------- Standard Output ---------------
[junit] Inside testPrintMessage()
[junit] Robert
[junit] Inside testSalutationMessage()
[junit] Hi!Robert
[junit] ------------- ---------------- ---------------
BUILD SUCCESSFUL
Total time: 0 seconds
24 Lectures
2.5 hours
Nishita Bhatt
56 Lectures
7.5 hours
Dinesh Varyani
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2069,
"s": 1972,
"text": "We will have an example to demonstrate how to run JUnit using ANT. Follow the steps given below."
},
{
"code": null,
"e": 2139,
"s": 2069,
"text": "Download Apache Ant based on the operating system you are working on."
},
{
"code": null,
"e": 2345,
"s": 2139,
"text": "Set the ANT_HOME environment variable to point to the base directory location, where the ANT libraries are stored on your machine. Let us assume the Ant libraries are stored in the folder apache-ant-1.8.4."
},
{
"code": null,
"e": 2353,
"s": 2345,
"text": "Windows"
},
{
"code": null,
"e": 2455,
"s": 2353,
"text": "Set the environment variable ANT_HOME to C:\\Program Files\\Apache Software Foundation\\apache-ant-1.8.4"
},
{
"code": null,
"e": 2461,
"s": 2455,
"text": "Linux"
},
{
"code": null,
"e": 2507,
"s": 2461,
"text": "export ANT_HOME = /usr/local/apache-ant-1.8.4"
},
{
"code": null,
"e": 2511,
"s": 2507,
"text": "Mac"
},
{
"code": null,
"e": 2555,
"s": 2511,
"text": "export ANT_HOME = /Library/apache-ant-1.8.4"
},
{
"code": null,
"e": 2616,
"s": 2555,
"text": "Append Ant compiler location to the System Path as follows −"
},
{
"code": null,
"e": 2675,
"s": 2616,
"text": "Download a JUnit Archive that suits your operating system."
},
{
"code": null,
"e": 2732,
"s": 2675,
"text": "Create a folder TestJunitWithAnt in C:\\>JUNIT_WORKSPACE."
},
{
"code": null,
"e": 2789,
"s": 2732,
"text": "Create a folder TestJunitWithAnt in C:\\>JUNIT_WORKSPACE."
},
{
"code": null,
"e": 2850,
"s": 2789,
"text": "Create a folder src in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt."
},
{
"code": null,
"e": 2911,
"s": 2850,
"text": "Create a folder src in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt."
},
{
"code": null,
"e": 2973,
"s": 2911,
"text": "Create a folder test in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt."
},
{
"code": null,
"e": 3035,
"s": 2973,
"text": "Create a folder test in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt."
},
{
"code": null,
"e": 3096,
"s": 3035,
"text": "Create a folder lib in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt."
},
{
"code": null,
"e": 3157,
"s": 3096,
"text": "Create a folder lib in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt."
},
{
"code": null,
"e": 3234,
"s": 3157,
"text": "Create MessageUtil class in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt> srcfolder."
},
{
"code": null,
"e": 3311,
"s": 3234,
"text": "Create MessageUtil class in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt> srcfolder."
},
{
"code": null,
"e": 3847,
"s": 3311,
"text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message; \n }\n\n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n\n // add \"Hi!\" to the message\n public String salutationMessage(){\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n } \n} \t"
},
{
"code": null,
"e": 3932,
"s": 3847,
"text": "Create TestMessageUtil class in the folder C:\\>JUNIT_WORKSPACE>TestJunitWithAnt>src."
},
{
"code": null,
"e": 4528,
"s": 3932,
"text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestMessageUtil {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test\n public void testPrintMessage() {\t\n System.out.println(\"Inside testPrintMessage()\"); \n assertEquals(message,messageUtil.printMessage());\n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n}"
},
{
"code": null,
"e": 4606,
"s": 4528,
"text": "Copy junit-4.10.jar onto the folder C:\\>JUNIT_WORKSPACE>TestJunitWithAnt>lib."
},
{
"code": null,
"e": 4674,
"s": 4606,
"text": "We'll be using <junit> task in Ant to execute our JUnit test cases."
},
{
"code": null,
"e": 5788,
"s": 4674,
"text": "<project name = \"JunitTest\" default = \"test\" basedir = \".\">\n <property name = \"testdir\" location = \"test\" />\n <property name = \"srcdir\" location = \"src\" />\n <property name = \"full-compile\" value = \"true\" />\n\t\n <path id = \"classpath.base\"/>\n\t\n <path id = \"classpath.test\">\n <pathelement location = \"lib/junit-4.10.jar\" />\n <pathelement location = \"${testdir}\" />\n <pathelement location = \"${srcdir}\" />\n <path refid = \"classpath.base\" />\n </path>\n\t\n <target name = \"clean\" >\n <delete verbose = \"${full-compile}\">\n <fileset dir = \"${testdir}\" includes = \"**/*.class\" />\n </delete>\n </target>\n\t\n <target name = \"compile\" depends = \"clean\">\n <javac srcdir = \"${srcdir}\" destdir = \"${testdir}\" \n verbose = \"${full-compile}\">\n <classpath refid = \"classpath.test\"/>\n </javac>\n </target>\n\t\n <target name = \"test\" depends = \"compile\">\n <junit>\n <classpath refid = \"classpath.test\" />\n <formatter type = \"brief\" usefile = \"false\" />\n <test name = \"TestMessageUtil\" />\n </junit>\n </target>\n\t\n</project>"
},
{
"code": null,
"e": 5819,
"s": 5788,
"text": "Run the following Ant command."
},
{
"code": null,
"e": 5860,
"s": 5819,
"text": "C:\\JUNIT_WORKSPACE\\TestJunitWithAnt>ant\n"
},
{
"code": null,
"e": 5879,
"s": 5860,
"text": "Verify the output."
},
{
"code": null,
"e": 8744,
"s": 5879,
"text": "Buildfile: C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\build.xml\n\nclean: \n\ncompile: \n [javac] Compiling 2 source files to C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\test\n [javac] [parsing started C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\src\\\n MessageUtil.java]\n [javac] [parsing completed 18ms]\n [javac] [parsing started C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\src\\\n TestMessageUtil.java]\n [javac] [parsing completed 2ms]\n [javac] [search path for source files: C:\\JUNIT_WORKSPACE\\\n TestJunitWithAnt\\src] \n [javac] [loading java\\lang\\Object.class(java\\lang:Object.class)]\n [javac] [loading java\\lang\\String.class(java\\lang:String.class)]\n [javac] [loading org\\junit\\Test.class(org\\junit:Test.class)]\n [javac] [loading org\\junit\\Ignore.class(org\\junit:Ignore.class)]\n [javac] [loading org\\junit\\Assert.class(org\\junit:Assert.class)]\n [javac] [loading java\\lang\\annotation\\Retention.class\n (java\\lang\\annotation:Retention.class)]\n [javac] [loading java\\lang\\annotation\\RetentionPolicy.class\n (java\\lang\\annotation:RetentionPolicy.class)]\n [javac] [loading java\\lang\\annotation\\Target.class\n (java\\lang\\annotation:Target.class)]\n [javac] [loading java\\lang\\annotation\\ElementType.class\n (java\\lang\\annotation:ElementType.class)]\n [javac] [loading java\\lang\\annotation\\Annotation.class\n (java\\lang\\annotation:Annotation.class)]\n [javac] [checking MessageUtil]\n [javac] [loading java\\lang\\System.class(java\\lang:System.class)]\n [javac] [loading java\\io\\PrintStream.class(java\\io:PrintStream.class)]\n [javac] [loading java\\io\\FilterOutputStream.class\n (java\\io:FilterOutputStream.class)]\n [javac] [loading java\\io\\OutputStream.class(java\\io:OutputStream.class)]\n [javac] [loading java\\lang\\StringBuilder.class\n (java\\lang:StringBuilder.class)]\n [javac] [loading java\\lang\\AbstractStringBuilder.class\n (java\\lang:AbstractStringBuilder.class)]\n [javac] [loading java\\lang\\CharSequence.class(java\\lang:CharSequence.class)]\n [javac] [loading java\\io\\Serializable.class(java\\io:Serializable.class)]\n [javac] [loading java\\lang\\Comparable.class(java\\lang:Comparable.class)]\n [javac] [loading java\\lang\\StringBuffer.class(java\\lang:StringBuffer.class)]\n [javac] [wrote C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\test\\MessageUtil.class]\n [javac] [checking TestMessageUtil]\n [javac] [wrote C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\test\\TestMessageUtil.class]\n [javac] [total 281ms]\n\ntest:\n [junit] Testsuite: TestMessageUtil\n [junit] Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 0.008 sec\n [junit]\n [junit] ------------- Standard Output ---------------\n [junit] Inside testPrintMessage()\n [junit] Robert\n [junit] Inside testSalutationMessage()\n [junit] Hi!Robert\n [junit] ------------- ---------------- ---------------\n\nBUILD SUCCESSFUL\nTotal time: 0 seconds\n"
},
{
"code": null,
"e": 8779,
"s": 8744,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8794,
"s": 8779,
"text": " Nishita Bhatt"
},
{
"code": null,
"e": 8829,
"s": 8794,
"text": "\n 56 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8845,
"s": 8829,
"text": " Dinesh Varyani"
},
{
"code": null,
"e": 8852,
"s": 8845,
"text": " Print"
},
{
"code": null,
"e": 8863,
"s": 8852,
"text": " Add Notes"
}
] |
User-defined Exceptions in C# with Example
|
An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Define your own exception. User-defined exception classes are derived from the Exception class.
The following is an example −
using System;
namespace UserDefinedException {
class TestFitness {
static void Main(string[] args) {
Fitness f = new Fitness();
try {
f.showResult();
} catch(FitnessTestFailedException e) {
Console.WriteLine("User defined exception: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class FitnessTestFailedException: Exception {
public FitnessTestFailedException(string message): base(message) {
}
}
public class Fitness {
int points = 0;
public void showResult() {
if(points < 110) {
throw (new FitnessTestFailedException("Player failed the fitness test!"));
} else {
Console.WriteLine("Player passed the fitness test!");
}
}
}
Above, we created a user-defined exception −
public class FitnessTestFailedException: Exception {
public FitnessTestFailedException(string message): base(message) {
}
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero."
},
{
"code": null,
"e": 1369,
"s": 1273,
"text": "Define your own exception. User-defined exception classes are derived from the Exception class."
},
{
"code": null,
"e": 1399,
"s": 1369,
"text": "The following is an example −"
},
{
"code": null,
"e": 2178,
"s": 1399,
"text": "using System;\n\nnamespace UserDefinedException {\n class TestFitness {\n static void Main(string[] args) {\n Fitness f = new Fitness();\n try {\n f.showResult();\n } catch(FitnessTestFailedException e) {\n Console.WriteLine(\"User defined exception: {0}\", e.Message);\n }\n Console.ReadKey();\n }\n }\n}\n\npublic class FitnessTestFailedException: Exception {\n public FitnessTestFailedException(string message): base(message) {\n }\n}\n\npublic class Fitness {\n int points = 0;\n\n public void showResult() {\n \n if(points < 110) {\n throw (new FitnessTestFailedException(\"Player failed the fitness test!\"));\n } else {\n Console.WriteLine(\"Player passed the fitness test!\");\n }\n }\n}"
},
{
"code": null,
"e": 2223,
"s": 2178,
"text": "Above, we created a user-defined exception −"
},
{
"code": null,
"e": 2348,
"s": 2223,
"text": "public class FitnessTestFailedException: Exception {\n public FitnessTestFailedException(string message): base(message) {\n}"
}
] |
How to handle action event for JComboBox in Java?
|
The following is an example to handle action event for JComboBox in Java:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> combo = new JComboBox<>(new String[] { "One","Two", "Three","Four","Five", "Six" });
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
combo.addItem("New");
}
});
frame.add(combo);
frame.add(add, BorderLayout.NORTH);
frame.setSize(500, 100);
frame.setVisible(true);
}
}
Now, we have the following items:
Now, click “Add” above to add a new item on runtime. After clicking, a new item would be visible in the bottom as shown in the following screenshot:
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "The following is an example to handle action event for JComboBox in Java:"
},
{
"code": null,
"e": 1967,
"s": 1136,
"text": "import java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JComboBox<String> combo = new JComboBox<>(new String[] { \"One\",\"Two\", \"Three\",\"Four\",\"Five\", \"Six\" });\n JButton add = new JButton(\"Add\");\n add.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n combo.addItem(\"New\");\n }\n });\n frame.add(combo);\n frame.add(add, BorderLayout.NORTH);\n frame.setSize(500, 100);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2001,
"s": 1967,
"text": "Now, we have the following items:"
},
{
"code": null,
"e": 2150,
"s": 2001,
"text": "Now, click “Add” above to add a new item on runtime. After clicking, a new item would be visible in the bottom as shown in the following screenshot:"
}
] |
java.time.LocalTime.format() Method Example
|
The java.time.LocalTime.format(DateTimeFormatter formatter) method formats this time using the specified formatter.
Following is the declaration for java.time.LocalTime.format(DateTimeFormatter formatter) method.
public String format(DateTimeFormatter formatter)
formatter − the formatter to use, not null.
the formatted date string, not null.
DateTimeException − if an error occurs during printing.
The following example shows the usage of java.time.LocalTime.format(DateTimeFormatter formatter) method.
package com.tutorialspoint;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class LocalTimeDemo {
public static void main(String[] args) {
LocalTime time = LocalTime.parse("12:30:30");
System.out.println(time);
DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME;
System.out.println(formatter.format(time));
}
}
Let us compile and run the above program, this will produce the following result −
12:30:30
12:30:30
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2031,
"s": 1915,
"text": "The java.time.LocalTime.format(DateTimeFormatter formatter) method formats this time using the specified formatter."
},
{
"code": null,
"e": 2128,
"s": 2031,
"text": "Following is the declaration for java.time.LocalTime.format(DateTimeFormatter formatter) method."
},
{
"code": null,
"e": 2179,
"s": 2128,
"text": "public String format(DateTimeFormatter formatter)\n"
},
{
"code": null,
"e": 2223,
"s": 2179,
"text": "formatter − the formatter to use, not null."
},
{
"code": null,
"e": 2260,
"s": 2223,
"text": "the formatted date string, not null."
},
{
"code": null,
"e": 2316,
"s": 2260,
"text": "DateTimeException − if an error occurs during printing."
},
{
"code": null,
"e": 2421,
"s": 2316,
"text": "The following example shows the usage of java.time.LocalTime.format(DateTimeFormatter formatter) method."
},
{
"code": null,
"e": 2805,
"s": 2421,
"text": "package com.tutorialspoint;\n\nimport java.time.LocalTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class LocalTimeDemo {\n public static void main(String[] args) {\n\n LocalTime time = LocalTime.parse(\"12:30:30\");\n System.out.println(time); \n DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME;\n System.out.println(formatter.format(time)); \n }\n}"
},
{
"code": null,
"e": 2888,
"s": 2805,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2907,
"s": 2888,
"text": "12:30:30\n12:30:30\n"
},
{
"code": null,
"e": 2914,
"s": 2907,
"text": " Print"
},
{
"code": null,
"e": 2925,
"s": 2914,
"text": " Add Notes"
}
] |
Difference Between Data Scientist & MLOps Engineer | Towards Data Science
|
IntroductionData ScientistMachine Learning Operations EngineerSimilarities and DifferencesSummaryReferences
Introduction
Data Scientist
Machine Learning Operations Engineer
Similarities and Differences
Summary
References
While I have written articles on Data Science and Machine Learning Engineering roles, I wanted to compare the specific positions of Data Scientists and Machine Learning Operations Engineers, often referred to as MLOps Engineers. Machine Learning itself can be incredibly broad, so as a result, a newer career has emerged that solely focuses on the operations rather than the research that goes behind the algorithms themselves. Data Scientists ironically focus more on Machine Learning algorithms than does an MLOps Engineer. You could even go as far as saying an MLOps Engineer is a Software Engineer traditionally who has then added the specialization of deployment and production parts of the overall Data Science process. I will be diving deeper into these two positions, so keep on reading if you would like to learn more about the common differences and similarities between these two prominent careers.
As more specializations emerge in the field of Data Science, the role of Data Scientist is becoming broader. Therefore, you can expect my experiences to include some differences from yours or your expectations. However, I have studied Data Science in a variety of forms, and want to give the best overview of the position, along with key points that distinguish it from an MLOps role. A Data Scientist can best be described as a business-focused scientist who studies, finds, and solves problems within the company with Machine Learning algorithms. Your main goal will usually be to make a process both more accurate and efficient compared to how it was previously done. This definition sounds quite similar to a Software Engineering role, however, this position focuses of course more on the algorithms and how they work as the solutions rather than more hand-made and object-oriented programming code solutions.
Here is a general process that a Data Scientist can expect at their company over the course of several days to several months:
explore the data and products of your companymeet with stakeholders who have previously identified pain points in the business either internally or externallycome up with a business problem statement that highlights the issue at handobtain the data in some way, usually with SQL or working with a Data Engineer to digest newer data from other, new sourcesperform exploratory data analysis on your chosen datasetcompare several models compared to a baseline modelchoose your main algorithmidentify key features — feature engineeringremove redundant and unnecessary featurespossibly create an ensemble or stepwise algorithm processaccount for outlierssave your model and test in a dev environmentprovide details on accuracy or error metricspresent how much you can save the company, and how you can make the product better
explore the data and products of your company
meet with stakeholders who have previously identified pain points in the business either internally or externally
come up with a business problem statement that highlights the issue at hand
obtain the data in some way, usually with SQL or working with a Data Engineer to digest newer data from other, new sources
perform exploratory data analysis on your chosen dataset
compare several models compared to a baseline model
choose your main algorithm
identify key features — feature engineering
remove redundant and unnecessary features
possibly create an ensemble or stepwise algorithm process
account for outliers
save your model and test in a dev environment
provide details on accuracy or error metrics
present how much you can save the company, and how you can make the product better
Sometimes these steps in the Data Science process that I have listed above can change from time to time. You want to keep in mind that all businesses are different but if you follow a process of data creation, algorithm comparison, testing, and presentation of results, you will be a great Data Scientist for your company.
Now, what happens after step 14? That is where the next role comes into play. However, also keep in mind that not every company can afford or deems it necessary to have an MLOps Engineer alongside a Data Scientist. But, if you are lucky enough to have a more full Data Science team, you can focus on those steps from above, and the MLOps Engineer can focus on the next steps that I will describe below. Of course, it would be great if you could do both, and a lot of people work in both roles. Sometimes though, it can be more beneficial if a Data Scientist focuses more on the Machine Learning algorithms and the MLOps Engineer focuses on the deployment, pipelines, and productionalization of your Data Science model. It can help you to improve on your model's accuracy or reduce its error metrics when you do not have to worry about the software engineering heavy aspects of implementing the actual model into your business, phone application, and other parts of your company’s software.
MLOps Engineer
The Machine Learning Operations Engineer role, often referred to as an MLOps Engineer is important and beneficial to have on your Data Science team. You may find yourself switching to this role if you are a current Sofware Engineer and want to work cross-functionally, yet specifically with Machine Learning algorithms, or you could be a current Data Scientist who has knowledge of how the algorithms work, but want to focus more on the Software Engineering, Data Engineering, and deployment of models. You may first be handed a Data Science model that has been developed by a Data Scientist when you are working as an MLOps Engineer. You will also work on seeing on how to optimize some of the Data Science code, since you will be more Sofware Engineering focused with more object-oriented programming experience (once again, this experience may be different for you or your company, but generally, I have seen MLOps being more proficient in programming).
So, in general, as an MLOps Engineer, you can expect to work with Data Scientists to connect the gap from testing to production within your company software with the practice of both Data Engineering and DevOps tools.
Here is a general process that an MLOps Engineer can expect at their company over the course of several days to several months:
study the general concepts of the Machine Learning algorithm(s) usedunderstand the business problem and the Data Science solutionunderstand how often the model would need to be trained, tested, and deployedhow many predictions will you make and when?but more importantly (the Data Scientists can work on steps 2–4 as well), see how you can use your expertise to automate the whole workflowalso, to implement the model within the app or software of your company (e.g., inserting model results hourly into a table that shows into a UI that a consumer sees)ultimately optimize the model itself with Data Engineering techniques like data storage and OOP improvementswork on versioning (like Git/GitHub) and monitoring of training/predictionscode repository creation or efficiency
study the general concepts of the Machine Learning algorithm(s) used
understand the business problem and the Data Science solution
understand how often the model would need to be trained, tested, and deployed
how many predictions will you make and when?
but more importantly (the Data Scientists can work on steps 2–4 as well), see how you can use your expertise to automate the whole workflow
also, to implement the model within the app or software of your company (e.g., inserting model results hourly into a table that shows into a UI that a consumer sees)
ultimately optimize the model itself with Data Engineering techniques like data storage and OOP improvements
work on versioning (like Git/GitHub) and monitoring of training/predictions
code repository creation or efficiency
As you can see, some of the steps of the overall Data Science process overlap between Data Scientists and MLOps Engineers. They often work closely together to achieve the ultimate goal of the company running a beneficial Machine Learning algorithm or Data Science model.
You can expect these roles to be different from company to company, but, in general, there are key similarities and differences between these two positions that can mostly be applied anywhere. If you are capable of performing both, then great for you, but at some point, the scalable method will require both Data Science and MLOps Engineering to be working together — by more than one person.
Here are the similarities that you can expect between the two roles
both need to understand the business, problem, and solution (at least a high-level overview)
both need to know the data of the company well and where to look for more if needed
both usually are proficient in SQL and Python
both usually work with Git and GitHub (version control and repositories)
both need to know the concept of training and testing
Here are the differences that you can expect between the two roles
Data Scientists usually work or develop in their Jupyter Notebooks or something similar
Data Scientists tend to be more research-oriented whereas...
MLOps focus on production-ready code and programming
MLOps work with DevOp tools like Docker and CircleCi
as well as with AWS/EC2, Google Cloud, or Kubeflow
MLOps tend to focus more on OOP
Data Scientists must know how the actual Machine Learning algorithm works (e.g., gradient descent, regularizations, parameter tuning, etc.)
Data Scientists focus on choosing and creating the algorithm (e.g., is it supervised, is it unsupervised, is it regression, is it classification?)
Schooling/education is different. Usually, a Masters in Data Science for Data Scientists and a Software Engineering Bachelors for MLOps Engineers — more and more undergrad schools are creating Data Science Bachelor’s degrees.
It is also beneficial to have specialization in Software Engineering for Data Scientists, and Machine Learning for MLOps, in terms of certifications or other forms of shorter educational experiences so that both roles are more well-rounded and can collaborate together better.
Above are just some of the key similarities and differences between Data Scientists and Machine Learning Operations Engineers. There are much more, and if you are currently in one of these roles you may experience something similar or different to what I described. Overall, if you are in a different role and are choosing between these two, you cannot go wrong. It ultimately depends on your preferences and what you excel in. For example, I would summarize Data Science as statistics, Machine Learning, and business analysis, and for Machine Learning Operations Engineering, I would summarize the role as a combination of Software Engineering, Machine Learning deployment expertise, Data Engineering, and DevOps. Data Scientists focus on the algorithms at hand, whereas MLOps works on the deployment and automation of the algorithm.
As you can see, both roles require a few different skills and have different goals, but at the same time, they share a plethora of skills, and ultimately the main goal is the same. I personally like the role of Data Scientist more than MLOps, however, I find myself learning more and more MLOps tools and practices every day. I do strive to be aware of all that an MLOps person would know so that I can slowly become more efficient (and it is interesting). Both positions are highly critical to the company, so if you want to have a positive impact on your company, then pursuing one of these roles would be a great idea.
Overall, here are both roles summarized
Data Scientists: business analysis, research, data, statistics, and Machine Learning algorithmsMLOps Engineer: programming, Software Engineering, productionaliztion, DevOps, and automation
I hope you found this article both interesting and useful. Keep in mind this article is based on my opinion and personal experiences with both roles. If you disagree or agree, feel free to comment down below why and the specific things you would add. Do you like being a Data Scientist more, or an MLOps Engineer more? Do you think they should be consolidated into one role? Is there really a difference? It would be interesting to receive some insight from others so that everyone can learn from others in order to find out the best representation of the similarities and differences between Data Science and Machine Learning Operations Engineering. Thank you for reading and feel free to check out my profile or read other articles and contact me if you have any questions about any of them.
Here is another article I have written covering Data Science versus Business Analytics [5]:
towardsdatascience.com
[1] Photo by LinkedIn Sales Navigator on Unsplash, (2020)
[2] Photo by Álvaro Bernal on Unsplash, (2019)
[3] Photo by Jefferson Santos on Unsplash, (2017)
[4] Photo by Veronica Benavides on Unsplash, (2017)
[5] M.Przybyla, Data Scientist vs Business Analyst. Here’s the Difference, (2020
|
[
{
"code": null,
"e": 280,
"s": 172,
"text": "IntroductionData ScientistMachine Learning Operations EngineerSimilarities and DifferencesSummaryReferences"
},
{
"code": null,
"e": 293,
"s": 280,
"text": "Introduction"
},
{
"code": null,
"e": 308,
"s": 293,
"text": "Data Scientist"
},
{
"code": null,
"e": 345,
"s": 308,
"text": "Machine Learning Operations Engineer"
},
{
"code": null,
"e": 374,
"s": 345,
"text": "Similarities and Differences"
},
{
"code": null,
"e": 382,
"s": 374,
"text": "Summary"
},
{
"code": null,
"e": 393,
"s": 382,
"text": "References"
},
{
"code": null,
"e": 1303,
"s": 393,
"text": "While I have written articles on Data Science and Machine Learning Engineering roles, I wanted to compare the specific positions of Data Scientists and Machine Learning Operations Engineers, often referred to as MLOps Engineers. Machine Learning itself can be incredibly broad, so as a result, a newer career has emerged that solely focuses on the operations rather than the research that goes behind the algorithms themselves. Data Scientists ironically focus more on Machine Learning algorithms than does an MLOps Engineer. You could even go as far as saying an MLOps Engineer is a Software Engineer traditionally who has then added the specialization of deployment and production parts of the overall Data Science process. I will be diving deeper into these two positions, so keep on reading if you would like to learn more about the common differences and similarities between these two prominent careers."
},
{
"code": null,
"e": 2217,
"s": 1303,
"text": "As more specializations emerge in the field of Data Science, the role of Data Scientist is becoming broader. Therefore, you can expect my experiences to include some differences from yours or your expectations. However, I have studied Data Science in a variety of forms, and want to give the best overview of the position, along with key points that distinguish it from an MLOps role. A Data Scientist can best be described as a business-focused scientist who studies, finds, and solves problems within the company with Machine Learning algorithms. Your main goal will usually be to make a process both more accurate and efficient compared to how it was previously done. This definition sounds quite similar to a Software Engineering role, however, this position focuses of course more on the algorithms and how they work as the solutions rather than more hand-made and object-oriented programming code solutions."
},
{
"code": null,
"e": 2344,
"s": 2217,
"text": "Here is a general process that a Data Scientist can expect at their company over the course of several days to several months:"
},
{
"code": null,
"e": 3165,
"s": 2344,
"text": "explore the data and products of your companymeet with stakeholders who have previously identified pain points in the business either internally or externallycome up with a business problem statement that highlights the issue at handobtain the data in some way, usually with SQL or working with a Data Engineer to digest newer data from other, new sourcesperform exploratory data analysis on your chosen datasetcompare several models compared to a baseline modelchoose your main algorithmidentify key features — feature engineeringremove redundant and unnecessary featurespossibly create an ensemble or stepwise algorithm processaccount for outlierssave your model and test in a dev environmentprovide details on accuracy or error metricspresent how much you can save the company, and how you can make the product better"
},
{
"code": null,
"e": 3211,
"s": 3165,
"text": "explore the data and products of your company"
},
{
"code": null,
"e": 3325,
"s": 3211,
"text": "meet with stakeholders who have previously identified pain points in the business either internally or externally"
},
{
"code": null,
"e": 3401,
"s": 3325,
"text": "come up with a business problem statement that highlights the issue at hand"
},
{
"code": null,
"e": 3524,
"s": 3401,
"text": "obtain the data in some way, usually with SQL or working with a Data Engineer to digest newer data from other, new sources"
},
{
"code": null,
"e": 3581,
"s": 3524,
"text": "perform exploratory data analysis on your chosen dataset"
},
{
"code": null,
"e": 3633,
"s": 3581,
"text": "compare several models compared to a baseline model"
},
{
"code": null,
"e": 3660,
"s": 3633,
"text": "choose your main algorithm"
},
{
"code": null,
"e": 3704,
"s": 3660,
"text": "identify key features — feature engineering"
},
{
"code": null,
"e": 3746,
"s": 3704,
"text": "remove redundant and unnecessary features"
},
{
"code": null,
"e": 3804,
"s": 3746,
"text": "possibly create an ensemble or stepwise algorithm process"
},
{
"code": null,
"e": 3825,
"s": 3804,
"text": "account for outliers"
},
{
"code": null,
"e": 3871,
"s": 3825,
"text": "save your model and test in a dev environment"
},
{
"code": null,
"e": 3916,
"s": 3871,
"text": "provide details on accuracy or error metrics"
},
{
"code": null,
"e": 3999,
"s": 3916,
"text": "present how much you can save the company, and how you can make the product better"
},
{
"code": null,
"e": 4322,
"s": 3999,
"text": "Sometimes these steps in the Data Science process that I have listed above can change from time to time. You want to keep in mind that all businesses are different but if you follow a process of data creation, algorithm comparison, testing, and presentation of results, you will be a great Data Scientist for your company."
},
{
"code": null,
"e": 5312,
"s": 4322,
"text": "Now, what happens after step 14? That is where the next role comes into play. However, also keep in mind that not every company can afford or deems it necessary to have an MLOps Engineer alongside a Data Scientist. But, if you are lucky enough to have a more full Data Science team, you can focus on those steps from above, and the MLOps Engineer can focus on the next steps that I will describe below. Of course, it would be great if you could do both, and a lot of people work in both roles. Sometimes though, it can be more beneficial if a Data Scientist focuses more on the Machine Learning algorithms and the MLOps Engineer focuses on the deployment, pipelines, and productionalization of your Data Science model. It can help you to improve on your model's accuracy or reduce its error metrics when you do not have to worry about the software engineering heavy aspects of implementing the actual model into your business, phone application, and other parts of your company’s software."
},
{
"code": null,
"e": 5327,
"s": 5312,
"text": "MLOps Engineer"
},
{
"code": null,
"e": 6284,
"s": 5327,
"text": "The Machine Learning Operations Engineer role, often referred to as an MLOps Engineer is important and beneficial to have on your Data Science team. You may find yourself switching to this role if you are a current Sofware Engineer and want to work cross-functionally, yet specifically with Machine Learning algorithms, or you could be a current Data Scientist who has knowledge of how the algorithms work, but want to focus more on the Software Engineering, Data Engineering, and deployment of models. You may first be handed a Data Science model that has been developed by a Data Scientist when you are working as an MLOps Engineer. You will also work on seeing on how to optimize some of the Data Science code, since you will be more Sofware Engineering focused with more object-oriented programming experience (once again, this experience may be different for you or your company, but generally, I have seen MLOps being more proficient in programming)."
},
{
"code": null,
"e": 6502,
"s": 6284,
"text": "So, in general, as an MLOps Engineer, you can expect to work with Data Scientists to connect the gap from testing to production within your company software with the practice of both Data Engineering and DevOps tools."
},
{
"code": null,
"e": 6630,
"s": 6502,
"text": "Here is a general process that an MLOps Engineer can expect at their company over the course of several days to several months:"
},
{
"code": null,
"e": 7406,
"s": 6630,
"text": "study the general concepts of the Machine Learning algorithm(s) usedunderstand the business problem and the Data Science solutionunderstand how often the model would need to be trained, tested, and deployedhow many predictions will you make and when?but more importantly (the Data Scientists can work on steps 2–4 as well), see how you can use your expertise to automate the whole workflowalso, to implement the model within the app or software of your company (e.g., inserting model results hourly into a table that shows into a UI that a consumer sees)ultimately optimize the model itself with Data Engineering techniques like data storage and OOP improvementswork on versioning (like Git/GitHub) and monitoring of training/predictionscode repository creation or efficiency"
},
{
"code": null,
"e": 7475,
"s": 7406,
"text": "study the general concepts of the Machine Learning algorithm(s) used"
},
{
"code": null,
"e": 7537,
"s": 7475,
"text": "understand the business problem and the Data Science solution"
},
{
"code": null,
"e": 7615,
"s": 7537,
"text": "understand how often the model would need to be trained, tested, and deployed"
},
{
"code": null,
"e": 7660,
"s": 7615,
"text": "how many predictions will you make and when?"
},
{
"code": null,
"e": 7800,
"s": 7660,
"text": "but more importantly (the Data Scientists can work on steps 2–4 as well), see how you can use your expertise to automate the whole workflow"
},
{
"code": null,
"e": 7966,
"s": 7800,
"text": "also, to implement the model within the app or software of your company (e.g., inserting model results hourly into a table that shows into a UI that a consumer sees)"
},
{
"code": null,
"e": 8075,
"s": 7966,
"text": "ultimately optimize the model itself with Data Engineering techniques like data storage and OOP improvements"
},
{
"code": null,
"e": 8151,
"s": 8075,
"text": "work on versioning (like Git/GitHub) and monitoring of training/predictions"
},
{
"code": null,
"e": 8190,
"s": 8151,
"text": "code repository creation or efficiency"
},
{
"code": null,
"e": 8461,
"s": 8190,
"text": "As you can see, some of the steps of the overall Data Science process overlap between Data Scientists and MLOps Engineers. They often work closely together to achieve the ultimate goal of the company running a beneficial Machine Learning algorithm or Data Science model."
},
{
"code": null,
"e": 8855,
"s": 8461,
"text": "You can expect these roles to be different from company to company, but, in general, there are key similarities and differences between these two positions that can mostly be applied anywhere. If you are capable of performing both, then great for you, but at some point, the scalable method will require both Data Science and MLOps Engineering to be working together — by more than one person."
},
{
"code": null,
"e": 8923,
"s": 8855,
"text": "Here are the similarities that you can expect between the two roles"
},
{
"code": null,
"e": 9016,
"s": 8923,
"text": "both need to understand the business, problem, and solution (at least a high-level overview)"
},
{
"code": null,
"e": 9100,
"s": 9016,
"text": "both need to know the data of the company well and where to look for more if needed"
},
{
"code": null,
"e": 9146,
"s": 9100,
"text": "both usually are proficient in SQL and Python"
},
{
"code": null,
"e": 9219,
"s": 9146,
"text": "both usually work with Git and GitHub (version control and repositories)"
},
{
"code": null,
"e": 9273,
"s": 9219,
"text": "both need to know the concept of training and testing"
},
{
"code": null,
"e": 9340,
"s": 9273,
"text": "Here are the differences that you can expect between the two roles"
},
{
"code": null,
"e": 9428,
"s": 9340,
"text": "Data Scientists usually work or develop in their Jupyter Notebooks or something similar"
},
{
"code": null,
"e": 9489,
"s": 9428,
"text": "Data Scientists tend to be more research-oriented whereas..."
},
{
"code": null,
"e": 9542,
"s": 9489,
"text": "MLOps focus on production-ready code and programming"
},
{
"code": null,
"e": 9595,
"s": 9542,
"text": "MLOps work with DevOp tools like Docker and CircleCi"
},
{
"code": null,
"e": 9646,
"s": 9595,
"text": "as well as with AWS/EC2, Google Cloud, or Kubeflow"
},
{
"code": null,
"e": 9678,
"s": 9646,
"text": "MLOps tend to focus more on OOP"
},
{
"code": null,
"e": 9818,
"s": 9678,
"text": "Data Scientists must know how the actual Machine Learning algorithm works (e.g., gradient descent, regularizations, parameter tuning, etc.)"
},
{
"code": null,
"e": 9965,
"s": 9818,
"text": "Data Scientists focus on choosing and creating the algorithm (e.g., is it supervised, is it unsupervised, is it regression, is it classification?)"
},
{
"code": null,
"e": 10191,
"s": 9965,
"text": "Schooling/education is different. Usually, a Masters in Data Science for Data Scientists and a Software Engineering Bachelors for MLOps Engineers — more and more undergrad schools are creating Data Science Bachelor’s degrees."
},
{
"code": null,
"e": 10468,
"s": 10191,
"text": "It is also beneficial to have specialization in Software Engineering for Data Scientists, and Machine Learning for MLOps, in terms of certifications or other forms of shorter educational experiences so that both roles are more well-rounded and can collaborate together better."
},
{
"code": null,
"e": 11303,
"s": 10468,
"text": "Above are just some of the key similarities and differences between Data Scientists and Machine Learning Operations Engineers. There are much more, and if you are currently in one of these roles you may experience something similar or different to what I described. Overall, if you are in a different role and are choosing between these two, you cannot go wrong. It ultimately depends on your preferences and what you excel in. For example, I would summarize Data Science as statistics, Machine Learning, and business analysis, and for Machine Learning Operations Engineering, I would summarize the role as a combination of Software Engineering, Machine Learning deployment expertise, Data Engineering, and DevOps. Data Scientists focus on the algorithms at hand, whereas MLOps works on the deployment and automation of the algorithm."
},
{
"code": null,
"e": 11925,
"s": 11303,
"text": "As you can see, both roles require a few different skills and have different goals, but at the same time, they share a plethora of skills, and ultimately the main goal is the same. I personally like the role of Data Scientist more than MLOps, however, I find myself learning more and more MLOps tools and practices every day. I do strive to be aware of all that an MLOps person would know so that I can slowly become more efficient (and it is interesting). Both positions are highly critical to the company, so if you want to have a positive impact on your company, then pursuing one of these roles would be a great idea."
},
{
"code": null,
"e": 11965,
"s": 11925,
"text": "Overall, here are both roles summarized"
},
{
"code": null,
"e": 12154,
"s": 11965,
"text": "Data Scientists: business analysis, research, data, statistics, and Machine Learning algorithmsMLOps Engineer: programming, Software Engineering, productionaliztion, DevOps, and automation"
},
{
"code": null,
"e": 12948,
"s": 12154,
"text": "I hope you found this article both interesting and useful. Keep in mind this article is based on my opinion and personal experiences with both roles. If you disagree or agree, feel free to comment down below why and the specific things you would add. Do you like being a Data Scientist more, or an MLOps Engineer more? Do you think they should be consolidated into one role? Is there really a difference? It would be interesting to receive some insight from others so that everyone can learn from others in order to find out the best representation of the similarities and differences between Data Science and Machine Learning Operations Engineering. Thank you for reading and feel free to check out my profile or read other articles and contact me if you have any questions about any of them."
},
{
"code": null,
"e": 13040,
"s": 12948,
"text": "Here is another article I have written covering Data Science versus Business Analytics [5]:"
},
{
"code": null,
"e": 13063,
"s": 13040,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13121,
"s": 13063,
"text": "[1] Photo by LinkedIn Sales Navigator on Unsplash, (2020)"
},
{
"code": null,
"e": 13169,
"s": 13121,
"text": "[2] Photo by Álvaro Bernal on Unsplash, (2019)"
},
{
"code": null,
"e": 13219,
"s": 13169,
"text": "[3] Photo by Jefferson Santos on Unsplash, (2017)"
},
{
"code": null,
"e": 13271,
"s": 13219,
"text": "[4] Photo by Veronica Benavides on Unsplash, (2017)"
}
] |
What is the difference between int and integer in MySQL?
|
The int is the synonym of integer in MySQL 5.0. Here is the demo display both int and integer internally represents int(11).
Creating a table with int datatype
mysql> create table IntDemo
-> (
-> Id int
-> );
Query OK, 0 rows affected (1.04 sec)
Here is description of the table. The query is as follows
mysql> desc IntDemo;
The following is the output
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| Id | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.06 sec)
Look at the column type, which is int(11). Now it stores the same range as defined for integer. The query to insert record is as follows
mysql> insert into IntDemo values(2147483647);
Query OK, 1 row affected (0.20 sec)
mysql> insert into IntDemo values(-2147483648);
Query OK, 1 row affected (0.42 sec)
Display all records from the table using select statement. The query is as follows
mysql> select *from IntDemo;
The following is the output
+-------------+
| Id |
+-------------+
| 2147483647 |
| -2147483648 |
+-------------+
2 rows in set (0.00 sec)
Creating a table with data type integer.
The query to create a table is as follows
mysql> create table IntegerDemo
-> (
-> Id integer
-> );
Query OK, 0 rows affected (0.93 sec)
Check the description of the table using desc command.
mysql> desc IntegerDemo;
The following is the output
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| Id | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
Insert record in the table using insert command. The integer takes the same range as int. The query is as follows
mysql> insert into IntegerDemo values(2147483647);
Query OK, 1 row affected (0.11 sec)
mysql> insert into IntegerDemo values(-2147483648);
Query OK, 1 row affected (0.27 sec)
Display all records from the table using select statement. The query is as follows
mysql> select *from IntegerDemo;
The following is the output
+-------------+
| Id |
+-------------+
| 2147483647 |
| -2147483648 |
+-------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1187,
"s": 1062,
"text": "The int is the synonym of integer in MySQL 5.0. Here is the demo display both int and integer internally represents int(11)."
},
{
"code": null,
"e": 1222,
"s": 1187,
"text": "Creating a table with int datatype"
},
{
"code": null,
"e": 1317,
"s": 1222,
"text": "mysql> create table IntDemo\n -> (\n -> Id int\n -> );\nQuery OK, 0 rows affected (1.04 sec)"
},
{
"code": null,
"e": 1375,
"s": 1317,
"text": "Here is description of the table. The query is as follows"
},
{
"code": null,
"e": 1396,
"s": 1375,
"text": "mysql> desc IntDemo;"
},
{
"code": null,
"e": 1424,
"s": 1396,
"text": "The following is the output"
},
{
"code": null,
"e": 1703,
"s": 1424,
"text": "+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| Id | int(11) | YES | | NULL | |\n+-------+---------+------+-----+---------+-------+\n1 row in set (0.06 sec)"
},
{
"code": null,
"e": 1840,
"s": 1703,
"text": "Look at the column type, which is int(11). Now it stores the same range as defined for integer. The query to insert record is as follows"
},
{
"code": null,
"e": 2008,
"s": 1840,
"text": "mysql> insert into IntDemo values(2147483647);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into IntDemo values(-2147483648);\nQuery OK, 1 row affected (0.42 sec)"
},
{
"code": null,
"e": 2091,
"s": 2008,
"text": "Display all records from the table using select statement. The query is as follows"
},
{
"code": null,
"e": 2120,
"s": 2091,
"text": "mysql> select *from IntDemo;"
},
{
"code": null,
"e": 2148,
"s": 2120,
"text": "The following is the output"
},
{
"code": null,
"e": 2269,
"s": 2148,
"text": "+-------------+\n| Id |\n+-------------+\n| 2147483647 |\n| -2147483648 |\n+-------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2310,
"s": 2269,
"text": "Creating a table with data type integer."
},
{
"code": null,
"e": 2352,
"s": 2310,
"text": "The query to create a table is as follows"
},
{
"code": null,
"e": 2455,
"s": 2352,
"text": "mysql> create table IntegerDemo\n -> (\n -> Id integer\n -> );\nQuery OK, 0 rows affected (0.93 sec)"
},
{
"code": null,
"e": 2510,
"s": 2455,
"text": "Check the description of the table using desc command."
},
{
"code": null,
"e": 2535,
"s": 2510,
"text": "mysql> desc IntegerDemo;"
},
{
"code": null,
"e": 2563,
"s": 2535,
"text": "The following is the output"
},
{
"code": null,
"e": 2842,
"s": 2563,
"text": "+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| Id | int(11) | YES | | NULL | |\n+-------+---------+------+-----+---------+-------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2956,
"s": 2842,
"text": "Insert record in the table using insert command. The integer takes the same range as int. The query is as follows"
},
{
"code": null,
"e": 3132,
"s": 2956,
"text": "mysql> insert into IntegerDemo values(2147483647);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into IntegerDemo values(-2147483648);\nQuery OK, 1 row affected (0.27 sec)"
},
{
"code": null,
"e": 3215,
"s": 3132,
"text": "Display all records from the table using select statement. The query is as follows"
},
{
"code": null,
"e": 3248,
"s": 3215,
"text": "mysql> select *from IntegerDemo;"
},
{
"code": null,
"e": 3276,
"s": 3248,
"text": "The following is the output"
},
{
"code": null,
"e": 3397,
"s": 3276,
"text": "+-------------+\n| Id |\n+-------------+\n| 2147483647 |\n| -2147483648 |\n+-------------+\n2 rows in set (0.00 sec)"
}
] |
How to change Azure Subscription in PowerShell?
|
To change the azure subscription using PowerShell, we can use the Select-AZSubscription command. When you use this command, you can use either the subscription ID, Subscription Name, or the Tenant ID.
With Subscription Name,
Select-AzSubscription -SubscriptionName 'Visual Studio'
With TenantID,
Select-AzSubscription -Tenant 'XXXX-XXXXX-XXXXXXX-XXXX'
With Subscription ID,
Select-AzSubscription -SubscriptionId 'XXXX-XXXXX-XXXXXXX-XXXX'
Sometimes on console messages will appear that one or more subscriptions are active. In that case, you can switch the other subscription using the Set-AZContext command and you can use subscription ID or the Name for it.
Set-AzContext -SubscriptionId "xxxx-xxxx-xxxx-xxxx"
Or
Set-AzContext -SubscriptionName "Visual Studio"
|
[
{
"code": null,
"e": 1263,
"s": 1062,
"text": "To change the azure subscription using PowerShell, we can use the Select-AZSubscription command. When you use this command, you can use either the subscription ID, Subscription Name, or the Tenant ID."
},
{
"code": null,
"e": 1287,
"s": 1263,
"text": "With Subscription Name,"
},
{
"code": null,
"e": 1343,
"s": 1287,
"text": "Select-AzSubscription -SubscriptionName 'Visual Studio'"
},
{
"code": null,
"e": 1358,
"s": 1343,
"text": "With TenantID,"
},
{
"code": null,
"e": 1414,
"s": 1358,
"text": "Select-AzSubscription -Tenant 'XXXX-XXXXX-XXXXXXX-XXXX'"
},
{
"code": null,
"e": 1436,
"s": 1414,
"text": "With Subscription ID,"
},
{
"code": null,
"e": 1500,
"s": 1436,
"text": "Select-AzSubscription -SubscriptionId 'XXXX-XXXXX-XXXXXXX-XXXX'"
},
{
"code": null,
"e": 1721,
"s": 1500,
"text": "Sometimes on console messages will appear that one or more subscriptions are active. In that case, you can switch the other subscription using the Set-AZContext command and you can use subscription ID or the Name for it."
},
{
"code": null,
"e": 1774,
"s": 1721,
"text": "Set-AzContext -SubscriptionId \"xxxx-xxxx-xxxx-xxxx\"\n"
},
{
"code": null,
"e": 1777,
"s": 1774,
"text": "Or"
},
{
"code": null,
"e": 1825,
"s": 1777,
"text": "Set-AzContext -SubscriptionName \"Visual Studio\""
}
] |
Int64.GetHashCode Method in C# with Examples - GeeksforGeeks
|
04 Apr, 2019
Int64.GetHashCode method is used to get the HashCode for the current Int64 instance.
Syntax: public override int GetHashCode ();
Return Value: This method returns a 32-bit signed integer hash code.
Below programs illustrate the use of the above discussed-method:
Example 1:
// C# program to illustrate the// Int64.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // Taking Int64 variable // i.e. long data type long s1 = 458732523; // Getting the hash code for Int64 // using GetHashCode() method int result = s1.GetHashCode(); // Display the HashCode Console.WriteLine("HashCode for Int64 is: {0}", result); }}
HashCode for Int64 is: 458732523
Example 2:
// C# program to illustrate the// Int64.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // using result() Method result(Int64.MinValue); result(Int64.MaxValue); } // result() method public static void result(long val) { // using GetHashCode() method int code = val.GetHashCode(); // Display the hashcode Console.WriteLine("HashCode for {0} is {1}", val, code); }}
HashCode for -9223372036854775808 is -2147483648
HashCode for 9223372036854775807 is -2147483648
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int64.gethashcode?view=netframework-4.7.2
CSharp-Int64-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
|
[
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 23996,
"s": 23911,
"text": "Int64.GetHashCode method is used to get the HashCode for the current Int64 instance."
},
{
"code": null,
"e": 24040,
"s": 23996,
"text": "Syntax: public override int GetHashCode ();"
},
{
"code": null,
"e": 24109,
"s": 24040,
"text": "Return Value: This method returns a 32-bit signed integer hash code."
},
{
"code": null,
"e": 24174,
"s": 24109,
"text": "Below programs illustrate the use of the above discussed-method:"
},
{
"code": null,
"e": 24185,
"s": 24174,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the// Int64.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // Taking Int64 variable // i.e. long data type long s1 = 458732523; // Getting the hash code for Int64 // using GetHashCode() method int result = s1.GetHashCode(); // Display the HashCode Console.WriteLine(\"HashCode for Int64 is: {0}\", result); }}",
"e": 24687,
"s": 24185,
"text": null
},
{
"code": null,
"e": 24721,
"s": 24687,
"text": "HashCode for Int64 is: 458732523\n"
},
{
"code": null,
"e": 24732,
"s": 24721,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the// Int64.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // using result() Method result(Int64.MinValue); result(Int64.MaxValue); } // result() method public static void result(long val) { // using GetHashCode() method int code = val.GetHashCode(); // Display the hashcode Console.WriteLine(\"HashCode for {0} is {1}\", val, code); }}",
"e": 25258,
"s": 24732,
"text": null
},
{
"code": null,
"e": 25356,
"s": 25258,
"text": "HashCode for -9223372036854775808 is -2147483648\nHashCode for 9223372036854775807 is -2147483648\n"
},
{
"code": null,
"e": 25367,
"s": 25356,
"text": "Reference:"
},
{
"code": null,
"e": 25460,
"s": 25367,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.int64.gethashcode?view=netframework-4.7.2"
},
{
"code": null,
"e": 25480,
"s": 25460,
"text": "CSharp-Int64-Struct"
},
{
"code": null,
"e": 25494,
"s": 25480,
"text": "CSharp-method"
},
{
"code": null,
"e": 25497,
"s": 25494,
"text": "C#"
},
{
"code": null,
"e": 25595,
"s": 25497,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25604,
"s": 25595,
"text": "Comments"
},
{
"code": null,
"e": 25617,
"s": 25604,
"text": "Old Comments"
},
{
"code": null,
"e": 25657,
"s": 25617,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 25680,
"s": 25657,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25708,
"s": 25680,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25730,
"s": 25708,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 25747,
"s": 25730,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 25787,
"s": 25747,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 25820,
"s": 25787,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 25863,
"s": 25820,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 25879,
"s": 25863,
"text": "C# | List Class"
}
] |
Draw a unstructured triangular grid as lines or markers in Python using Matplotlib - GeeksforGeeks
|
08 Jun, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
An unstructured grid can be defined as the part of the Euclidean plane or diagram that can be fit together in a pattern with no spaces in between two shapes. Unstructured grid can be triangle or tetrahedra in an irregular pattern. Unstructured Triangular Grid can be drawn from an irregularly shaped polygon using the Ruppert’s algorithm.
Here the task is to draw a unstructured triangular grid as lines and/or markers in Python using Matplotlib. In order to do this task, you can use the triplot() function and we require some modules from matplotlib and numpy library.
Example 1: Creating and plotting unstructured triangular grids.
Python3
# Importing modulesimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np n_angles = 24n_radii = 9min_radius = 0.5radii = np.linspace(min_radius, 0.9, n_radii) angles = np.linspace(0, 6 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()triang = tri.Triangulation(x, y) triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) plt.triplot(triang, 'o-', lw=1)plt.title('Example 1')plt.show()
Output:
Example 2: Using the TriFinder object to highlight the unstructured triangular grid.
Python3
# Importing modules import matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np def Trigolo1(tri): if tri == -1: points = [0, 0, 0] else: points = triang.triangles[tri] xs = triang.x[points] ys = triang.y[points] polygon.set_xy(np.column_stack([xs, ys])) def Trigolo2(event): if event.inaxes is None: tri = -1 else: tri = trifinder(event.xdata, event.ydata) Trigolo1(tri) plt.title('Example 2\nTriangle No : %i' % tri) event.canvas.draw() # Create a Triangulation.ang = 16rad = 5mrad = 0.25radii = np.linspace(mrad, 0.95, rad) angletri = np.linspace(0, 2 * np.pi, ang, endpoint=False) angletri = np.repeat(angletri[..., np.newaxis], rad, axis=1) angletri[:, 1::2] += np.pi / ang x = (radii*np.cos(angletri)).flatten()y = (radii*np.sin(angletri)).flatten() triang = Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < mrad) # Use the triangulation's default TriFinder object.trifinder = triang.get_trifinder() # Setup plot and callbacks.plt.subplot(111, aspect='equal')plt.triplot(triang, 'o-')polygon = Polygon([[0, 0], [0, 0]], facecolor='y')Trigolo1(-1)plt.gca().add_patch(polygon)plt.gcf().canvas.mpl_connect('motion_notify_event', Trigolo2) plt.show()
Output:
Example 3: Example showing the plot the triangulation.
Python3
import matplotlib.pyplot as plt import matplotlib.tri as mtri import numpy as np # Create triangulation. x = np.asarray([0, 1, 2, 3, 0.5, 1.5, 2.5, 1, 2, 1.5]) y = np.asarray([0, 0, 0, 0, 1.0, 1.0, 1.0, 2, 2, 3.0]) triangles = [[0, 1, 4], [1, 2, 5], [2, 3, 6], [1, 5, 4], [2, 6, 5], [4, 5, 7], [5, 6, 8], [5, 8, 7], [7, 8, 9]] triang = mtri.Triangulation(x, y, triangles) z = np.cos(1.5 * x) * np.cos(1.5 * y) plt.tricontourf(triang, z) plt.triplot(triang, 'go-') plt.title('Example 3') plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 25062,
"s": 25034,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 25274,
"s": 25062,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 25615,
"s": 25274,
"text": "An unstructured grid can be defined as the part of the Euclidean plane or diagram that can be fit together in a pattern with no spaces in between two shapes. Unstructured grid can be triangle or tetrahedra in an irregular pattern. Unstructured Triangular Grid can be drawn from an irregularly shaped polygon using the Ruppert’s algorithm."
},
{
"code": null,
"e": 25847,
"s": 25615,
"text": "Here the task is to draw a unstructured triangular grid as lines and/or markers in Python using Matplotlib. In order to do this task, you can use the triplot() function and we require some modules from matplotlib and numpy library."
},
{
"code": null,
"e": 25911,
"s": 25847,
"text": "Example 1: Creating and plotting unstructured triangular grids."
},
{
"code": null,
"e": 25919,
"s": 25911,
"text": "Python3"
},
{
"code": "# Importing modulesimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np n_angles = 24n_radii = 9min_radius = 0.5radii = np.linspace(min_radius, 0.9, n_radii) angles = np.linspace(0, 6 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()triang = tri.Triangulation(x, y) triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) plt.triplot(triang, 'o-', lw=1)plt.title('Example 1')plt.show()",
"e": 26645,
"s": 25919,
"text": null
},
{
"code": null,
"e": 26653,
"s": 26645,
"text": "Output:"
},
{
"code": null,
"e": 26738,
"s": 26653,
"text": "Example 2: Using the TriFinder object to highlight the unstructured triangular grid."
},
{
"code": null,
"e": 26746,
"s": 26738,
"text": "Python3"
},
{
"code": "# Importing modules import matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np def Trigolo1(tri): if tri == -1: points = [0, 0, 0] else: points = triang.triangles[tri] xs = triang.x[points] ys = triang.y[points] polygon.set_xy(np.column_stack([xs, ys])) def Trigolo2(event): if event.inaxes is None: tri = -1 else: tri = trifinder(event.xdata, event.ydata) Trigolo1(tri) plt.title('Example 2\\nTriangle No : %i' % tri) event.canvas.draw() # Create a Triangulation.ang = 16rad = 5mrad = 0.25radii = np.linspace(mrad, 0.95, rad) angletri = np.linspace(0, 2 * np.pi, ang, endpoint=False) angletri = np.repeat(angletri[..., np.newaxis], rad, axis=1) angletri[:, 1::2] += np.pi / ang x = (radii*np.cos(angletri)).flatten()y = (radii*np.sin(angletri)).flatten() triang = Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < mrad) # Use the triangulation's default TriFinder object.trifinder = triang.get_trifinder() # Setup plot and callbacks.plt.subplot(111, aspect='equal')plt.triplot(triang, 'o-')polygon = Polygon([[0, 0], [0, 0]], facecolor='y')Trigolo1(-1)plt.gca().add_patch(polygon)plt.gcf().canvas.mpl_connect('motion_notify_event', Trigolo2) plt.show()",
"e": 28276,
"s": 26746,
"text": null
},
{
"code": null,
"e": 28284,
"s": 28276,
"text": "Output:"
},
{
"code": null,
"e": 28339,
"s": 28284,
"text": "Example 3: Example showing the plot the triangulation."
},
{
"code": null,
"e": 28347,
"s": 28339,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt import matplotlib.tri as mtri import numpy as np # Create triangulation. x = np.asarray([0, 1, 2, 3, 0.5, 1.5, 2.5, 1, 2, 1.5]) y = np.asarray([0, 0, 0, 0, 1.0, 1.0, 1.0, 2, 2, 3.0]) triangles = [[0, 1, 4], [1, 2, 5], [2, 3, 6], [1, 5, 4], [2, 6, 5], [4, 5, 7], [5, 6, 8], [5, 8, 7], [7, 8, 9]] triang = mtri.Triangulation(x, y, triangles) z = np.cos(1.5 * x) * np.cos(1.5 * y) plt.tricontourf(triang, z) plt.triplot(triang, 'go-') plt.title('Example 3') plt.show()",
"e": 29023,
"s": 28347,
"text": null
},
{
"code": null,
"e": 29031,
"s": 29023,
"text": "Output:"
},
{
"code": null,
"e": 29049,
"s": 29031,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29056,
"s": 29049,
"text": "Python"
},
{
"code": null,
"e": 29154,
"s": 29056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29172,
"s": 29154,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29207,
"s": 29172,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29229,
"s": 29207,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29261,
"s": 29229,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29291,
"s": 29261,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29333,
"s": 29291,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29359,
"s": 29333,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29402,
"s": 29359,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29439,
"s": 29402,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to calculate local time in Node.js? - GeeksforGeeks
|
07 Oct, 2021
A JavaScript file is given and the task at hand is to calculate the local time. The local time is determined by the system in question where we execute our file. Node.js will be used as a runtime.
There are two approaches to this problem that are discussed below:
Approach 1: The first approach is to use the built-in methods provided by JavaScript. First, create a new Date object using new Date() method and then use the same object to get the date part using toDateString() and the time part using toTimeString() methods.
Filename: index.js
Javascript
// Creating a Date objectconst dateObj = new Date(); // Printing the date and time partsconsole.log(`Date: ${dateObj.toDateString()}`);console.log(`Time: ${dateObj.toTimeString()}`);
Run the index.js file using the following command:
node index.js
Date: Wed Nov 11 2020
Time: 18:39:31 GMT+0530 (India Standard Time)
Approach 2: The next approach is based on using a third-party library named luxon. Luxon is a wrapper for JavaScript dates and times. First, we need to install luxon as a dependency in the project. To do so, run the following command from the root directory of the project.
npm install luxon
The above command will install luxon as a dependency and it will be available for use in the JavaScript file.
Filename: index.js
Javascript
const{ DateTime } = require('luxon'); // Creating a date time objectlet date = DateTime.local(); // Printing the date and time partsconsole.log(`Date: ${date.toLocaleString(DateTime.DATE_FULL)}`);console.log(`Time: ${date.toLocaleString(DateTime.TIME_24_WITH_LONG_OFFSET)}`);
Run the index.js file using the following command:
node index.js
Output:
Date: November 11, 2020
Time: 18:57:20 India Standard Time
JavaScript-Misc
Node.js-Methods
Picked
Technical Scripter 2020
JavaScript
Node.js
Technical Scripter
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
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
|
[
{
"code": null,
"e": 25169,
"s": 25141,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 25367,
"s": 25169,
"text": "A JavaScript file is given and the task at hand is to calculate the local time. The local time is determined by the system in question where we execute our file. Node.js will be used as a runtime. "
},
{
"code": null,
"e": 25434,
"s": 25367,
"text": "There are two approaches to this problem that are discussed below:"
},
{
"code": null,
"e": 25695,
"s": 25434,
"text": "Approach 1: The first approach is to use the built-in methods provided by JavaScript. First, create a new Date object using new Date() method and then use the same object to get the date part using toDateString() and the time part using toTimeString() methods."
},
{
"code": null,
"e": 25714,
"s": 25695,
"text": "Filename: index.js"
},
{
"code": null,
"e": 25725,
"s": 25714,
"text": "Javascript"
},
{
"code": "// Creating a Date objectconst dateObj = new Date(); // Printing the date and time partsconsole.log(`Date: ${dateObj.toDateString()}`);console.log(`Time: ${dateObj.toTimeString()}`);",
"e": 25909,
"s": 25725,
"text": null
},
{
"code": null,
"e": 25960,
"s": 25909,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 25974,
"s": 25960,
"text": "node index.js"
},
{
"code": null,
"e": 26042,
"s": 25974,
"text": "Date: Wed Nov 11 2020\nTime: 18:39:31 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 26316,
"s": 26042,
"text": "Approach 2: The next approach is based on using a third-party library named luxon. Luxon is a wrapper for JavaScript dates and times. First, we need to install luxon as a dependency in the project. To do so, run the following command from the root directory of the project."
},
{
"code": null,
"e": 26335,
"s": 26316,
"text": "npm install luxon\n"
},
{
"code": null,
"e": 26445,
"s": 26335,
"text": "The above command will install luxon as a dependency and it will be available for use in the JavaScript file."
},
{
"code": null,
"e": 26464,
"s": 26445,
"text": "Filename: index.js"
},
{
"code": null,
"e": 26475,
"s": 26464,
"text": "Javascript"
},
{
"code": "const{ DateTime } = require('luxon'); // Creating a date time objectlet date = DateTime.local(); // Printing the date and time partsconsole.log(`Date: ${date.toLocaleString(DateTime.DATE_FULL)}`);console.log(`Time: ${date.toLocaleString(DateTime.TIME_24_WITH_LONG_OFFSET)}`);",
"e": 26753,
"s": 26475,
"text": null
},
{
"code": null,
"e": 26804,
"s": 26753,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 26818,
"s": 26804,
"text": "node index.js"
},
{
"code": null,
"e": 26826,
"s": 26818,
"text": "Output:"
},
{
"code": null,
"e": 26885,
"s": 26826,
"text": "Date: November 11, 2020\nTime: 18:57:20 India Standard Time"
},
{
"code": null,
"e": 26901,
"s": 26885,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 26917,
"s": 26901,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 26924,
"s": 26917,
"text": "Picked"
},
{
"code": null,
"e": 26948,
"s": 26924,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26959,
"s": 26948,
"text": "JavaScript"
},
{
"code": null,
"e": 26967,
"s": 26959,
"text": "Node.js"
},
{
"code": null,
"e": 26986,
"s": 26967,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27003,
"s": 26986,
"text": "Web Technologies"
},
{
"code": null,
"e": 27101,
"s": 27003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27110,
"s": 27101,
"text": "Comments"
},
{
"code": null,
"e": 27123,
"s": 27110,
"text": "Old Comments"
},
{
"code": null,
"e": 27184,
"s": 27123,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27225,
"s": 27184,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27265,
"s": 27225,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27319,
"s": 27265,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27381,
"s": 27319,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27414,
"s": 27381,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27462,
"s": 27414,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27495,
"s": 27462,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 27524,
"s": 27495,
"text": "Node.js fs.readFile() Method"
}
] |
JavaScript | Sort() method - GeeksforGeeks
|
14 Feb, 2019
The array.sort() is an inbuilt method in JavaScript which is used to sort the array. An array can be of any type i.e. string, numbers, characters etc.Syntax:
array.sort()
Here array is the set of values which is going to be sorted.Parameters: It does not accept any parameters.Return values: It does not return anything.Examples:
Input: var arr = ["Manish", "Rishabh", "Nitika", "Harshita"];
Output: Harshita, Manish, Nitika, Rishabh
Input: var arr = [1, 4, 3, 2];
Output: 1, 2, 3, 4
<html> <body> <p>Click on the Sort button to sort the array</p> <!-- button for click event --> <!-- onclick event is generated when the button is clicked --> <p id="demo"></p> <script> <!-- array of names --> var names = [" Manish", " Rishabh", " Nitika", " Harshita"]; document.getElementById("demo").innerHTML = names; <!-- sortAlphabet function that sort above array alphabetically --> function sortAlphabet() { names.sort(); document.getElementById("demo").innerHTML = names; } </script> <button onclick="sortAlphabet()"> Sort </button></body> </html>
Output:Before clicking the “sort” button-After clicking the “sort” button-Code #2: To sort an array of integers:
<html> <body> <p>Click on the Sort button to sort the array</p> <!-- button for click event --> <!-- onclick event is generated when the button is clicked--> <p id="demo"></p> <script> <!-- array numbers --> var numbers = [7, 1, 6, 9, 2]; document.getElementById("demo").innerHTML = numbers; <!-- sortNumber function that sort the array --> function sortNumber() { numbers.sort(); document.getElementById("demo").innerHTML = numbers; } </script> <button onclick="sortNumber()"> Sort </button></body> </html>
Output:Before clicking the “sort” button-After clicking the “sort” button-
javascript-array
javascript-functions
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to Use the JavaScript Fetch API to Get Data?
How to read a local text file using JavaScript?
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
Node.js | fs.writeFileSync() Method
Difference between TypeScript and JavaScript
|
[
{
"code": null,
"e": 24109,
"s": 24081,
"text": "\n14 Feb, 2019"
},
{
"code": null,
"e": 24267,
"s": 24109,
"text": "The array.sort() is an inbuilt method in JavaScript which is used to sort the array. An array can be of any type i.e. string, numbers, characters etc.Syntax:"
},
{
"code": null,
"e": 24281,
"s": 24267,
"text": "array.sort()\n"
},
{
"code": null,
"e": 24440,
"s": 24281,
"text": "Here array is the set of values which is going to be sorted.Parameters: It does not accept any parameters.Return values: It does not return anything.Examples:"
},
{
"code": null,
"e": 24597,
"s": 24440,
"text": "Input: var arr = [\"Manish\", \"Rishabh\", \"Nitika\", \"Harshita\"];\nOutput: Harshita, Manish, Nitika, Rishabh\n\nInput: var arr = [1, 4, 3, 2];\nOutput: 1, 2, 3, 4\n"
},
{
"code": "<html> <body> <p>Click on the Sort button to sort the array</p> <!-- button for click event --> <!-- onclick event is generated when the button is clicked --> <p id=\"demo\"></p> <script> <!-- array of names --> var names = [\" Manish\", \" Rishabh\", \" Nitika\", \" Harshita\"]; document.getElementById(\"demo\").innerHTML = names; <!-- sortAlphabet function that sort above array alphabetically --> function sortAlphabet() { names.sort(); document.getElementById(\"demo\").innerHTML = names; } </script> <button onclick=\"sortAlphabet()\"> Sort </button></body> </html>",
"e": 25252,
"s": 24597,
"text": null
},
{
"code": null,
"e": 25365,
"s": 25252,
"text": "Output:Before clicking the “sort” button-After clicking the “sort” button-Code #2: To sort an array of integers:"
},
{
"code": "<html> <body> <p>Click on the Sort button to sort the array</p> <!-- button for click event --> <!-- onclick event is generated when the button is clicked--> <p id=\"demo\"></p> <script> <!-- array numbers --> var numbers = [7, 1, 6, 9, 2]; document.getElementById(\"demo\").innerHTML = numbers; <!-- sortNumber function that sort the array --> function sortNumber() { numbers.sort(); document.getElementById(\"demo\").innerHTML = numbers; } </script> <button onclick=\"sortNumber()\"> Sort </button></body> </html>",
"e": 25955,
"s": 25365,
"text": null
},
{
"code": null,
"e": 26030,
"s": 25955,
"text": "Output:Before clicking the “sort” button-After clicking the “sort” button-"
},
{
"code": null,
"e": 26047,
"s": 26030,
"text": "javascript-array"
},
{
"code": null,
"e": 26068,
"s": 26047,
"text": "javascript-functions"
},
{
"code": null,
"e": 26079,
"s": 26068,
"text": "JavaScript"
},
{
"code": null,
"e": 26177,
"s": 26079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26186,
"s": 26177,
"text": "Comments"
},
{
"code": null,
"e": 26199,
"s": 26186,
"text": "Old Comments"
},
{
"code": null,
"e": 26260,
"s": 26199,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26305,
"s": 26260,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26377,
"s": 26305,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26423,
"s": 26377,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26472,
"s": 26423,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 26520,
"s": 26472,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 26561,
"s": 26520,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26607,
"s": 26561,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 26643,
"s": 26607,
"text": "Node.js | fs.writeFileSync() Method"
}
] |
What can cause the "cannot find symbol" error in Java?
|
The “cannot find symbol” error occurs mainly when we try to reference a variable that is not declared in the program which we are compiling, it means that the compiler doesn’t know the variable we are referring to.
Using a variable that is not declared or outside the code.
Using wrong cases (“tutorials” and “Tutorials" are different) or making spelling mistakes.
The packaged class has not been referenced correctly using an import declaration.
Using improper identifier values like letters, numbers, underscore and dollar sign. The hello-class is different from helloclass.
public class CannotFindSymbolTest {
public static void main(String[] args) {
int n1 = 10;
int n2 = 20;
sum = n1 + n2;
System.out.println(sum);
}
}
CannotFindSymbolTest.java:5: error: cannot find symbol
sum = n1 + n2;
^
symbol: variable sum
location: class CannotFindSymbolTest
CannotFindSymbolTest.java:7: error: cannot find symbol
System.out.println(sum);
^
symbol: variable sum
location: class CannotFindSymbolTest
In the above program, "Cannot find symbol" error will occur because “sum” is not declared. In order to solve the error, we need to define “int sum = n1+n2” before using the variable sum.
|
[
{
"code": null,
"e": 1402,
"s": 1187,
"text": "The “cannot find symbol” error occurs mainly when we try to reference a variable that is not declared in the program which we are compiling, it means that the compiler doesn’t know the variable we are referring to."
},
{
"code": null,
"e": 1461,
"s": 1402,
"text": "Using a variable that is not declared or outside the code."
},
{
"code": null,
"e": 1552,
"s": 1461,
"text": "Using wrong cases (“tutorials” and “Tutorials\" are different) or making spelling mistakes."
},
{
"code": null,
"e": 1634,
"s": 1552,
"text": "The packaged class has not been referenced correctly using an import declaration."
},
{
"code": null,
"e": 1764,
"s": 1634,
"text": "Using improper identifier values like letters, numbers, underscore and dollar sign. The hello-class is different from helloclass."
},
{
"code": null,
"e": 1941,
"s": 1764,
"text": "public class CannotFindSymbolTest {\n public static void main(String[] args) {\n int n1 = 10;\n int n2 = 20;\n sum = n1 + n2;\n System.out.println(sum);\n }\n}"
},
{
"code": null,
"e": 2211,
"s": 1941,
"text": "CannotFindSymbolTest.java:5: error: cannot find symbol\nsum = n1 + n2;\n^\nsymbol: variable sum\nlocation: class CannotFindSymbolTest\nCannotFindSymbolTest.java:7: error: cannot find symbol\nSystem.out.println(sum);\n^\nsymbol: variable sum\nlocation: class CannotFindSymbolTest"
},
{
"code": null,
"e": 2398,
"s": 2211,
"text": "In the above program, \"Cannot find symbol\" error will occur because “sum” is not declared. In order to solve the error, we need to define “int sum = n1+n2” before using the variable sum."
}
] |
How to change the color of selected text using CSS ?
|
15 Apr, 2020
The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background.
Below example implements the above approach:
Example:
<!DOCTYPE html><html lang="en"> <head> <title> How to change the color of selected text using CSS? </title> <style> .geeks h1 { color: green; } h1::selection { background: green; color: yellow; } p::selection { background: green; color: yellow; } </style></head> <body> <div class="geeks"> <h1>GeeksforGeeks</h1> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and many more. </p> </div></body> </html>
Output:
CSS-Misc
CSS-Selectors
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Apr, 2020"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background."
},
{
"code": null,
"e": 288,
"s": 243,
"text": "Below example implements the above approach:"
},
{
"code": null,
"e": 297,
"s": 288,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to change the color of selected text using CSS? </title> <style> .geeks h1 { color: green; } h1::selection { background: green; color: yellow; } p::selection { background: green; color: yellow; } </style></head> <body> <div class=\"geeks\"> <h1>GeeksforGeeks</h1> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and many more. </p> </div></body> </html>",
"e": 1046,
"s": 297,
"text": null
},
{
"code": null,
"e": 1054,
"s": 1046,
"text": "Output:"
},
{
"code": null,
"e": 1063,
"s": 1054,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1077,
"s": 1063,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 1087,
"s": 1077,
"text": "HTML-Misc"
},
{
"code": null,
"e": 1091,
"s": 1087,
"text": "CSS"
},
{
"code": null,
"e": 1096,
"s": 1091,
"text": "HTML"
},
{
"code": null,
"e": 1113,
"s": 1096,
"text": "Web Technologies"
},
{
"code": null,
"e": 1140,
"s": 1113,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1145,
"s": 1140,
"text": "HTML"
}
] |
Queue in Scala
|
15 Oct, 2019
A queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and a mutable queue. A mutable queue can be updated or extended in place. It means one can change, add, or remove elements of a queue as a side effect. Immutable queue, by contrast, never change.
In Scala, Queue is implemented as a pair of lists. One is used to insert the elements and second to contain deleted elements. Elements are added to the first list and removed from the second list. The two most basic operations of Queue are Enqueue and Dequeue.
Enqueue – Adding an element at the end of the queue.
Dequeue – Deleting an element from the beginning of the queue.
Methods in Queue:
+=: This method is used to add a single element in the end of the queue.++=: This method is used to Insert more than one the element in the end of the queue.clear: Remove all elements from the queue.dequeue: Returns the first element in the queueenqueue: Adds all the elements to the queue.equals: Checks if two queues are structurally identical.front: Returns the first element in the queue.isEmpty: Check if the queue is empty or not.
+=: This method is used to add a single element in the end of the queue.
++=: This method is used to Insert more than one the element in the end of the queue.
clear: Remove all elements from the queue.
dequeue: Returns the first element in the queue
enqueue: Adds all the elements to the queue.
equals: Checks if two queues are structurally identical.
front: Returns the first element in the queue.
isEmpty: Check if the queue is empty or not.
Below are simple Scala programs to demonstrate these operations:
Example 1:
// Scala program for illustrating Queue // Import Queue import scala.collection.mutable._ // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Initialize a queue var q1 = Queue(1, 2, 3, 4, 5) // Print the elements of queue print("Queue Elements: ") q1.foreach((element:Int) => print(element+" ")) // Print the first element of the queue var firstElement = q1.front println("\nFirst element in the queue: "+ firstElement) // Enqueue 10 in the queue q1.enqueue(10) // Print the elements of queue print("Queue Elements after enqueue: ") q1.foreach((element:Int) => print(element+" ")) // Dequeue first element from the queue var deq = q1.dequeue // Print the elements of queue print("\nQueue Elements after dequeue: ") q1.foreach((element:Int) => print(element+" ")) // Print the Dequeued element print("\nDequeued element: " + deq) // using isEmpty method println("\nQueue is empty: "+ q1.isEmpty) }}
Queue Elements: 1 2 3 4 5
First element in the queue: 1
Queue Elements after enqueue: 1 2 3 4 5 10
Queue Elements after dequeue: 2 3 4 5 10
Dequeued element: 1
Queue is empty: false
Example 2:
// Scala program for illustrating Queue // Import Queue import scala.collection.mutable._ // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Initialize a queue var fruits = Queue[String]() // Adding elements to the queue fruits.enqueue("apple") fruits.enqueue("banana") fruits.enqueue("mango") fruits.enqueue("guava") // Print the elements of queue print("Queue Elements: ") fruits.foreach((element:String) => print(element+" ")) // Print the first element of the queue var firstElement = fruits.front println("\nFirst element in the queue: "+ firstElement) // Enqueue pineapple in the queue fruits.enqueue("pineapple") // Print the elements of queue print("Queue Elements after enqueue: ") fruits.foreach((element:String) => print(element+" ")) // Dequeue first element from the queue var deq = fruits.dequeue // Print the elements of queue print("\nQueue Elements after dequeue: ") fruits.foreach((element:String) => print(element+" ")) // Print the Dequeued element print("\nDequeued element: " + deq) // Using clear method println("\nclear the queue: "+ fruits.clear) // Using isEmpty method println("\nqueue is empty: "+ fruits.isEmpty) }}
Queue Elements: apple banana mango guava
First element in the queue: apple
Queue Elements after enqueue: apple banana mango guava pineapple
Queue Elements after dequeue: banana mango guava pineapple
Dequeued element: apple
clear the queue: ()
queue is empty:true
Picked
Scala
scala-collection
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2019"
},
{
"code": null,
"e": 317,
"s": 28,
"text": "A queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and a mutable queue. A mutable queue can be updated or extended in place. It means one can change, add, or remove elements of a queue as a side effect. Immutable queue, by contrast, never change."
},
{
"code": null,
"e": 578,
"s": 317,
"text": "In Scala, Queue is implemented as a pair of lists. One is used to insert the elements and second to contain deleted elements. Elements are added to the first list and removed from the second list. The two most basic operations of Queue are Enqueue and Dequeue."
},
{
"code": null,
"e": 631,
"s": 578,
"text": "Enqueue – Adding an element at the end of the queue."
},
{
"code": null,
"e": 694,
"s": 631,
"text": "Dequeue – Deleting an element from the beginning of the queue."
},
{
"code": null,
"e": 712,
"s": 694,
"text": "Methods in Queue:"
},
{
"code": null,
"e": 1149,
"s": 712,
"text": "+=: This method is used to add a single element in the end of the queue.++=: This method is used to Insert more than one the element in the end of the queue.clear: Remove all elements from the queue.dequeue: Returns the first element in the queueenqueue: Adds all the elements to the queue.equals: Checks if two queues are structurally identical.front: Returns the first element in the queue.isEmpty: Check if the queue is empty or not."
},
{
"code": null,
"e": 1222,
"s": 1149,
"text": "+=: This method is used to add a single element in the end of the queue."
},
{
"code": null,
"e": 1308,
"s": 1222,
"text": "++=: This method is used to Insert more than one the element in the end of the queue."
},
{
"code": null,
"e": 1351,
"s": 1308,
"text": "clear: Remove all elements from the queue."
},
{
"code": null,
"e": 1399,
"s": 1351,
"text": "dequeue: Returns the first element in the queue"
},
{
"code": null,
"e": 1444,
"s": 1399,
"text": "enqueue: Adds all the elements to the queue."
},
{
"code": null,
"e": 1501,
"s": 1444,
"text": "equals: Checks if two queues are structurally identical."
},
{
"code": null,
"e": 1548,
"s": 1501,
"text": "front: Returns the first element in the queue."
},
{
"code": null,
"e": 1593,
"s": 1548,
"text": "isEmpty: Check if the queue is empty or not."
},
{
"code": null,
"e": 1658,
"s": 1593,
"text": "Below are simple Scala programs to demonstrate these operations:"
},
{
"code": null,
"e": 1669,
"s": 1658,
"text": "Example 1:"
},
{
"code": "// Scala program for illustrating Queue // Import Queue import scala.collection.mutable._ // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Initialize a queue var q1 = Queue(1, 2, 3, 4, 5) // Print the elements of queue print(\"Queue Elements: \") q1.foreach((element:Int) => print(element+\" \")) // Print the first element of the queue var firstElement = q1.front println(\"\\nFirst element in the queue: \"+ firstElement) // Enqueue 10 in the queue q1.enqueue(10) // Print the elements of queue print(\"Queue Elements after enqueue: \") q1.foreach((element:Int) => print(element+\" \")) // Dequeue first element from the queue var deq = q1.dequeue // Print the elements of queue print(\"\\nQueue Elements after dequeue: \") q1.foreach((element:Int) => print(element+\" \")) // Print the Dequeued element print(\"\\nDequeued element: \" + deq) // using isEmpty method println(\"\\nQueue is empty: \"+ q1.isEmpty) }}",
"e": 2849,
"s": 1669,
"text": null
},
{
"code": null,
"e": 3035,
"s": 2849,
"text": "Queue Elements: 1 2 3 4 5 \nFirst element in the queue: 1\nQueue Elements after enqueue: 1 2 3 4 5 10 \nQueue Elements after dequeue: 2 3 4 5 10 \nDequeued element: 1\nQueue is empty: false\n"
},
{
"code": null,
"e": 3046,
"s": 3035,
"text": "Example 2:"
},
{
"code": "// Scala program for illustrating Queue // Import Queue import scala.collection.mutable._ // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Initialize a queue var fruits = Queue[String]() // Adding elements to the queue fruits.enqueue(\"apple\") fruits.enqueue(\"banana\") fruits.enqueue(\"mango\") fruits.enqueue(\"guava\") // Print the elements of queue print(\"Queue Elements: \") fruits.foreach((element:String) => print(element+\" \")) // Print the first element of the queue var firstElement = fruits.front println(\"\\nFirst element in the queue: \"+ firstElement) // Enqueue pineapple in the queue fruits.enqueue(\"pineapple\") // Print the elements of queue print(\"Queue Elements after enqueue: \") fruits.foreach((element:String) => print(element+\" \")) // Dequeue first element from the queue var deq = fruits.dequeue // Print the elements of queue print(\"\\nQueue Elements after dequeue: \") fruits.foreach((element:String) => print(element+\" \")) // Print the Dequeued element print(\"\\nDequeued element: \" + deq) // Using clear method println(\"\\nclear the queue: \"+ fruits.clear) // Using isEmpty method println(\"\\nqueue is empty: \"+ fruits.isEmpty) }}",
"e": 4545,
"s": 3046,
"text": null
},
{
"code": null,
"e": 4813,
"s": 4545,
"text": "Queue Elements: apple banana mango guava \nFirst element in the queue: apple\nQueue Elements after enqueue: apple banana mango guava pineapple \nQueue Elements after dequeue: banana mango guava pineapple \nDequeued element: apple\nclear the queue: ()\n\nqueue is empty:true\n"
},
{
"code": null,
"e": 4820,
"s": 4813,
"text": "Picked"
},
{
"code": null,
"e": 4826,
"s": 4820,
"text": "Scala"
},
{
"code": null,
"e": 4843,
"s": 4826,
"text": "scala-collection"
},
{
"code": null,
"e": 4849,
"s": 4843,
"text": "Scala"
}
] |
Animated sliding image gallery using framer and ReactJS
|
24 Mar, 2021
The following approach covers how to create an animated sliding image gallery using framer and ReactJS.
Prerequisites:
Knowledge of JavaScript (ES6)Knowledge of HTML/CSS.Basic knowledge of ReactJS.
Knowledge of JavaScript (ES6)
Knowledge of HTML/CSS.
Basic knowledge of ReactJS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:$ npx create-react-app image-gallery
Step 1: Create a React application using the following command:
$ npx create-react-app image-gallery
Step 2: After creating your project folder i.e. image-gallery, move to it using the following command.$ cd image-gallery
Step 2: After creating your project folder i.e. image-gallery, move to it using the following command.
$ cd image-gallery
Step 3: Add the npm packages you will need during the project.$ npm install framer
Step 3: Add the npm packages you will need during the project.
$ npm install framer
Open the src folder and delete the following files:
logo.svgserviceWorker.jssetupTests.jsApp.test.js (if any)App.jsApp.css
logo.svg
serviceWorker.js
setupTests.js
App.test.js (if any)
App.js
App.css
Project Structure: It will look like the following.
Project structure
index.js
import React from "react";import { render } from "react-dom"; // Importing framer components : Frame and Pageimport { Frame, Page } from "framer";import "./index.css"; export function MyComponent() { // Object array of sliding gallery pages data const pages = [ { index: 1, // Source of the image src: "https://media.geeksforgeeks.org/wp-content/" + "cdn-uploads/gfg_200x200-min.png", // background color of the page background: "#1e1e1e" }, { index: 2, src: "https://media.geeksforgeeks.org/wp-content/" + "cdn-uploads/20190710102234/download3.png", background: "#fcfcfc" }, { index: 3, src: "https://yt3.ggpht.com/ytc/AAUvwnjJqZG9PvGfC3Go"+ "V27UlohMeBLxyUdhs9hUbc-Agw=s900-c-k-c0x00ffffff-no-rj", background: "#bcbcbc" } ]; return ( // Framer component with some of its attributes <Page defaultEffect="none" width={350} height={350} contentWidth="auto" alignment="end" radius={30} > {/* Map through the Pages object array and rendering each page with its specified image and background-color */} {pages.map((page) => ( // Framer "Frame" component <Frame width={350} height={350} radius={30} background={page.background} > <img src={page.src} alt="geeksforgeeks" /> </Frame> ))} </Page> );} // Export default MyComponent;// rendering "MyComponent"const rootElement = document.getElementById("root");render(<MyComponent />, rootElement);
index.css
#root { width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; background: rgba(0, 85, 255, 1); perspective: 1000px; cursor: ew-resize;} body { font-family: sans-serif; text-align: center; margin: 0;} img { border-radius: 100%; height: 300px; width: 300px; margin-top: 25px; justify-content: center; align-items: center;}
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.
Reference: https://codesandbox.io/s/animated-sliding-image-gallery-9pplj
Framer-motion
React-Questions
CSS
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Roadmap to Learn JavaScript For Beginners
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "The following approach covers how to create an animated sliding image gallery using framer and ReactJS."
},
{
"code": null,
"e": 147,
"s": 132,
"text": "Prerequisites:"
},
{
"code": null,
"e": 226,
"s": 147,
"text": "Knowledge of JavaScript (ES6)Knowledge of HTML/CSS.Basic knowledge of ReactJS."
},
{
"code": null,
"e": 256,
"s": 226,
"text": "Knowledge of JavaScript (ES6)"
},
{
"code": null,
"e": 279,
"s": 256,
"text": "Knowledge of HTML/CSS."
},
{
"code": null,
"e": 307,
"s": 279,
"text": "Basic knowledge of ReactJS."
},
{
"code": null,
"e": 357,
"s": 307,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 457,
"s": 357,
"text": "Step 1: Create a React application using the following command:$ npx create-react-app image-gallery"
},
{
"code": null,
"e": 521,
"s": 457,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 558,
"s": 521,
"text": "$ npx create-react-app image-gallery"
},
{
"code": null,
"e": 679,
"s": 558,
"text": "Step 2: After creating your project folder i.e. image-gallery, move to it using the following command.$ cd image-gallery"
},
{
"code": null,
"e": 782,
"s": 679,
"text": "Step 2: After creating your project folder i.e. image-gallery, move to it using the following command."
},
{
"code": null,
"e": 801,
"s": 782,
"text": "$ cd image-gallery"
},
{
"code": null,
"e": 884,
"s": 801,
"text": "Step 3: Add the npm packages you will need during the project.$ npm install framer"
},
{
"code": null,
"e": 947,
"s": 884,
"text": "Step 3: Add the npm packages you will need during the project."
},
{
"code": null,
"e": 968,
"s": 947,
"text": "$ npm install framer"
},
{
"code": null,
"e": 1020,
"s": 968,
"text": "Open the src folder and delete the following files:"
},
{
"code": null,
"e": 1091,
"s": 1020,
"text": "logo.svgserviceWorker.jssetupTests.jsApp.test.js (if any)App.jsApp.css"
},
{
"code": null,
"e": 1100,
"s": 1091,
"text": "logo.svg"
},
{
"code": null,
"e": 1117,
"s": 1100,
"text": "serviceWorker.js"
},
{
"code": null,
"e": 1131,
"s": 1117,
"text": "setupTests.js"
},
{
"code": null,
"e": 1152,
"s": 1131,
"text": "App.test.js (if any)"
},
{
"code": null,
"e": 1159,
"s": 1152,
"text": "App.js"
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "App.css"
},
{
"code": null,
"e": 1219,
"s": 1167,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1237,
"s": 1219,
"text": "Project structure"
},
{
"code": null,
"e": 1246,
"s": 1237,
"text": "index.js"
},
{
"code": "import React from \"react\";import { render } from \"react-dom\"; // Importing framer components : Frame and Pageimport { Frame, Page } from \"framer\";import \"./index.css\"; export function MyComponent() { // Object array of sliding gallery pages data const pages = [ { index: 1, // Source of the image src: \"https://media.geeksforgeeks.org/wp-content/\" + \"cdn-uploads/gfg_200x200-min.png\", // background color of the page background: \"#1e1e1e\" }, { index: 2, src: \"https://media.geeksforgeeks.org/wp-content/\" + \"cdn-uploads/20190710102234/download3.png\", background: \"#fcfcfc\" }, { index: 3, src: \"https://yt3.ggpht.com/ytc/AAUvwnjJqZG9PvGfC3Go\"+ \"V27UlohMeBLxyUdhs9hUbc-Agw=s900-c-k-c0x00ffffff-no-rj\", background: \"#bcbcbc\" } ]; return ( // Framer component with some of its attributes <Page defaultEffect=\"none\" width={350} height={350} contentWidth=\"auto\" alignment=\"end\" radius={30} > {/* Map through the Pages object array and rendering each page with its specified image and background-color */} {pages.map((page) => ( // Framer \"Frame\" component <Frame width={350} height={350} radius={30} background={page.background} > <img src={page.src} alt=\"geeksforgeeks\" /> </Frame> ))} </Page> );} // Export default MyComponent;// rendering \"MyComponent\"const rootElement = document.getElementById(\"root\");render(<MyComponent />, rootElement);",
"e": 2868,
"s": 1246,
"text": null
},
{
"code": null,
"e": 2878,
"s": 2868,
"text": "index.css"
},
{
"code": "#root { width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; background: rgba(0, 85, 255, 1); perspective: 1000px; cursor: ew-resize;} body { font-family: sans-serif; text-align: center; margin: 0;} img { border-radius: 100%; height: 300px; width: 300px; margin-top: 25px; justify-content: center; align-items: center;}",
"e": 3254,
"s": 2878,
"text": null
},
{
"code": null,
"e": 3367,
"s": 3254,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3379,
"s": 3367,
"text": "$ npm start"
},
{
"code": null,
"e": 3478,
"s": 3379,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 3551,
"s": 3478,
"text": "Reference: https://codesandbox.io/s/animated-sliding-image-gallery-9pplj"
},
{
"code": null,
"e": 3565,
"s": 3551,
"text": "Framer-motion"
},
{
"code": null,
"e": 3581,
"s": 3565,
"text": "React-Questions"
},
{
"code": null,
"e": 3585,
"s": 3581,
"text": "CSS"
},
{
"code": null,
"e": 3596,
"s": 3585,
"text": "JavaScript"
},
{
"code": null,
"e": 3604,
"s": 3596,
"text": "ReactJS"
},
{
"code": null,
"e": 3621,
"s": 3604,
"text": "Web Technologies"
},
{
"code": null,
"e": 3719,
"s": 3621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3758,
"s": 3719,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 3797,
"s": 3758,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3836,
"s": 3797,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3865,
"s": 3836,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3902,
"s": 3865,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 3963,
"s": 3902,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4035,
"s": 3963,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4075,
"s": 4035,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4128,
"s": 4075,
"text": "Hide or show elements in HTML using display property"
}
] |
Seaborn – Bubble Plot
|
11 Dec, 2020
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas.
Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. Bubble plots are scatter plots with bubbles (color filled circles) rather than information focuses. Bubbles have various sizes dependent on another variable in the data. Likewise, Bubbles can be of various color dependent on another variable in the dataset.
Let us load the required module and the simplified Iris data as a Pandas Data frame:
Python3
# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata= "https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head()
Output:
As stated earlier than, bubble is a unique form of scatter plot with bubbles as opposed to easy facts points in scatter plot. Let us first make a simple scatter plot the usage of Seaborn’s scatterplot() function.
Python3
# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata = "https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head() # depict scatterplot illustrationsns.set_context("talk", font_scale=1.1)plt.figure(figsize=(8, 6))sns.scatterplot(x="sepal.length", y="sepal.width", data=df) # assign labelsplt.xlabel("Sepal.Length")plt.ylabel("sepal.width")
Output:
To make bubble plot in Seaborn, we are able to use scatterplot() function in Seaborn with a variable specifying size argument in addition to x and y-axis variables for scatter plot.
In this bubble plot instance, we have length= ”body_mass_g”. And this will create a bubble plot with unique bubble sizes based at the body length variable.
Python3
# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata = "https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head() # depict scatter plot illustrationsns.set_context("talk", font_scale=1.1)plt.figure(figsize=(10, 6))sns.scatterplot(x="petal.length", y="petal.width", data=df)# Put the legend out of the figureplt.legend(bbox_to_anchor=(1.01, 1), borderaxespad=0)plt.xlabel("petal.length")plt.ylabel("petal.width")plt.tight_layout()plt.savefig("Bubble_plot_Seaborn_scatterplot.png", format='png', dpi=150)
Output:
The below example depicts a bubble plot having colored bubbles:
Python3
# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata= "https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head() # depict bubble plot illustrationsns.set_context("talk", font_scale=1.2)plt.figure(figsize=(10,6))sns.scatterplot(x='petal.length', y='petal.width', sizes=(20,500), alpha=0.5, data= df)# Put the legend out of the figureplt.legend(bbox_to_anchor=(1.01, 1),borderaxespad=0) # assign labelsplt.xlabel("Sepal.length")plt.ylabel("Sepal.width") # assign titleplt.title("Bubble plot in Seaborn") # adjust layoutplt.tight_layout()
Output:
We can alter the air bubble plot made with Seaborn without any problem. Something that we notice from the bubble plot above is that the bubble size range is by all accounts little. It will be extraordinary in the event that we could differ the littlest and biggest bubble sizes.
With the contention sizes in Seaborn‘s scatterplot() work, we can indicate ranges for the bubble sizes. In this air pocket plot model underneath, we utilized sizes=(20,500).
Python3
# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata = "https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head() # depict bubble plot illustrationsns.set_context("talk", font_scale=1.2)plt.figure(figsize=(10, 6))sns.scatterplot(x='sepal.length', y='sepal.width', # size="body_mass_g", sizes=(20, 500), alpha=0.5, hue='variety', data=df) # Put the legend out of the figureplt.legend(bbox_to_anchor=(1.01, 1), borderaxespad=0) # Put the legend out of the figureplt.xlabel("sepal.length")plt.ylabel("sepal.width")plt.title("Bubble plot with Colors in Seaborn")plt.tight_layout()
Output:
Presently our bubble plot looks much better with the lowest bubble comparing to the lowest weight and the greatest bubble relates to the biggest weight. At the point when you have more factors in the information, we can shade the bubble by the fourth factor. To color the bubble plot by a variable, we determine tone contention.
Python-Seaborn
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
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 351,
"s": 54,
"text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas."
},
{
"code": null,
"e": 732,
"s": 351,
"text": "Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. Bubble plots are scatter plots with bubbles (color filled circles) rather than information focuses. Bubbles have various sizes dependent on another variable in the data. Likewise, Bubbles can be of various color dependent on another variable in the dataset."
},
{
"code": null,
"e": 817,
"s": 732,
"text": "Let us load the required module and the simplified Iris data as a Pandas Data frame:"
},
{
"code": null,
"e": 825,
"s": 817,
"text": "Python3"
},
{
"code": "# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata= \"https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv\" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head()",
"e": 1134,
"s": 825,
"text": null
},
{
"code": null,
"e": 1142,
"s": 1134,
"text": "Output:"
},
{
"code": null,
"e": 1355,
"s": 1142,
"text": "As stated earlier than, bubble is a unique form of scatter plot with bubbles as opposed to easy facts points in scatter plot. Let us first make a simple scatter plot the usage of Seaborn’s scatterplot() function."
},
{
"code": null,
"e": 1363,
"s": 1355,
"text": "Python3"
},
{
"code": "# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata = \"https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv\" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head() # depict scatterplot illustrationsns.set_context(\"talk\", font_scale=1.1)plt.figure(figsize=(8, 6))sns.scatterplot(x=\"sepal.length\", y=\"sepal.width\", data=df) # assign labelsplt.xlabel(\"Sepal.Length\")plt.ylabel(\"sepal.width\")",
"e": 1930,
"s": 1363,
"text": null
},
{
"code": null,
"e": 1938,
"s": 1930,
"text": "Output:"
},
{
"code": null,
"e": 2120,
"s": 1938,
"text": "To make bubble plot in Seaborn, we are able to use scatterplot() function in Seaborn with a variable specifying size argument in addition to x and y-axis variables for scatter plot."
},
{
"code": null,
"e": 2276,
"s": 2120,
"text": "In this bubble plot instance, we have length= ”body_mass_g”. And this will create a bubble plot with unique bubble sizes based at the body length variable."
},
{
"code": null,
"e": 2284,
"s": 2276,
"text": "Python3"
},
{
"code": "# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata = \"https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv\" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head() # depict scatter plot illustrationsns.set_context(\"talk\", font_scale=1.1)plt.figure(figsize=(10, 6))sns.scatterplot(x=\"petal.length\", y=\"petal.width\", data=df)# Put the legend out of the figureplt.legend(bbox_to_anchor=(1.01, 1), borderaxespad=0)plt.xlabel(\"petal.length\")plt.ylabel(\"petal.width\")plt.tight_layout()plt.savefig(\"Bubble_plot_Seaborn_scatterplot.png\", format='png', dpi=150)",
"e": 3025,
"s": 2284,
"text": null
},
{
"code": null,
"e": 3033,
"s": 3025,
"text": "Output:"
},
{
"code": null,
"e": 3097,
"s": 3033,
"text": "The below example depicts a bubble plot having colored bubbles:"
},
{
"code": null,
"e": 3105,
"s": 3097,
"text": "Python3"
},
{
"code": "# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata= \"https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv\" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head() # depict bubble plot illustrationsns.set_context(\"talk\", font_scale=1.2)plt.figure(figsize=(10,6))sns.scatterplot(x='petal.length', y='petal.width', sizes=(20,500), alpha=0.5, data= df)# Put the legend out of the figureplt.legend(bbox_to_anchor=(1.01, 1),borderaxespad=0) # assign labelsplt.xlabel(\"Sepal.length\")plt.ylabel(\"Sepal.width\") # assign titleplt.title(\"Bubble plot in Seaborn\") # adjust layoutplt.tight_layout()",
"e": 3899,
"s": 3105,
"text": null
},
{
"code": null,
"e": 3907,
"s": 3899,
"text": "Output:"
},
{
"code": null,
"e": 4188,
"s": 3907,
"text": "We can alter the air bubble plot made with Seaborn without any problem. Something that we notice from the bubble plot above is that the bubble size range is by all accounts little. It will be extraordinary in the event that we could differ the littlest and biggest bubble sizes. "
},
{
"code": null,
"e": 4362,
"s": 4188,
"text": "With the contention sizes in Seaborn‘s scatterplot() work, we can indicate ranges for the bubble sizes. In this air pocket plot model underneath, we utilized sizes=(20,500)."
},
{
"code": null,
"e": 4370,
"s": 4362,
"text": "Python3"
},
{
"code": "# import all important librariesimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as sns # load datasetdata = \"https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv\" # convert to dataframedf = pd.read_csv(data) # display top most rowsdf.head() # depict bubble plot illustrationsns.set_context(\"talk\", font_scale=1.2)plt.figure(figsize=(10, 6))sns.scatterplot(x='sepal.length', y='sepal.width', # size=\"body_mass_g\", sizes=(20, 500), alpha=0.5, hue='variety', data=df) # Put the legend out of the figureplt.legend(bbox_to_anchor=(1.01, 1), borderaxespad=0) # Put the legend out of the figureplt.xlabel(\"sepal.length\")plt.ylabel(\"sepal.width\")plt.title(\"Bubble plot with Colors in Seaborn\")plt.tight_layout()",
"e": 5236,
"s": 4370,
"text": null
},
{
"code": null,
"e": 5244,
"s": 5236,
"text": "Output:"
},
{
"code": null,
"e": 5573,
"s": 5244,
"text": "Presently our bubble plot looks much better with the lowest bubble comparing to the lowest weight and the greatest bubble relates to the biggest weight. At the point when you have more factors in the information, we can shade the bubble by the fourth factor. To color the bubble plot by a variable, we determine tone contention."
},
{
"code": null,
"e": 5588,
"s": 5573,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 5595,
"s": 5588,
"text": "Python"
},
{
"code": null,
"e": 5693,
"s": 5595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5725,
"s": 5693,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5752,
"s": 5725,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5773,
"s": 5752,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5796,
"s": 5773,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5852,
"s": 5796,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5883,
"s": 5852,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5925,
"s": 5883,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5967,
"s": 5925,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 6006,
"s": 5967,
"text": "Python | Get unique values from a list"
}
] |
Difference between break and continue statement in C
|
27 Mar, 2021
In this article, we will discuss the difference between the break and continue statements in C. They are the same type of statements which is used to alter the flow of a program still they have some difference between them.
break statement: This statement terminates the smallest enclosing loop (i.e., while, do-while, for loop, or switch statement). Below is the program to illustrate the same:
C
// C program to illustrate the// break statement#include <stdio.h> // Driver Codeint main(){ int i = 0, j = 0; // Iterate a loop over the // range [0, 5] for (int i = 0; i < 5; i++) { printf("i = %d, j = ", i); // Iterate a loop over the // range [0, 5] for (int j = 0; j < 5; j++) { // Break Statement if (j == 2) break; printf("%d ", j); } printf("\n"); } return 0;}
i = 0, j = 0 1
i = 1, j = 0 1
i = 2, j = 0 1
i = 3, j = 0 1
i = 4, j = 0 1
Explanation: In the above program the inner for loop always ends when the value of the variable j becomes 2.
continue statement: This statement skips the rest of the loop statement and starts the next iteration of the loop to take place. Below is the program to illustrate the same:
C
// C program to illustrate the// continue statement#include <stdio.h> // Driver Codeint main(){ int i = 0, j = 0; // Iterate a loop over the // range [0, 5] for (int i = 0; i < 5; i++) { printf("i = %d, j = ", i); // Iterate a loop over the // range [0, 5] for (int j = 0; j < 5; j++) { // Continue Statement if (j == 2) continue; printf("%d ", j); } printf("\n"); } return 0;}
i = 0, j = 0 1 3 4
i = 1, j = 0 1 3 4
i = 2, j = 0 1 3 4
i = 3, j = 0 1 3 4
i = 4, j = 0 1 3 4
Explanation: In the above program the inner for loop always skip the iteration when the value of the variable j becomes 2.
Tabular Difference Between the break and continue statement:
C Language
C Programs
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Mar, 2021"
},
{
"code": null,
"e": 276,
"s": 52,
"text": "In this article, we will discuss the difference between the break and continue statements in C. They are the same type of statements which is used to alter the flow of a program still they have some difference between them."
},
{
"code": null,
"e": 448,
"s": 276,
"text": "break statement: This statement terminates the smallest enclosing loop (i.e., while, do-while, for loop, or switch statement). Below is the program to illustrate the same:"
},
{
"code": null,
"e": 450,
"s": 448,
"text": "C"
},
{
"code": "// C program to illustrate the// break statement#include <stdio.h> // Driver Codeint main(){ int i = 0, j = 0; // Iterate a loop over the // range [0, 5] for (int i = 0; i < 5; i++) { printf(\"i = %d, j = \", i); // Iterate a loop over the // range [0, 5] for (int j = 0; j < 5; j++) { // Break Statement if (j == 2) break; printf(\"%d \", j); } printf(\"\\n\"); } return 0;}",
"e": 944,
"s": 450,
"text": null
},
{
"code": null,
"e": 1024,
"s": 944,
"text": "i = 0, j = 0 1 \ni = 1, j = 0 1 \ni = 2, j = 0 1 \ni = 3, j = 0 1 \ni = 4, j = 0 1\n"
},
{
"code": null,
"e": 1133,
"s": 1024,
"text": "Explanation: In the above program the inner for loop always ends when the value of the variable j becomes 2."
},
{
"code": null,
"e": 1307,
"s": 1133,
"text": "continue statement: This statement skips the rest of the loop statement and starts the next iteration of the loop to take place. Below is the program to illustrate the same:"
},
{
"code": null,
"e": 1309,
"s": 1307,
"text": "C"
},
{
"code": "// C program to illustrate the// continue statement#include <stdio.h> // Driver Codeint main(){ int i = 0, j = 0; // Iterate a loop over the // range [0, 5] for (int i = 0; i < 5; i++) { printf(\"i = %d, j = \", i); // Iterate a loop over the // range [0, 5] for (int j = 0; j < 5; j++) { // Continue Statement if (j == 2) continue; printf(\"%d \", j); } printf(\"\\n\"); } return 0;}",
"e": 1812,
"s": 1309,
"text": null
},
{
"code": null,
"e": 1912,
"s": 1812,
"text": "i = 0, j = 0 1 3 4 \ni = 1, j = 0 1 3 4 \ni = 2, j = 0 1 3 4 \ni = 3, j = 0 1 3 4 \ni = 4, j = 0 1 3 4\n"
},
{
"code": null,
"e": 2035,
"s": 1912,
"text": "Explanation: In the above program the inner for loop always skip the iteration when the value of the variable j becomes 2."
},
{
"code": null,
"e": 2096,
"s": 2035,
"text": "Tabular Difference Between the break and continue statement:"
},
{
"code": null,
"e": 2107,
"s": 2096,
"text": "C Language"
},
{
"code": null,
"e": 2118,
"s": 2107,
"text": "C Programs"
},
{
"code": null,
"e": 2137,
"s": 2118,
"text": "Difference Between"
}
] |
Search and update array based on key JavaScript
|
We have two arrays like these −
let arr1 =
[{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"}]
let arr2 = [{"EMAIL":"test1@stc.com","POSITION":"GM"},
{"EMAIL":"test2@stc.com","POSITION":"GMH"},
{"EMAIL":"test3@stc.com","POSITION":"RGM"},
{"EMAIL":"test3@CSR.COM.AU","POSITION":"GM"}
]
We are required to write a function that adds the property level to each object of arr2, picking it
up from the object from arr1 that have the same value for property "POSITION"
Let's write the code for this function −
let arr1 =
[{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSI
TION":"GMH"}]
let arr2 = [{"EMAIL":"test1@stc.com","POSITION":"GM"},
{"EMAIL":"test2@stc.com","POSITION":"GMH"},
{"EMAIL":"test3@stc.com","POSITION":"RGM"},
{"EMAIL":"test3@CSR.COM.AU","POSITION":"GM"}
]
const formatArray = (first, second) => {
second.forEach((el, index) => {
const ind = first.findIndex(item => item["POSITION"] ===
el["POSITION"]);
if(ind !== -1){
second[index]["LEVEL"] = first[ind]["LEVEL"];
};
});
};
formatArray(arr1, arr2);
console.log(arr2);
The output in the console will be −
[
{ EMAIL: 'test1@stc.com', POSITION: 'GM', LEVEL: 5 },
{ EMAIL: 'test2@stc.com', POSITION: 'GMH', LEVEL: 5 },
{ EMAIL: 'test3@stc.com', POSITION: 'RGM', LEVEL: 4 },
{ EMAIL: 'test3@CSR.COM.AU', POSITION: 'GM', LEVEL: 5 }
]
|
[
{
"code": null,
"e": 1094,
"s": 1062,
"text": "We have two arrays like these −"
},
{
"code": null,
"e": 1383,
"s": 1094,
"text": "let arr1 =\n[{\"LEVEL\":4,\"POSITION\":\"RGM\"},{\"LEVEL\":5,\"POSITION\":\"GM\"},{\"LEVEL\":5,\"POSITION\":\"GMH\"}]\nlet arr2 = [{\"EMAIL\":\"test1@stc.com\",\"POSITION\":\"GM\"},\n{\"EMAIL\":\"test2@stc.com\",\"POSITION\":\"GMH\"},\n{\"EMAIL\":\"test3@stc.com\",\"POSITION\":\"RGM\"},\n{\"EMAIL\":\"test3@CSR.COM.AU\",\"POSITION\":\"GM\"}\n]"
},
{
"code": null,
"e": 1561,
"s": 1383,
"text": "We are required to write a function that adds the property level to each object of arr2, picking it\nup from the object from arr1 that have the same value for property \"POSITION\""
},
{
"code": null,
"e": 1602,
"s": 1561,
"text": "Let's write the code for this function −"
},
{
"code": null,
"e": 2206,
"s": 1602,
"text": "let arr1 =\n[{\"LEVEL\":4,\"POSITION\":\"RGM\"},{\"LEVEL\":5,\"POSITION\":\"GM\"},{\"LEVEL\":5,\"POSI\nTION\":\"GMH\"}]\n let arr2 = [{\"EMAIL\":\"test1@stc.com\",\"POSITION\":\"GM\"},\n {\"EMAIL\":\"test2@stc.com\",\"POSITION\":\"GMH\"},\n {\"EMAIL\":\"test3@stc.com\",\"POSITION\":\"RGM\"},\n {\"EMAIL\":\"test3@CSR.COM.AU\",\"POSITION\":\"GM\"}\n]\nconst formatArray = (first, second) => {\n second.forEach((el, index) => {\n const ind = first.findIndex(item => item[\"POSITION\"] ===\n el[\"POSITION\"]);\n if(ind !== -1){\n second[index][\"LEVEL\"] = first[ind][\"LEVEL\"];\n };\n });\n};\nformatArray(arr1, arr2);\nconsole.log(arr2);"
},
{
"code": null,
"e": 2242,
"s": 2206,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2478,
"s": 2242,
"text": "[\n { EMAIL: 'test1@stc.com', POSITION: 'GM', LEVEL: 5 },\n { EMAIL: 'test2@stc.com', POSITION: 'GMH', LEVEL: 5 },\n { EMAIL: 'test3@stc.com', POSITION: 'RGM', LEVEL: 4 },\n { EMAIL: 'test3@CSR.COM.AU', POSITION: 'GM', LEVEL: 5 }\n]"
}
] |
Hide or show elements in HTML using display property - GeeksforGeeks
|
28 Jul, 2021
Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery.
To hide an element, set the style display property to “none”.
document.getElementById("element").style.display = "none";
To show an element, set the style display property to “block”.
document.getElementById("element").style.display = "block";
Steps to show the working of style display property:Create some div and assign them an id or class and then add styling to it.<div class="circle" id="circle"></div><div class="rounded" id="rounded"></div><div class="square" id="square"></div>Width and height will set the width and height of the content, border-radius 0% will make a square border, 50% will make a circle and 25% will make a rounded shape and float will make the divs get positioned, margin-right will make them separated with a space at right.<style type="text/css"> .circle { width: 130px; height: 130px; border-radius: 50%; float: left; margin-right: 50px; } .rounded { width: 130px; height: 130px; border-radius: 25%; float: left; margin-right: 50px; } .square { width: 130px; height: 130px; border-radius: 0%; float: left; margin-right: 50px; }Background-color will set the background color of the div.#circle { background-color: #196F3D; } #rounded { background-color: #5DADE2; } #square { background-color: #58D68D; }The document.getElementById will select the div with given id.<script type="text/javascript"> document.getElementById("circle").onclick = function()The style.display = "none" will make it disappear when clicked on div..style.display = "none";
Create some div and assign them an id or class and then add styling to it.<div class="circle" id="circle"></div><div class="rounded" id="rounded"></div><div class="square" id="square"></div>
<div class="circle" id="circle"></div><div class="rounded" id="rounded"></div><div class="square" id="square"></div>
Width and height will set the width and height of the content, border-radius 0% will make a square border, 50% will make a circle and 25% will make a rounded shape and float will make the divs get positioned, margin-right will make them separated with a space at right.<style type="text/css"> .circle { width: 130px; height: 130px; border-radius: 50%; float: left; margin-right: 50px; } .rounded { width: 130px; height: 130px; border-radius: 25%; float: left; margin-right: 50px; } .square { width: 130px; height: 130px; border-radius: 0%; float: left; margin-right: 50px; }
<style type="text/css"> .circle { width: 130px; height: 130px; border-radius: 50%; float: left; margin-right: 50px; } .rounded { width: 130px; height: 130px; border-radius: 25%; float: left; margin-right: 50px; } .square { width: 130px; height: 130px; border-radius: 0%; float: left; margin-right: 50px; }
Background-color will set the background color of the div.#circle { background-color: #196F3D; } #rounded { background-color: #5DADE2; } #square { background-color: #58D68D; }
#circle { background-color: #196F3D; } #rounded { background-color: #5DADE2; } #square { background-color: #58D68D; }
The document.getElementById will select the div with given id.<script type="text/javascript"> document.getElementById("circle").onclick = function()
<script type="text/javascript"> document.getElementById("circle").onclick = function()
The style.display = "none" will make it disappear when clicked on div..style.display = "none";
.style.display = "none";
Implementation of style.display property:
<html><head> <title>Javascript</title> <style type="text/css"> .circle { width: 130px; height: 130px; border-radius: 50%; float: left; margin-right: 50px; } .rounded { width: 130px; height: 130px; border-radius: 25%; float: left; margin-right: 50px; } .square { width: 130px; height: 130px; border-radius: 0%; float: left; margin-right: 50px; } #circle { background-color: #196F3D; } #rounded { background-color: #5DADE2; } #square { background-color: #58D68D; } </style> </head> <body> <div class="circle" id="circle"></div> <div class="rounded" id="rounded"></div> <div class="square" id="square"></div> <script type="text/javascript"> document.getElementById("circle").onclick = function() { document.getElementById("circle").style.display = "none"; } document.getElementById("rounded").onclick = function() { document.getElementById("rounded").style.display = "none"; } document.getElementById("square").onclick = function() { document.getElementById("square").style.display = "none"; } </script> </body> </html>
Output:Output of the above code is:
Square shape will get disappear after clicking on it:
Similarly Rounded shape will get disappear after clicking on it:
Similarly, Circle shape will get disappear after clicking on it.
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
HTML-Misc
JavaScript-Misc
HTML
JavaScript
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 25319,
"s": 25291,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 25445,
"s": 25319,
"text": "Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery."
},
{
"code": null,
"e": 25507,
"s": 25445,
"text": "To hide an element, set the style display property to “none”."
},
{
"code": null,
"e": 25567,
"s": 25507,
"text": "document.getElementById(\"element\").style.display = \"none\";\n"
},
{
"code": null,
"e": 25630,
"s": 25567,
"text": "To show an element, set the style display property to “block”."
},
{
"code": null,
"e": 25691,
"s": 25630,
"text": "document.getElementById(\"element\").style.display = \"block\";\n"
},
{
"code": null,
"e": 27200,
"s": 25691,
"text": "Steps to show the working of style display property:Create some div and assign them an id or class and then add styling to it.<div class=\"circle\" id=\"circle\"></div><div class=\"rounded\" id=\"rounded\"></div><div class=\"square\" id=\"square\"></div>Width and height will set the width and height of the content, border-radius 0% will make a square border, 50% will make a circle and 25% will make a rounded shape and float will make the divs get positioned, margin-right will make them separated with a space at right.<style type=\"text/css\"> .circle { width: 130px; height: 130px; border-radius: 50%; float: left; margin-right: 50px; } .rounded { width: 130px; height: 130px; border-radius: 25%; float: left; margin-right: 50px; } .square { width: 130px; height: 130px; border-radius: 0%; float: left; margin-right: 50px; }Background-color will set the background color of the div.#circle { background-color: #196F3D; } #rounded { background-color: #5DADE2; } #square { background-color: #58D68D; }The document.getElementById will select the div with given id.<script type=\"text/javascript\"> document.getElementById(\"circle\").onclick = function()The style.display = \"none\" will make it disappear when clicked on div..style.display = \"none\";"
},
{
"code": null,
"e": 27391,
"s": 27200,
"text": "Create some div and assign them an id or class and then add styling to it.<div class=\"circle\" id=\"circle\"></div><div class=\"rounded\" id=\"rounded\"></div><div class=\"square\" id=\"square\"></div>"
},
{
"code": "<div class=\"circle\" id=\"circle\"></div><div class=\"rounded\" id=\"rounded\"></div><div class=\"square\" id=\"square\"></div>",
"e": 27508,
"s": 27391,
"text": null
},
{
"code": null,
"e": 28287,
"s": 27508,
"text": "Width and height will set the width and height of the content, border-radius 0% will make a square border, 50% will make a circle and 25% will make a rounded shape and float will make the divs get positioned, margin-right will make them separated with a space at right.<style type=\"text/css\"> .circle { width: 130px; height: 130px; border-radius: 50%; float: left; margin-right: 50px; } .rounded { width: 130px; height: 130px; border-radius: 25%; float: left; margin-right: 50px; } .square { width: 130px; height: 130px; border-radius: 0%; float: left; margin-right: 50px; }"
},
{
"code": "<style type=\"text/css\"> .circle { width: 130px; height: 130px; border-radius: 50%; float: left; margin-right: 50px; } .rounded { width: 130px; height: 130px; border-radius: 25%; float: left; margin-right: 50px; } .square { width: 130px; height: 130px; border-radius: 0%; float: left; margin-right: 50px; }",
"e": 28797,
"s": 28287,
"text": null
},
{
"code": null,
"e": 29037,
"s": 28797,
"text": "Background-color will set the background color of the div.#circle { background-color: #196F3D; } #rounded { background-color: #5DADE2; } #square { background-color: #58D68D; }"
},
{
"code": "#circle { background-color: #196F3D; } #rounded { background-color: #5DADE2; } #square { background-color: #58D68D; }",
"e": 29219,
"s": 29037,
"text": null
},
{
"code": null,
"e": 29375,
"s": 29219,
"text": "The document.getElementById will select the div with given id.<script type=\"text/javascript\"> document.getElementById(\"circle\").onclick = function()"
},
{
"code": "<script type=\"text/javascript\"> document.getElementById(\"circle\").onclick = function()",
"e": 29469,
"s": 29375,
"text": null
},
{
"code": null,
"e": 29564,
"s": 29469,
"text": "The style.display = \"none\" will make it disappear when clicked on div..style.display = \"none\";"
},
{
"code": ".style.display = \"none\";",
"e": 29589,
"s": 29564,
"text": null
},
{
"code": null,
"e": 29631,
"s": 29589,
"text": "Implementation of style.display property:"
},
{
"code": "<html><head> <title>Javascript</title> <style type=\"text/css\"> .circle { width: 130px; height: 130px; border-radius: 50%; float: left; margin-right: 50px; } .rounded { width: 130px; height: 130px; border-radius: 25%; float: left; margin-right: 50px; } .square { width: 130px; height: 130px; border-radius: 0%; float: left; margin-right: 50px; } #circle { background-color: #196F3D; } #rounded { background-color: #5DADE2; } #square { background-color: #58D68D; } </style> </head> <body> <div class=\"circle\" id=\"circle\"></div> <div class=\"rounded\" id=\"rounded\"></div> <div class=\"square\" id=\"square\"></div> <script type=\"text/javascript\"> document.getElementById(\"circle\").onclick = function() { document.getElementById(\"circle\").style.display = \"none\"; } document.getElementById(\"rounded\").onclick = function() { document.getElementById(\"rounded\").style.display = \"none\"; } document.getElementById(\"square\").onclick = function() { document.getElementById(\"square\").style.display = \"none\"; } </script> </body> </html>",
"e": 31111,
"s": 29631,
"text": null
},
{
"code": null,
"e": 31147,
"s": 31111,
"text": "Output:Output of the above code is:"
},
{
"code": null,
"e": 31201,
"s": 31147,
"text": "Square shape will get disappear after clicking on it:"
},
{
"code": null,
"e": 31266,
"s": 31201,
"text": "Similarly Rounded shape will get disappear after clicking on it:"
},
{
"code": null,
"e": 31331,
"s": 31266,
"text": "Similarly, Circle shape will get disappear after clicking on it."
},
{
"code": null,
"e": 31525,
"s": 31331,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 31535,
"s": 31525,
"text": "HTML-Misc"
},
{
"code": null,
"e": 31551,
"s": 31535,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 31556,
"s": 31551,
"text": "HTML"
},
{
"code": null,
"e": 31567,
"s": 31556,
"text": "JavaScript"
},
{
"code": null,
"e": 31572,
"s": 31567,
"text": "HTML"
},
{
"code": null,
"e": 31670,
"s": 31572,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31720,
"s": 31670,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31782,
"s": 31720,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31830,
"s": 31782,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31890,
"s": 31830,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31951,
"s": 31890,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31991,
"s": 31951,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32036,
"s": 31991,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32097,
"s": 32036,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32166,
"s": 32097,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
Check if a word is present in a sentence - GeeksforGeeks
|
20 Apr, 2022
Given a sentence as a string str and a word word, the task is to check if the word is present in str or not. A sentence is a string comprised of multiple words and each word is separated with spaces.Examples:
Input: str = “Geeks for Geeks”, word = “Geeks” Output: Word is present in the sentence
Input: str = “Geeks for Geeks”, word = “eeks” Output: Word is not present in the sentence
Approach: In this algorithm, stringstream is used to break the sentence into words then compare each individual word of the sentence with the given word. If the word is found then the function returns true. Note that this implementation does not search for a sub-sequence or sub-string, it only searches for a complete single word in a sentence.Below is the implementation for the case-sensitive search approach:
CPP
Java
Python
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the word is foundbool isWordPresent(string sentence, string word){ // To break the sentence in words stringstream s(sentence); // To temporarily store each individual word string temp; while (s >> temp) { // Comparing the current word // with the word to be searched if (temp.compare(word) == 0) { return true; } } return false;} // Driver codeint main(){ string s = "Geeks for Geeks"; string word = "Geeks"; if (isWordPresent(s, word)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachclass GFG{ // Function that returns true if the word is foundstatic boolean isWordPresent(String sentence, String word){ // To break the sentence in words String []s = sentence.split(" "); // To temporarily store each individual word for ( String temp :s) { // Comparing the current word // with the word to be searched if (temp.compareTo(word) == 0) { return true; } } return false;} // Driver codepublic static void main(String[] args){ String s = "Geeks for Geeks"; String word = "Geeks"; if (isWordPresent(s, word)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approach # Function that returns true if the word is founddef isWordPresent(sentence, word): # To break the sentence in words s = sentence.split(" ") for i in s: # Comparing the current word # with the word to be searched if (i == word): return True return False # Driver codes = "Geeks for Geeks"word = "Geeks" if (isWordPresent(s, word)): print("Yes")else: print("No") # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System; class GFG{ // Function that returns true if the word is foundstatic bool isWordPresent(String sentence, String word){ // To break the sentence in words String []s = sentence.Split(' '); // To temporarily store each individual word foreach(String temp in s) { // Comparing the current word // with the word to be searched if (temp.CompareTo(word) == 0) { return true; } } return false;} // Driver codepublic static void Main(String[] args){ String s = "Geeks for Geeks"; String word = "Geeks"; if (isWordPresent(s, word)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the approach // Function that returns true if the word is foundfunction isWordPresent(sentence, word){ // To break the sentence in words let s = sentence.split(" "); // To temporarily store each individual word for ( let temp=0;temp<s.length;temp++) { // Comparing the current word // with the word to be searched if (s[temp] == (word) ) { return true; } } return false;} // Driver codelet s = "Geeks for Geeks";let word = "Geeks"; if (isWordPresent(s, word)) document.write("Yes"); else document.write("No"); // This code is contributed by patel2127 </script>
Yes
Below is the implementation for the case-insensitive search approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the word is foundbool isWordPresent(string sentence, string word){ // To convert the word in uppercase transform(word.begin(), word.end(), word.begin(), ::toupper); // To convert the complete sentence in uppercase transform(sentence.begin(), sentence.end(), sentence.begin(), ::toupper); // Both strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words stringstream s(sentence); // To store the individual words of the sentence string temp; while (s >> temp) { // Compare the current word // with the word to be searched if (temp.compare(word) == 0) { return true; } } return false;} // Driver codeint main(){ string s = "Geeks for Geeks"; string word = "geeks"; if (isWordPresent(s, word)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if the word is foundstatic boolean isWordPresent(String sentence, String word){ // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words String []s = sentence.split(" "); // To store the individual words of the sentence for ( String temp :s) { // Comparing the current word // with the word to be searched if (temp.compareTo(word) == 0) { return true; } } return false;} static String transform(String word){ return word.toUpperCase();} // Driver codepublic static void main(String[] args){ String s = "Geeks for Geeks"; String word = "geeks"; if (isWordPresent(s, word)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approach # Function that returns true if the word is founddef isWordPresent(sentence, word) : # To convert the word in uppercase word = word.upper() # To convert the complete sentence in uppercase sentence = sentence.upper() # Both strings are converted to the same case, # so that the search is not case-sensitive # To break the sentence in words s = sentence.split(); for temp in s : # Compare the current word # with the word to be searched if (temp == word) : return True; return False; # Driver codeif __name__ == "__main__" : s = "Geeks for Geeks"; word = "geeks"; if (isWordPresent(s, word)) : print("Yes"); else : print("No"); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function that returns true if the word is foundstatic bool isWordPresent(String sentence, String word){ // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words String []s = sentence.Split(' '); // To store the individual words of the sentence foreach ( String temp in s) { // Comparing the current word // with the word to be searched if (temp.CompareTo(word) == 0) { return true; } } return false;} static String transform(String word){ return word.ToUpper();} // Driver codepublic static void Main(String[] args){ String s = "Geeks for Geeks"; String word = "geeks"; if (isWordPresent(s, word)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by 29AjayKumar
<script>// Javascript implementation of the approach // Function that returns true if the word is foundfunction isWordPresent(sentence,word){ // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words let s = sentence.split(" "); // To store the individual words of the sentence for ( let temp=0;temp<s.length;temp++) { // Comparing the current word // with the word to be searched if (s[temp] == (word)) { return true; } } return false;} function transform(word){ return word.toUpperCase();} // Driver codelet s = "Geeks for Geeks";let word = "geeks";if (isWordPresent(s, word)) document.write("Yes");else document.write("No"); // This code is contributed by unknown2108</script>
Yes
As all the words in a sentence are separated by spaces.
We have to split the sentence by spaces using split().
We split all the words by spaces and store them in a list.
We use count() function to check whether the word is in array
If the value of count is greater than 0 then word is present in string
Below is the implementation:
Python3
Javascript
# Python3 implementation of the approach # Function that returns true# if the word is founddef isWordPresent(sentence, word): # To convert the word in uppercase word = word.upper() # To convert the complete # sentence in uppercase sentence = sentence.upper() # splitting the sentence to list lis = sentence.split() # checking if word is present if(lis.count(word) > 0): return True else: return False # Driver codes = "Geeks for Geeks"word = "geeks"if (isWordPresent(s, word)): print("Yes")else: print("No") # This code is contributed by vikkycirus
<script> // JavaScript implementation of the approach // Function that returns true// if the word is foundfunction isWordPresent(sentence, word){ // To convert the word in uppercase word = word.toUpperCase() // To convert the complete // sentence in uppercase sentence = sentence.toUpperCase() // splitting the sentence to list let lis = sentence.split(' ') // checking if word is present if(lis.indexOf(word) != -1) return true else return false} // Driver codelet s = "Geeks for Geeks"let word = "geeks"if (isWordPresent(s, word)) document.write("Yes","</br>")else document.write("No","</br>") // This code is contributed by shinjanpatra </script>
Output:
Yes
mohit kumar 29
ankthon
princiraj1992
29AjayKumar
vikkycirus
patel2127
unknown2108
shinjanpatra
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Interfaces in Java
Constructors in C++
Operator Overloading in C++
Polymorphism in C++
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
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": 26419,
"s": 26391,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 26629,
"s": 26419,
"text": "Given a sentence as a string str and a word word, the task is to check if the word is present in str or not. A sentence is a string comprised of multiple words and each word is separated with spaces.Examples: "
},
{
"code": null,
"e": 26717,
"s": 26629,
"text": "Input: str = “Geeks for Geeks”, word = “Geeks” Output: Word is present in the sentence "
},
{
"code": null,
"e": 26808,
"s": 26717,
"text": "Input: str = “Geeks for Geeks”, word = “eeks” Output: Word is not present in the sentence "
},
{
"code": null,
"e": 27222,
"s": 26808,
"text": "Approach: In this algorithm, stringstream is used to break the sentence into words then compare each individual word of the sentence with the given word. If the word is found then the function returns true. Note that this implementation does not search for a sub-sequence or sub-string, it only searches for a complete single word in a sentence.Below is the implementation for the case-sensitive search approach: "
},
{
"code": null,
"e": 27226,
"s": 27222,
"text": "CPP"
},
{
"code": null,
"e": 27231,
"s": 27226,
"text": "Java"
},
{
"code": null,
"e": 27238,
"s": 27231,
"text": "Python"
},
{
"code": null,
"e": 27241,
"s": 27238,
"text": "C#"
},
{
"code": null,
"e": 27252,
"s": 27241,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the word is foundbool isWordPresent(string sentence, string word){ // To break the sentence in words stringstream s(sentence); // To temporarily store each individual word string temp; while (s >> temp) { // Comparing the current word // with the word to be searched if (temp.compare(word) == 0) { return true; } } return false;} // Driver codeint main(){ string s = \"Geeks for Geeks\"; string word = \"Geeks\"; if (isWordPresent(s, word)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 27943,
"s": 27252,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function that returns true if the word is foundstatic boolean isWordPresent(String sentence, String word){ // To break the sentence in words String []s = sentence.split(\" \"); // To temporarily store each individual word for ( String temp :s) { // Comparing the current word // with the word to be searched if (temp.compareTo(word) == 0) { return true; } } return false;} // Driver codepublic static void main(String[] args){ String s = \"Geeks for Geeks\"; String word = \"Geeks\"; if (isWordPresent(s, word)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by PrinciRaj1992",
"e": 28699,
"s": 27943,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that returns true if the word is founddef isWordPresent(sentence, word): # To break the sentence in words s = sentence.split(\" \") for i in s: # Comparing the current word # with the word to be searched if (i == word): return True return False # Driver codes = \"Geeks for Geeks\"word = \"Geeks\" if (isWordPresent(s, word)): print(\"Yes\")else: print(\"No\") # This code is contributed by mohit kumar 29",
"e": 29204,
"s": 28699,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if the word is foundstatic bool isWordPresent(String sentence, String word){ // To break the sentence in words String []s = sentence.Split(' '); // To temporarily store each individual word foreach(String temp in s) { // Comparing the current word // with the word to be searched if (temp.CompareTo(word) == 0) { return true; } } return false;} // Driver codepublic static void Main(String[] args){ String s = \"Geeks for Geeks\"; String word = \"Geeks\"; if (isWordPresent(s, word)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by 29AjayKumar",
"e": 29964,
"s": 29204,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function that returns true if the word is foundfunction isWordPresent(sentence, word){ // To break the sentence in words let s = sentence.split(\" \"); // To temporarily store each individual word for ( let temp=0;temp<s.length;temp++) { // Comparing the current word // with the word to be searched if (s[temp] == (word) ) { return true; } } return false;} // Driver codelet s = \"Geeks for Geeks\";let word = \"Geeks\"; if (isWordPresent(s, word)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by patel2127 </script>",
"e": 30657,
"s": 29964,
"text": null
},
{
"code": null,
"e": 30661,
"s": 30657,
"text": "Yes"
},
{
"code": null,
"e": 30735,
"s": 30663,
"text": "Below is the implementation for the case-insensitive search approach: "
},
{
"code": null,
"e": 30739,
"s": 30735,
"text": "C++"
},
{
"code": null,
"e": 30744,
"s": 30739,
"text": "Java"
},
{
"code": null,
"e": 30752,
"s": 30744,
"text": "Python3"
},
{
"code": null,
"e": 30755,
"s": 30752,
"text": "C#"
},
{
"code": null,
"e": 30766,
"s": 30755,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the word is foundbool isWordPresent(string sentence, string word){ // To convert the word in uppercase transform(word.begin(), word.end(), word.begin(), ::toupper); // To convert the complete sentence in uppercase transform(sentence.begin(), sentence.end(), sentence.begin(), ::toupper); // Both strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words stringstream s(sentence); // To store the individual words of the sentence string temp; while (s >> temp) { // Compare the current word // with the word to be searched if (temp.compare(word) == 0) { return true; } } return false;} // Driver codeint main(){ string s = \"Geeks for Geeks\"; string word = \"geeks\"; if (isWordPresent(s, word)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 31819,
"s": 30766,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if the word is foundstatic boolean isWordPresent(String sentence, String word){ // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words String []s = sentence.split(\" \"); // To store the individual words of the sentence for ( String temp :s) { // Comparing the current word // with the word to be searched if (temp.compareTo(word) == 0) { return true; } } return false;} static String transform(String word){ return word.toUpperCase();} // Driver codepublic static void main(String[] args){ String s = \"Geeks for Geeks\"; String word = \"geeks\"; if (isWordPresent(s, word)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by PrinciRaj1992",
"e": 32948,
"s": 31819,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that returns true if the word is founddef isWordPresent(sentence, word) : # To convert the word in uppercase word = word.upper() # To convert the complete sentence in uppercase sentence = sentence.upper() # Both strings are converted to the same case, # so that the search is not case-sensitive # To break the sentence in words s = sentence.split(); for temp in s : # Compare the current word # with the word to be searched if (temp == word) : return True; return False; # Driver codeif __name__ == \"__main__\" : s = \"Geeks for Geeks\"; word = \"geeks\"; if (isWordPresent(s, word)) : print(\"Yes\"); else : print(\"No\"); # This code is contributed by AnkitRai01",
"e": 33757,
"s": 32948,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if the word is foundstatic bool isWordPresent(String sentence, String word){ // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words String []s = sentence.Split(' '); // To store the individual words of the sentence foreach ( String temp in s) { // Comparing the current word // with the word to be searched if (temp.CompareTo(word) == 0) { return true; } } return false;} static String transform(String word){ return word.ToUpper();} // Driver codepublic static void Main(String[] args){ String s = \"Geeks for Geeks\"; String word = \"geeks\"; if (isWordPresent(s, word)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by 29AjayKumar",
"e": 34869,
"s": 33757,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function that returns true if the word is foundfunction isWordPresent(sentence,word){ // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words let s = sentence.split(\" \"); // To store the individual words of the sentence for ( let temp=0;temp<s.length;temp++) { // Comparing the current word // with the word to be searched if (s[temp] == (word)) { return true; } } return false;} function transform(word){ return word.toUpperCase();} // Driver codelet s = \"Geeks for Geeks\";let word = \"geeks\";if (isWordPresent(s, word)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by unknown2108</script>",
"e": 35864,
"s": 34869,
"text": null
},
{
"code": null,
"e": 35868,
"s": 35864,
"text": "Yes"
},
{
"code": null,
"e": 35926,
"s": 35870,
"text": "As all the words in a sentence are separated by spaces."
},
{
"code": null,
"e": 35981,
"s": 35926,
"text": "We have to split the sentence by spaces using split()."
},
{
"code": null,
"e": 36040,
"s": 35981,
"text": "We split all the words by spaces and store them in a list."
},
{
"code": null,
"e": 36102,
"s": 36040,
"text": "We use count() function to check whether the word is in array"
},
{
"code": null,
"e": 36173,
"s": 36102,
"text": "If the value of count is greater than 0 then word is present in string"
},
{
"code": null,
"e": 36202,
"s": 36173,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 36210,
"s": 36202,
"text": "Python3"
},
{
"code": null,
"e": 36221,
"s": 36210,
"text": "Javascript"
},
{
"code": "# Python3 implementation of the approach # Function that returns true# if the word is founddef isWordPresent(sentence, word): # To convert the word in uppercase word = word.upper() # To convert the complete # sentence in uppercase sentence = sentence.upper() # splitting the sentence to list lis = sentence.split() # checking if word is present if(lis.count(word) > 0): return True else: return False # Driver codes = \"Geeks for Geeks\"word = \"geeks\"if (isWordPresent(s, word)): print(\"Yes\")else: print(\"No\") # This code is contributed by vikkycirus",
"e": 36824,
"s": 36221,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function that returns true// if the word is foundfunction isWordPresent(sentence, word){ // To convert the word in uppercase word = word.toUpperCase() // To convert the complete // sentence in uppercase sentence = sentence.toUpperCase() // splitting the sentence to list let lis = sentence.split(' ') // checking if word is present if(lis.indexOf(word) != -1) return true else return false} // Driver codelet s = \"Geeks for Geeks\"let word = \"geeks\"if (isWordPresent(s, word)) document.write(\"Yes\",\"</br>\")else document.write(\"No\",\"</br>\") // This code is contributed by shinjanpatra </script>",
"e": 37527,
"s": 36824,
"text": null
},
{
"code": null,
"e": 37535,
"s": 37527,
"text": "Output:"
},
{
"code": null,
"e": 37539,
"s": 37535,
"text": "Yes"
},
{
"code": null,
"e": 37554,
"s": 37539,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37562,
"s": 37554,
"text": "ankthon"
},
{
"code": null,
"e": 37576,
"s": 37562,
"text": "princiraj1992"
},
{
"code": null,
"e": 37588,
"s": 37576,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37599,
"s": 37588,
"text": "vikkycirus"
},
{
"code": null,
"e": 37609,
"s": 37599,
"text": "patel2127"
},
{
"code": null,
"e": 37621,
"s": 37609,
"text": "unknown2108"
},
{
"code": null,
"e": 37634,
"s": 37621,
"text": "shinjanpatra"
},
{
"code": null,
"e": 37653,
"s": 37634,
"text": "School Programming"
},
{
"code": null,
"e": 37661,
"s": 37653,
"text": "Strings"
},
{
"code": null,
"e": 37669,
"s": 37661,
"text": "Strings"
},
{
"code": null,
"e": 37767,
"s": 37669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37791,
"s": 37767,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 37810,
"s": 37791,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 37830,
"s": 37810,
"text": "Constructors in C++"
},
{
"code": null,
"e": 37858,
"s": 37830,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 37878,
"s": 37858,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 37924,
"s": 37878,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 37958,
"s": 37924,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 37973,
"s": 37958,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38033,
"s": 37973,
"text": "Write a program to print all permutations of a given string"
}
] |
Java Program to increase the row height in a JTable
|
To increase the row height, use the setRowHeight() method for a table in Java. Row height is the height of the row in pixels.
Let’s say the following is our table −
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
Set the rows and columns and increase the row height by first getting the current height and incrementing it. We are incrementing by 20 pixels here −
table.setRowHeight(table.getRowHeight() + 20);
The following is an example to increase the row height −
package my;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
public static void main(String[] argv) throws Exception {
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
tableModel.addColumn("Language/ Technology");
tableModel.addColumn("Difficulty Level");
tableModel.insertRow(0, new Object[] { "CSS", "Easy" });
tableModel.insertRow(0, new Object[] { "HTML5", "Easy"});
tableModel.insertRow(0, new Object[] { "JavaScript", "Intermediate" });
tableModel.insertRow(0, new Object[] { "jQuery", "Intermediate" });
tableModel.insertRow(0, new Object[] { "AngularJS", "Difficult"});
// adding a new row
tableModel.insertRow(tableModel.getRowCount(), new Object[] {"ExpressJS", "Intermediate" });
// appending a new row
tableModel.addRow(new Object[] { "WordPress", "Easy" });
// set row height
table.setRowHeight(table.getRowHeight() + 20);
JFrame f = new JFrame();
f.setSize(550, 350);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
The output is as follows. Here we have set the row height to 20 −
Now, let us change the row height to 5 and spot the difference −
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "To increase the row height, use the setRowHeight() method for a table in Java. Row height is the height of the row in pixels."
},
{
"code": null,
"e": 1227,
"s": 1188,
"text": "Let’s say the following is our table −"
},
{
"code": null,
"e": 1322,
"s": 1227,
"text": "DefaultTableModel tableModel = new DefaultTableModel();\nJTable table = new JTable(tableModel);"
},
{
"code": null,
"e": 1472,
"s": 1322,
"text": "Set the rows and columns and increase the row height by first getting the current height and incrementing it. We are incrementing by 20 pixels here −"
},
{
"code": null,
"e": 1519,
"s": 1472,
"text": "table.setRowHeight(table.getRowHeight() + 20);"
},
{
"code": null,
"e": 1576,
"s": 1519,
"text": "The following is an example to increase the row height −"
},
{
"code": null,
"e": 2785,
"s": 1576,
"text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n DefaultTableModel tableModel = new DefaultTableModel();\n JTable table = new JTable(tableModel);\n tableModel.addColumn(\"Language/ Technology\");\n tableModel.addColumn(\"Difficulty Level\");\n tableModel.insertRow(0, new Object[] { \"CSS\", \"Easy\" });\n tableModel.insertRow(0, new Object[] { \"HTML5\", \"Easy\"});\n tableModel.insertRow(0, new Object[] { \"JavaScript\", \"Intermediate\" });\n tableModel.insertRow(0, new Object[] { \"jQuery\", \"Intermediate\" });\n tableModel.insertRow(0, new Object[] { \"AngularJS\", \"Difficult\"});\n // adding a new row\n tableModel.insertRow(tableModel.getRowCount(), new Object[] {\"ExpressJS\", \"Intermediate\" });\n // appending a new row\n tableModel.addRow(new Object[] { \"WordPress\", \"Easy\" });\n // set row height\n table.setRowHeight(table.getRowHeight() + 20);\n JFrame f = new JFrame();\n f.setSize(550, 350);\n f.add(new JScrollPane(table));\n f.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2851,
"s": 2785,
"text": "The output is as follows. Here we have set the row height to 20 −"
},
{
"code": null,
"e": 2916,
"s": 2851,
"text": "Now, let us change the row height to 5 and spot the difference −"
}
] |
Image Captioning with Keras. Table of Contents: | by Harshall Lamba | Towards Data Science
|
IntroductionMotivationPrerequisitesData collectionUnderstanding the dataData CleaningLoading the training setData Preprocessing — ImagesData Preprocessing — CaptionsData Preparation using Generator FunctionWord EmbeddingsModel ArchitectureInferenceEvaluationConclusion and Future workReferences
Introduction
Motivation
Prerequisites
Data collection
Understanding the data
Data Cleaning
Loading the training set
Data Preprocessing — Images
Data Preprocessing — Captions
Data Preparation using Generator Function
Word Embeddings
Model Architecture
Inference
Evaluation
Conclusion and Future work
References
What do you see in the below picture?
Well some of you might say “A white dog in a grassy area”, some may say “White dog with brown spots” and yet some others might say “A dog on grass and some pink flowers”.
Definitely all of these captions are relevant for this image and there may be some others also. But the point I want to make is; it’s so easy for us, as human beings, to just have a glance at a picture and describe it in an appropriate language. Even a 5 year old could do this with utmost ease.
But, can you write a computer program that takes an image as input and produces a relevant caption as output?
Just prior to the recent development of Deep Neural Networks this problem was inconceivable even by the most advanced researchers in Computer Vision. But with the advent of Deep Learning this problem can be solved very easily if we have the required dataset.
This problem was well researched by Andrej Karapathy in his PhD thesis at Stanford [1], who is also now the Director of AI at Tesla.
The purpose of this blog post is to explain (in as simple words as possible) that how Deep Learning can be used to solve this problem of generating a caption for a given image, hence the name Image Captioning.
To get a better feel of this problem, I strongly recommend to use this state-of-the-art system created by Microsoft called as Caption Bot. Just go to this link and try uploading any picture you want; this system will generate a caption for it.
We must first understand how important this problem is to real world scenarios. Let’s see few applications where a solution to this problem can be very useful.
Self driving cars — Automatic driving is one of the biggest challenges and if we can properly caption the scene around the car, it can give a boost to the self driving system.
Aid to the blind — We can create a product for the blind which will guide them travelling on the roads without the support of anyone else. We can do this by first converting the scene into text and then the text to voice. Both are now famous applications of Deep Learning. Refer this link where its shown how Nvidia research is trying to create such a product.
CCTV cameras are everywhere today, but along with viewing the world, if we can also generate relevant captions, then we can raise alarms as soon as there is some malicious activity going on somewhere. This could probably help reduce some crime and/or accidents.
Automatic Captioning can help, make Google Image Search as good as Google Search, as then every image could be first converted into a caption and then search can be performed based on the caption.
This post assumes familiarity with basic Deep Learning concepts like Multi-layered Perceptrons, Convolution Neural Networks, Recurrent Neural Networks, Transfer Learning, Gradient Descent, Backpropagation, Overfitting, Probability, Text Processing, Python syntax and data structures, Keras library, etc.
There are many open source datasets available for this problem, like Flickr 8k (containing8k images), Flickr 30k (containing 30k images), MS COCO (containing 180k images), etc.
But for the purpose of this case study, I have used the Flickr 8k dataset which you can download by filling this form provided by the University of Illinois at Urbana-Champaign. Also training a model with large number of images may not be feasible on a system which is not a very high end PC/Laptop.
This dataset contains 8000 images each with 5 captions (as we have already seen in the Introduction section that an image can have multiple captions, all being relevant simultaneously).
These images are bifurcated as follows:
Training Set — 6000 images
Dev Set — 1000 images
Test Set — 1000 images
If you have downloaded the data from the link that I have provided, then, along with images, you will also get some text files related to the images. One of the files is “Flickr8k.token.txt” which contains the name of each image along with its 5 captions. We can read this file as follows:
# Below is the path for the file "Flickr8k.token.txt" on your diskfilename = "/dataset/TextFiles/Flickr8k.token.txt"file = open(filename, 'r')doc = file.read()
The text file looks as follows:
Thus every line contains the <image name>#i <caption>, where 0≤i≤4
i.e. the name of the image, caption number (0 to 4) and the actual caption.
Now, we create a dictionary named “descriptions” which contains the name of the image (without the .jpg extension) as keys and a list of the 5 captions for the corresponding image as values.
For example with reference to the above screenshot the dictionary will look as follows:
descriptions['101654506_8eb26cfb60'] = ['A brown and white dog is running through the snow .', 'A dog is running in the snow', 'A dog running through snow .', 'a white and brown dog is running through a snow covered field .', 'The white and brown dog is running over the surface of the snow .']
When we deal with text, we generally perform some basic cleaning like lower-casing all the words (otherwise“hello” and “Hello” will be regarded as two separate words), removing special tokens (like ‘%’, ‘$’, ‘#’, etc.), eliminating words which contain numbers (like ‘hey199’, etc.).
The below code does these basic cleaning steps:
Create a vocabulary of all the unique words present across all the 8000*5 (i.e. 40000) image captions (corpus) in the data set :
vocabulary = set()for key in descriptions.keys(): [vocabulary.update(d.split()) for d in descriptions[key]]print('Original Vocabulary Size: %d' % len(vocabulary))Original Vocabulary Size: 8763
This means we have 8763 unique words across all the 40000 image captions. We write all these captions along with their image names in a new file namely, “descriptions.txt” and save it on the disk.
However, if we think about it, many of these words will occur very few times, say 1, 2 or 3 times. Since we are creating a predictive model, we would not like to have all the words present in our vocabulary but the words which are more likely to occur or which are common. This helps the model become more robust to outliers and make less mistakes.
Hence we consider only those words which occur at least 10 times in the entire corpus. The code for this is below:
So now we have only 1651 unique words in our vocabulary. However, we will append 0’s (zero padding explained later) and thus total words = 1651+1 = 1652 (one index for the 0).
The text file “Flickr_8k.trainImages.txt” contains the names of the images that belong to the training set. So we load these names into a list “train”.
filename = 'dataset/TextFiles/Flickr_8k.trainImages.txt'doc = load_doc(filename)train = list()for line in doc.split('\n'): identifier = line.split('.')[0] train.append(identifier)print('Dataset: %d' % len(train))Dataset: 6000
Thus we have separated the 6000 training images in the list named “train”.
Now, we load the descriptions of these images from “descriptions.txt” (saved on the hard disk) in the Python dictionary “train_descriptions”.
However, when we load them, we will add two tokens in every caption as follows (significance explained later):
‘startseq’ -> This is a start sequence token which will be added at the start of every caption.
‘endseq’ -> This is an end sequence token which will be added at the end of every caption.
Images are nothing but input (X) to our model. As you may already know that any input to a model must be given in the form of a vector.
We need to convert every image into a fixed sized vector which can then be fed as input to the neural network. For this purpose, we opt for transfer learning by using the InceptionV3 model (Convolutional Neural Network) created by Google Research.
This model was trained on Imagenet dataset to perform image classification on 1000 different classes of images. However, our purpose here is not to classify the image but just get fixed-length informative vector for each image. This process is called automatic feature engineering.
Hence, we just remove the last softmax layer from the model and extract a 2048 length vector (bottleneck features) for every image as follows:
The code for this is as follows:
# Get the InceptionV3 model trained on imagenet datamodel = InceptionV3(weights='imagenet')# Remove the last layer (output softmax layer) from the inception v3model_new = Model(model.input, model.layers[-2].output)
Now, we pass every image to this model to get the corresponding 2048 length feature vector as follows:
# Convert all the images to size 299x299 as expected by the# inception v3 modelimg = image.load_img(image_path, target_size=(299, 299))# Convert PIL image to numpy array of 3-dimensionsx = image.img_to_array(img)# Add one more dimensionx = np.expand_dims(x, axis=0)# preprocess images using preprocess_input() from inception modulex = preprocess_input(x)# reshape from (1, 2048) to (2048, )x = np.reshape(x, x.shape[1])
We save all the bottleneck train features in a Python dictionary and save it on the disk using Pickle file, namely “encoded_train_images.pkl” whose keys are image names and values are corresponding 2048 length feature vector.
NOTE: This process might take an hour or two if you do not have a high end PC/laptop.
Similarly we encode all the test images and save them in the file “encoded_test_images.pkl”.
We must note that captions are something that we want to predict. So during the training period, captions will be the target variables (Y) that the model is learning to predict.
But the prediction of the entire caption, given the image does not happen at once. We will predict the caption word by word. Thus, we need to encode each word into a fixed sized vector. However, this part will be seen later when we look at the model design, but for now we will create two Python Dictionaries namely “wordtoix” (pronounced — word to index) and “ixtoword” (pronounced — index to word).
Stating simply, we will represent every unique word in the vocabulary by an integer (index). As seen above, we have 1652 unique words in the corpus and thus each word will be represented by an integer index between 1 to 1652.
These two Python dictionaries can be used as follows:
wordtoix[‘abc’] -> returns index of the word ‘abc’
ixtoword[k] -> returns the word whose index is ‘k’
The code used is as below:
ixtoword = {}wordtoix = {}ix = 1for w in vocab: wordtoix[w] = ix ixtoword[ix] = w ix += 1
There is one more parameter that we need to calculate, i.e., the maximum length of a caption and we do it as below:
# convert a dictionary of clean descriptions to a list of descriptionsdef to_lines(descriptions): all_desc = list() for key in descriptions.keys(): [all_desc.append(d) for d in descriptions[key]] return all_desc# calculate the length of the description with the most wordsdef max_length(descriptions): lines = to_lines(descriptions) return max(len(d.split()) for d in lines)# determine the maximum sequence lengthmax_length = max_length(train_descriptions)print('Max Description Length: %d' % max_length)Max Description Length: 34
So the maximum length of any caption is 34.
This is one of the most important steps in this case study. Here we will understand how to prepare the data in a manner which will be convenient to be given as input to the deep learning model.
Hereafter, I will try to explain the remaining steps by taking a sample example as follows:
Consider we have 3 images and their 3 corresponding captions as follows:
Now, let’s say we use the first two images and their captions to train the model and the third image to test our model.
Now the questions that will be answered are: how do we frame this as a supervised learning problem?, what does the data matrix look like? how many data points do we have?, etc.
First we need to convert both the images to their corresponding 2048 length feature vector as discussed above. Let “Image_1” and “Image_2” be the feature vectors of the first two images respectively
Secondly, let’s build the vocabulary for the first two (train) captions by adding the two tokens “startseq” and “endseq” in both of them: (Assume we have already performed the basic cleaning steps)
Caption_1 -> “startseq the black cat sat on grass endseq”
Caption_2 -> “startseq the white cat is walking on road endseq”
vocab = {black, cat, endseq, grass, is, on, road, sat, startseq, the, walking, white}
Let’s give an index to each word in the vocabulary:
black -1, cat -2, endseq -3, grass -4, is -5, on -6, road -7, sat -8, startseq -9, the -10, walking -11, white -12
Now let’s try to frame it as a supervised learning problem where we have a set of data points D = {Xi, Yi}, where Xi is the feature vector of data point ‘i’ and Yi is the corresponding target variable.
Let’s take the first image vector Image_1 and its corresponding caption “startseq the black cat sat on grass endseq”. Recall that, Image vector is the input and the caption is what we need to predict. But the way we predict the caption is as follows:
For the first time, we provide the image vector and the first word as input and try to predict the second word, i.e.:
Input = Image_1 + ‘startseq’; Output = ‘the’
Then we provide image vector and the first two words as input and try to predict the third word, i.e.:
Input = Image_1 + ‘startseq the’; Output = ‘cat’
And so on...
Thus, we can summarize the data matrix for one image and its corresponding caption as follows:
It must be noted that, one image+caption is not a single data point but are multiple data points depending on the length of the caption.
Similarly if we consider both the images and their captions, our data matrix will then look as follows:
We must now understand that in every data point, it’s not just the image which goes as input to the system, but also, a partial caption which helps to predict the next word in the sequence.
Since we are processing sequences, we will employ a Recurrent Neural Network to read these partial captions (more on this later).
However, we have already discussed that we are not going to pass the actual English text of the caption, rather we are going to pass the sequence of indices where each index represents a unique word.
Since we have already created an index for each word, let’s now replace the words with their indices and understand how the data matrix will look like:
Since we would be doing batch processing (explained later), we need to make sure that each sequence is of equal length. Hence we need to append 0’s (zero padding) at the end of each sequence. But how many zeros should we append in each sequence?
Well, this is the reason we had calculated the maximum length of a caption, which is 34 (if you remember). So we will append those many number of zeros which will lead to every sequence having a length of 34.
The data matrix will then look as follows:
Need for a Data Generator:
I hope this gives you a good sense as to how we can prepare the dataset for this problem. However, there is a big catch in this.
In the above example, I have only considered 2 images and captions which have lead to 15 data points.
However, in our actual training dataset we have 6000 images, each having 5 captions. This makes a total of 30000 images and captions.
Even if we assume that each caption on an average is just 7 words long, it will lead to a total of 30000*7 i.e. 210000 data points.
Compute the size of the data matrix:
Size of the data matrix = n*m
Where n-> number of data points (assumed as 210000)
And m-> length of each data point
Clearly m= Length of image vector(2048) + Length of partial caption(x).
m = 2048 + x
But what is the value of x?
Well you might think it is 34, but no wait, it’s wrong.
Every word (or index) will be mapped (embedded) to higher dimensional space through one of the word embedding techniques.
Later, during the model building stage, we will see that each word/index is mapped to a 200-long vector using a pre-trained GLOVE word embedding model.
Now each sequence contains 34 indices, where each index is a vector of length 200. Therefore x = 34*200 = 6800
Hence, m = 2048 + 6800 = 8848.
Finally, size of data matrix= 210000 * 8848= 1858080000 blocks.
Now even if we assume that one block takes 2 byte, then, to store this data matrix, we will require more than 3 GB of main memory.
This is pretty huge requirement and even if we are able to manage to load this much data into the RAM, it will make the system very slow.
For this reason we use data generators a lot in Deep Learning. Data Generators are a functionality which is natively implemented in Python. The ImageDataGenerator class provided by the Keras API is nothing but an implementation of generator function in Python.
So how does using a generator function solve this problem?
If you know the basics of Deep Learning, then you must know that to train a model on a particular dataset, we use some version of Stochastic Gradient Descent (SGD) like Adam, Rmsprop, Adagrad, etc.
With SGD, we do not calculate the loss on the entire data set to update the gradients. Rather in every iteration, we calculate the loss on a batch of data points (typically 64, 128, 256, etc.) to update the gradients.
This means that we do not require to store the entire dataset in the memory at once. Even if we have the current batch of points in the memory, it is sufficient for our purpose.
A generator function in Python is used exactly for this purpose. It’s like an iterator which resumes the functionality from the point it left the last time it was called.
To understand more about Generators, please read here.
The code for data generator is as follows:
As already stated above, we will map the every word (index) to a 200-long vector and for this purpose, we will use a pre-trained GLOVE Model:
# Load Glove vectorsglove_dir = 'dataset/glove'embeddings_index = {} # empty dictionaryf = open(os.path.join(glove_dir, 'glove.6B.200d.txt'), encoding="utf-8")for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefsf.close()
Now, for all the 1652 unique words in our vocabulary, we create an embedding matrix which will be loaded into the model before training.
embedding_dim = 200# Get 200-dim dense vector for each of the 10000 words in out vocabularyembedding_matrix = np.zeros((vocab_size, embedding_dim))for word, i in wordtoix.items(): #if i < max_words: embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # Words not found in the embedding index will be all zeros embedding_matrix[i] = embedding_vector
To understand more about word embeddings, please refer this link
Since the input consists of two parts, an image vector and a partial caption, we cannot use the Sequential API provided by the Keras library. For this reason, we use the Functional API which allows us to create Merge Models.
First, let’s look at the brief architecture which contains the high level sub-modules:
We define the model as follows:
Let’s look at the model summary:
The below plot helps to visualize the structure of the network and better understand the two streams of input:
The text in red on the right side are the comments provided for you to map your understanding of the data preparation to model architecture.
The LSTM (Long Short Term Memory) layer is nothing but a specialized Recurrent Neural Network to process the sequence input (partial captions in our case). To read more about LSTM, click here.
If you have followed the previous section, I think reading these comments should help you to understand the model architecture in a straight forward manner.
Recall that we had created an embedding matrix from a pre-trained Glove model which we need to include in the model before starting the training:
model.layers[2].set_weights([embedding_matrix])model.layers[2].trainable = False
Notice that since we are using a pre-trained embedding layer, we need to freeze it (trainable = False), before training the model, so that it does not get updated during the backpropagation.
Finally we compile the model using the adam optimizer
model.compile(loss=’categorical_crossentropy’, optimizer=’adam’)
Finally the weights of the model will be updated through backpropagation algorithm and the model will learn to output a word, given an image feature vector and a partial caption. So in summary, we have:
Input_1 -> Partial Caption
Input_2 -> Image feature vector
Output -> An appropriate word, next in the sequence of partial caption provided in the input_1 (or in probability terms we say conditioned on image vector and the partial caption)
Hyper parameters during training:
The model was then trained for 30 epochs with the initial learning rate of 0.001 and 3 pictures per batch (batch size). However after 20 epochs, the learning rate was reduced to 0.0001 and the model was trained on 6 pictures per batch.
This generally makes sense because during the later stages of training, since the model is moving towards convergence, we must lower the learning rate so that we take smaller steps towards the minima. Also increasing the batch size over time helps your gradient updates to be more powerful.
Time Taken: I used the GPU+ Gradient Notebook on www.paperspace.com and hence it took me approximately an hour to train the model. However if you train it on a PC without GPU, it could take anywhere from 8 to 16 hours depending on the configuration of your system.
So till now, we have seen how to prepare the data and build the model. In the final step of this series, we will understand how do we test (infer) our model by passing in new images, i.e. how can we generate a caption for a new test image.
Recall that in the example where we saw how to prepare the data, we used only first two images and their captions. Now let’s use the third image and try to understand how we would like the caption to be generated.
The third image vector and caption were as follows:
Caption -> the black cat is walking on grass
Also the vocabulary in the example was:
vocab = {black, cat, endseq, grass, is, on, road, sat, startseq, the, walking, white}
We will generate the caption iteratively, one word at a time as follows:
Iteration 1:
Input: Image vector + “startseq” (as partial caption)
Expected Output word: “the”
(You should now understand the importance of the token ‘startseq’ which is used as the initial partial caption for any image during inference).
But wait, the model generates a 12-long vector(in the sample example while 1652-long vector in the original example) which is a probability distribution across all the words in the vocabulary. For this reason we greedily select the word with the maximum probability, given the feature vector and partial caption.
If the model is trained well, we must expect the probability for the word “the” to be maximum:
This is called as Maximum Likelihood Estimation (MLE) i.e. we select that word which is most likely according to the model for the given input. And sometimes this method is also called as Greedy Search, as we greedily select the word with maximum probability.
Iteration 2:
Input: Image vector + “startseq the”
Expected Output word: “black”
Iteration 3:
Input: Image vector + “startseq the black”
Expected Output word: “cat”
Iteration 4:
Input: Image vector + “startseq the black cat”
Expected Output word: “is”
Iteration 5:
Input: Image vector + “startseq the black cat is”
Expected Output word: “walking”
Iteration 6:
Input: Image vector + “startseq the black cat is walking”
Expected Output word: “on”
Iteration 7:
Input: Image vector + “startseq the black cat is walking on”
Expected Output word: “grass”
Iteration 8:
Input: Image vector + “startseq the black cat is walking on grass”
Expected Output word: “endseq”
This is where we stop the iterations.
So we stop when either of the below two conditions is met:
We encounter an ‘endseq’ token which means the model thinks that this is the end of the caption. (You should now understand the importance of the ‘endseq’ token)
We reach a maximum threshold of the number of words generated by the model.
If any of the above conditions is met, we break the loop and report the generated caption as the output of the model for the given image. The code for inference is as follows:
To understand how good the model is, let’s try to generate captions on images from the test dataset (i.e. the images which the model did not see during the training).
Note: We must appreciate how the model is able to identify the colors precisely.
Of course, I would be fooling you if I only showed you the appropriate captions. No model in the world is ever perfect and this model also makes mistakes. Let’s look at some examples where the captions are not very relevant and sometimes even irrelevant.
Probably the color of the shirt got mixed with the color in the background
Why does the model classify the famous Rafael Nadal as a woman :-) ? Probably because of the long hair.
The model gets the grammar incorrect this time
Clearly, the model tried its best to understand the scenario but still the caption is not a good one.
Again one more example where the model fails and the caption is irrelevant.
So all in all, I must say that my naive first-cut model, without any rigorous hyper-parameter tuning does a decent job in generating captions for images.
Important Point:
We must understand that the images used for testing must be semantically related to those used for training the model. For example, if we train our model on the images of cats, dogs, etc. we must not test it on images of air planes, waterfalls, etc. This is an example where the distribution of the train and test sets will be very different and in such cases no Machine Learning model in the world will give good performance.
Thanks a lot if you have reached here. This is my first attempt in blogging so I expect the readers to be a bit generous and ignore the minor mistakes I might have made.
Please refer my GitHub link here to access the full code written in Jupyter Notebook.
Note that due to the stochastic nature of the models, the captions generated by you (if you try to replicate the code) may not be exactly similar to those generated in my case.
Of course this is just a first-cut solution and a lot of modifications can be made to improve this solution like:
Using a larger dataset.
Changing the model architecture, e.g. include an attention module.
Doing more hyper parameter tuning (learning rate, batch size, number of layers, number of units, dropout rate, batch normalization etc.).
Use the cross validation set to understand overfitting.
Using Beam Search instead of Greedy Search during Inference.
Using BLEU Score to evaluate and measure the performance of the model.
Writing the code in a proper object oriented way so that it becomes easier for others to replicate :-)
https://cs.stanford.edu/people/karpathy/cvpr2015.pdfhttps://arxiv.org/abs/1411.4555https://arxiv.org/abs/1703.09137https://arxiv.org/abs/1708.02043https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/https://www.youtube.com/watch?v=yk6XDFm3J2chttps://www.appliedaicourse.com/
https://cs.stanford.edu/people/karpathy/cvpr2015.pdf
https://arxiv.org/abs/1411.4555
https://arxiv.org/abs/1703.09137
https://arxiv.org/abs/1708.02043
https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/
https://www.youtube.com/watch?v=yk6XDFm3J2c
https://www.appliedaicourse.com/
PS: Feel free to provide comments/criticisms if you think they can improve this blog, I will definitely try to make the required changes.
|
[
{
"code": null,
"e": 466,
"s": 171,
"text": "IntroductionMotivationPrerequisitesData collectionUnderstanding the dataData CleaningLoading the training setData Preprocessing — ImagesData Preprocessing — CaptionsData Preparation using Generator FunctionWord EmbeddingsModel ArchitectureInferenceEvaluationConclusion and Future workReferences"
},
{
"code": null,
"e": 479,
"s": 466,
"text": "Introduction"
},
{
"code": null,
"e": 490,
"s": 479,
"text": "Motivation"
},
{
"code": null,
"e": 504,
"s": 490,
"text": "Prerequisites"
},
{
"code": null,
"e": 520,
"s": 504,
"text": "Data collection"
},
{
"code": null,
"e": 543,
"s": 520,
"text": "Understanding the data"
},
{
"code": null,
"e": 557,
"s": 543,
"text": "Data Cleaning"
},
{
"code": null,
"e": 582,
"s": 557,
"text": "Loading the training set"
},
{
"code": null,
"e": 610,
"s": 582,
"text": "Data Preprocessing — Images"
},
{
"code": null,
"e": 640,
"s": 610,
"text": "Data Preprocessing — Captions"
},
{
"code": null,
"e": 682,
"s": 640,
"text": "Data Preparation using Generator Function"
},
{
"code": null,
"e": 698,
"s": 682,
"text": "Word Embeddings"
},
{
"code": null,
"e": 717,
"s": 698,
"text": "Model Architecture"
},
{
"code": null,
"e": 727,
"s": 717,
"text": "Inference"
},
{
"code": null,
"e": 738,
"s": 727,
"text": "Evaluation"
},
{
"code": null,
"e": 765,
"s": 738,
"text": "Conclusion and Future work"
},
{
"code": null,
"e": 776,
"s": 765,
"text": "References"
},
{
"code": null,
"e": 814,
"s": 776,
"text": "What do you see in the below picture?"
},
{
"code": null,
"e": 985,
"s": 814,
"text": "Well some of you might say “A white dog in a grassy area”, some may say “White dog with brown spots” and yet some others might say “A dog on grass and some pink flowers”."
},
{
"code": null,
"e": 1281,
"s": 985,
"text": "Definitely all of these captions are relevant for this image and there may be some others also. But the point I want to make is; it’s so easy for us, as human beings, to just have a glance at a picture and describe it in an appropriate language. Even a 5 year old could do this with utmost ease."
},
{
"code": null,
"e": 1391,
"s": 1281,
"text": "But, can you write a computer program that takes an image as input and produces a relevant caption as output?"
},
{
"code": null,
"e": 1650,
"s": 1391,
"text": "Just prior to the recent development of Deep Neural Networks this problem was inconceivable even by the most advanced researchers in Computer Vision. But with the advent of Deep Learning this problem can be solved very easily if we have the required dataset."
},
{
"code": null,
"e": 1783,
"s": 1650,
"text": "This problem was well researched by Andrej Karapathy in his PhD thesis at Stanford [1], who is also now the Director of AI at Tesla."
},
{
"code": null,
"e": 1993,
"s": 1783,
"text": "The purpose of this blog post is to explain (in as simple words as possible) that how Deep Learning can be used to solve this problem of generating a caption for a given image, hence the name Image Captioning."
},
{
"code": null,
"e": 2237,
"s": 1993,
"text": "To get a better feel of this problem, I strongly recommend to use this state-of-the-art system created by Microsoft called as Caption Bot. Just go to this link and try uploading any picture you want; this system will generate a caption for it."
},
{
"code": null,
"e": 2397,
"s": 2237,
"text": "We must first understand how important this problem is to real world scenarios. Let’s see few applications where a solution to this problem can be very useful."
},
{
"code": null,
"e": 2573,
"s": 2397,
"text": "Self driving cars — Automatic driving is one of the biggest challenges and if we can properly caption the scene around the car, it can give a boost to the self driving system."
},
{
"code": null,
"e": 2934,
"s": 2573,
"text": "Aid to the blind — We can create a product for the blind which will guide them travelling on the roads without the support of anyone else. We can do this by first converting the scene into text and then the text to voice. Both are now famous applications of Deep Learning. Refer this link where its shown how Nvidia research is trying to create such a product."
},
{
"code": null,
"e": 3196,
"s": 2934,
"text": "CCTV cameras are everywhere today, but along with viewing the world, if we can also generate relevant captions, then we can raise alarms as soon as there is some malicious activity going on somewhere. This could probably help reduce some crime and/or accidents."
},
{
"code": null,
"e": 3393,
"s": 3196,
"text": "Automatic Captioning can help, make Google Image Search as good as Google Search, as then every image could be first converted into a caption and then search can be performed based on the caption."
},
{
"code": null,
"e": 3697,
"s": 3393,
"text": "This post assumes familiarity with basic Deep Learning concepts like Multi-layered Perceptrons, Convolution Neural Networks, Recurrent Neural Networks, Transfer Learning, Gradient Descent, Backpropagation, Overfitting, Probability, Text Processing, Python syntax and data structures, Keras library, etc."
},
{
"code": null,
"e": 3874,
"s": 3697,
"text": "There are many open source datasets available for this problem, like Flickr 8k (containing8k images), Flickr 30k (containing 30k images), MS COCO (containing 180k images), etc."
},
{
"code": null,
"e": 4174,
"s": 3874,
"text": "But for the purpose of this case study, I have used the Flickr 8k dataset which you can download by filling this form provided by the University of Illinois at Urbana-Champaign. Also training a model with large number of images may not be feasible on a system which is not a very high end PC/Laptop."
},
{
"code": null,
"e": 4360,
"s": 4174,
"text": "This dataset contains 8000 images each with 5 captions (as we have already seen in the Introduction section that an image can have multiple captions, all being relevant simultaneously)."
},
{
"code": null,
"e": 4400,
"s": 4360,
"text": "These images are bifurcated as follows:"
},
{
"code": null,
"e": 4427,
"s": 4400,
"text": "Training Set — 6000 images"
},
{
"code": null,
"e": 4449,
"s": 4427,
"text": "Dev Set — 1000 images"
},
{
"code": null,
"e": 4472,
"s": 4449,
"text": "Test Set — 1000 images"
},
{
"code": null,
"e": 4762,
"s": 4472,
"text": "If you have downloaded the data from the link that I have provided, then, along with images, you will also get some text files related to the images. One of the files is “Flickr8k.token.txt” which contains the name of each image along with its 5 captions. We can read this file as follows:"
},
{
"code": null,
"e": 4922,
"s": 4762,
"text": "# Below is the path for the file \"Flickr8k.token.txt\" on your diskfilename = \"/dataset/TextFiles/Flickr8k.token.txt\"file = open(filename, 'r')doc = file.read()"
},
{
"code": null,
"e": 4954,
"s": 4922,
"text": "The text file looks as follows:"
},
{
"code": null,
"e": 5021,
"s": 4954,
"text": "Thus every line contains the <image name>#i <caption>, where 0≤i≤4"
},
{
"code": null,
"e": 5097,
"s": 5021,
"text": "i.e. the name of the image, caption number (0 to 4) and the actual caption."
},
{
"code": null,
"e": 5288,
"s": 5097,
"text": "Now, we create a dictionary named “descriptions” which contains the name of the image (without the .jpg extension) as keys and a list of the 5 captions for the corresponding image as values."
},
{
"code": null,
"e": 5376,
"s": 5288,
"text": "For example with reference to the above screenshot the dictionary will look as follows:"
},
{
"code": null,
"e": 5671,
"s": 5376,
"text": "descriptions['101654506_8eb26cfb60'] = ['A brown and white dog is running through the snow .', 'A dog is running in the snow', 'A dog running through snow .', 'a white and brown dog is running through a snow covered field .', 'The white and brown dog is running over the surface of the snow .']"
},
{
"code": null,
"e": 5954,
"s": 5671,
"text": "When we deal with text, we generally perform some basic cleaning like lower-casing all the words (otherwise“hello” and “Hello” will be regarded as two separate words), removing special tokens (like ‘%’, ‘$’, ‘#’, etc.), eliminating words which contain numbers (like ‘hey199’, etc.)."
},
{
"code": null,
"e": 6002,
"s": 5954,
"text": "The below code does these basic cleaning steps:"
},
{
"code": null,
"e": 6131,
"s": 6002,
"text": "Create a vocabulary of all the unique words present across all the 8000*5 (i.e. 40000) image captions (corpus) in the data set :"
},
{
"code": null,
"e": 6327,
"s": 6131,
"text": "vocabulary = set()for key in descriptions.keys(): [vocabulary.update(d.split()) for d in descriptions[key]]print('Original Vocabulary Size: %d' % len(vocabulary))Original Vocabulary Size: 8763"
},
{
"code": null,
"e": 6524,
"s": 6327,
"text": "This means we have 8763 unique words across all the 40000 image captions. We write all these captions along with their image names in a new file namely, “descriptions.txt” and save it on the disk."
},
{
"code": null,
"e": 6873,
"s": 6524,
"text": "However, if we think about it, many of these words will occur very few times, say 1, 2 or 3 times. Since we are creating a predictive model, we would not like to have all the words present in our vocabulary but the words which are more likely to occur or which are common. This helps the model become more robust to outliers and make less mistakes."
},
{
"code": null,
"e": 6988,
"s": 6873,
"text": "Hence we consider only those words which occur at least 10 times in the entire corpus. The code for this is below:"
},
{
"code": null,
"e": 7164,
"s": 6988,
"text": "So now we have only 1651 unique words in our vocabulary. However, we will append 0’s (zero padding explained later) and thus total words = 1651+1 = 1652 (one index for the 0)."
},
{
"code": null,
"e": 7316,
"s": 7164,
"text": "The text file “Flickr_8k.trainImages.txt” contains the names of the images that belong to the training set. So we load these names into a list “train”."
},
{
"code": null,
"e": 7548,
"s": 7316,
"text": "filename = 'dataset/TextFiles/Flickr_8k.trainImages.txt'doc = load_doc(filename)train = list()for line in doc.split('\\n'): identifier = line.split('.')[0] train.append(identifier)print('Dataset: %d' % len(train))Dataset: 6000"
},
{
"code": null,
"e": 7623,
"s": 7548,
"text": "Thus we have separated the 6000 training images in the list named “train”."
},
{
"code": null,
"e": 7765,
"s": 7623,
"text": "Now, we load the descriptions of these images from “descriptions.txt” (saved on the hard disk) in the Python dictionary “train_descriptions”."
},
{
"code": null,
"e": 7876,
"s": 7765,
"text": "However, when we load them, we will add two tokens in every caption as follows (significance explained later):"
},
{
"code": null,
"e": 7972,
"s": 7876,
"text": "‘startseq’ -> This is a start sequence token which will be added at the start of every caption."
},
{
"code": null,
"e": 8063,
"s": 7972,
"text": "‘endseq’ -> This is an end sequence token which will be added at the end of every caption."
},
{
"code": null,
"e": 8199,
"s": 8063,
"text": "Images are nothing but input (X) to our model. As you may already know that any input to a model must be given in the form of a vector."
},
{
"code": null,
"e": 8447,
"s": 8199,
"text": "We need to convert every image into a fixed sized vector which can then be fed as input to the neural network. For this purpose, we opt for transfer learning by using the InceptionV3 model (Convolutional Neural Network) created by Google Research."
},
{
"code": null,
"e": 8729,
"s": 8447,
"text": "This model was trained on Imagenet dataset to perform image classification on 1000 different classes of images. However, our purpose here is not to classify the image but just get fixed-length informative vector for each image. This process is called automatic feature engineering."
},
{
"code": null,
"e": 8872,
"s": 8729,
"text": "Hence, we just remove the last softmax layer from the model and extract a 2048 length vector (bottleneck features) for every image as follows:"
},
{
"code": null,
"e": 8905,
"s": 8872,
"text": "The code for this is as follows:"
},
{
"code": null,
"e": 9120,
"s": 8905,
"text": "# Get the InceptionV3 model trained on imagenet datamodel = InceptionV3(weights='imagenet')# Remove the last layer (output softmax layer) from the inception v3model_new = Model(model.input, model.layers[-2].output)"
},
{
"code": null,
"e": 9223,
"s": 9120,
"text": "Now, we pass every image to this model to get the corresponding 2048 length feature vector as follows:"
},
{
"code": null,
"e": 9643,
"s": 9223,
"text": "# Convert all the images to size 299x299 as expected by the# inception v3 modelimg = image.load_img(image_path, target_size=(299, 299))# Convert PIL image to numpy array of 3-dimensionsx = image.img_to_array(img)# Add one more dimensionx = np.expand_dims(x, axis=0)# preprocess images using preprocess_input() from inception modulex = preprocess_input(x)# reshape from (1, 2048) to (2048, )x = np.reshape(x, x.shape[1])"
},
{
"code": null,
"e": 9869,
"s": 9643,
"text": "We save all the bottleneck train features in a Python dictionary and save it on the disk using Pickle file, namely “encoded_train_images.pkl” whose keys are image names and values are corresponding 2048 length feature vector."
},
{
"code": null,
"e": 9955,
"s": 9869,
"text": "NOTE: This process might take an hour or two if you do not have a high end PC/laptop."
},
{
"code": null,
"e": 10048,
"s": 9955,
"text": "Similarly we encode all the test images and save them in the file “encoded_test_images.pkl”."
},
{
"code": null,
"e": 10226,
"s": 10048,
"text": "We must note that captions are something that we want to predict. So during the training period, captions will be the target variables (Y) that the model is learning to predict."
},
{
"code": null,
"e": 10627,
"s": 10226,
"text": "But the prediction of the entire caption, given the image does not happen at once. We will predict the caption word by word. Thus, we need to encode each word into a fixed sized vector. However, this part will be seen later when we look at the model design, but for now we will create two Python Dictionaries namely “wordtoix” (pronounced — word to index) and “ixtoword” (pronounced — index to word)."
},
{
"code": null,
"e": 10853,
"s": 10627,
"text": "Stating simply, we will represent every unique word in the vocabulary by an integer (index). As seen above, we have 1652 unique words in the corpus and thus each word will be represented by an integer index between 1 to 1652."
},
{
"code": null,
"e": 10907,
"s": 10853,
"text": "These two Python dictionaries can be used as follows:"
},
{
"code": null,
"e": 10958,
"s": 10907,
"text": "wordtoix[‘abc’] -> returns index of the word ‘abc’"
},
{
"code": null,
"e": 11009,
"s": 10958,
"text": "ixtoword[k] -> returns the word whose index is ‘k’"
},
{
"code": null,
"e": 11036,
"s": 11009,
"text": "The code used is as below:"
},
{
"code": null,
"e": 11135,
"s": 11036,
"text": "ixtoword = {}wordtoix = {}ix = 1for w in vocab: wordtoix[w] = ix ixtoword[ix] = w ix += 1"
},
{
"code": null,
"e": 11251,
"s": 11135,
"text": "There is one more parameter that we need to calculate, i.e., the maximum length of a caption and we do it as below:"
},
{
"code": null,
"e": 11783,
"s": 11251,
"text": "# convert a dictionary of clean descriptions to a list of descriptionsdef to_lines(descriptions): all_desc = list() for key in descriptions.keys(): [all_desc.append(d) for d in descriptions[key]] return all_desc# calculate the length of the description with the most wordsdef max_length(descriptions): lines = to_lines(descriptions) return max(len(d.split()) for d in lines)# determine the maximum sequence lengthmax_length = max_length(train_descriptions)print('Max Description Length: %d' % max_length)Max Description Length: 34"
},
{
"code": null,
"e": 11827,
"s": 11783,
"text": "So the maximum length of any caption is 34."
},
{
"code": null,
"e": 12021,
"s": 11827,
"text": "This is one of the most important steps in this case study. Here we will understand how to prepare the data in a manner which will be convenient to be given as input to the deep learning model."
},
{
"code": null,
"e": 12113,
"s": 12021,
"text": "Hereafter, I will try to explain the remaining steps by taking a sample example as follows:"
},
{
"code": null,
"e": 12186,
"s": 12113,
"text": "Consider we have 3 images and their 3 corresponding captions as follows:"
},
{
"code": null,
"e": 12306,
"s": 12186,
"text": "Now, let’s say we use the first two images and their captions to train the model and the third image to test our model."
},
{
"code": null,
"e": 12483,
"s": 12306,
"text": "Now the questions that will be answered are: how do we frame this as a supervised learning problem?, what does the data matrix look like? how many data points do we have?, etc."
},
{
"code": null,
"e": 12682,
"s": 12483,
"text": "First we need to convert both the images to their corresponding 2048 length feature vector as discussed above. Let “Image_1” and “Image_2” be the feature vectors of the first two images respectively"
},
{
"code": null,
"e": 12880,
"s": 12682,
"text": "Secondly, let’s build the vocabulary for the first two (train) captions by adding the two tokens “startseq” and “endseq” in both of them: (Assume we have already performed the basic cleaning steps)"
},
{
"code": null,
"e": 12938,
"s": 12880,
"text": "Caption_1 -> “startseq the black cat sat on grass endseq”"
},
{
"code": null,
"e": 13002,
"s": 12938,
"text": "Caption_2 -> “startseq the white cat is walking on road endseq”"
},
{
"code": null,
"e": 13088,
"s": 13002,
"text": "vocab = {black, cat, endseq, grass, is, on, road, sat, startseq, the, walking, white}"
},
{
"code": null,
"e": 13140,
"s": 13088,
"text": "Let’s give an index to each word in the vocabulary:"
},
{
"code": null,
"e": 13255,
"s": 13140,
"text": "black -1, cat -2, endseq -3, grass -4, is -5, on -6, road -7, sat -8, startseq -9, the -10, walking -11, white -12"
},
{
"code": null,
"e": 13457,
"s": 13255,
"text": "Now let’s try to frame it as a supervised learning problem where we have a set of data points D = {Xi, Yi}, where Xi is the feature vector of data point ‘i’ and Yi is the corresponding target variable."
},
{
"code": null,
"e": 13708,
"s": 13457,
"text": "Let’s take the first image vector Image_1 and its corresponding caption “startseq the black cat sat on grass endseq”. Recall that, Image vector is the input and the caption is what we need to predict. But the way we predict the caption is as follows:"
},
{
"code": null,
"e": 13826,
"s": 13708,
"text": "For the first time, we provide the image vector and the first word as input and try to predict the second word, i.e.:"
},
{
"code": null,
"e": 13871,
"s": 13826,
"text": "Input = Image_1 + ‘startseq’; Output = ‘the’"
},
{
"code": null,
"e": 13974,
"s": 13871,
"text": "Then we provide image vector and the first two words as input and try to predict the third word, i.e.:"
},
{
"code": null,
"e": 14023,
"s": 13974,
"text": "Input = Image_1 + ‘startseq the’; Output = ‘cat’"
},
{
"code": null,
"e": 14036,
"s": 14023,
"text": "And so on..."
},
{
"code": null,
"e": 14131,
"s": 14036,
"text": "Thus, we can summarize the data matrix for one image and its corresponding caption as follows:"
},
{
"code": null,
"e": 14268,
"s": 14131,
"text": "It must be noted that, one image+caption is not a single data point but are multiple data points depending on the length of the caption."
},
{
"code": null,
"e": 14372,
"s": 14268,
"text": "Similarly if we consider both the images and their captions, our data matrix will then look as follows:"
},
{
"code": null,
"e": 14562,
"s": 14372,
"text": "We must now understand that in every data point, it’s not just the image which goes as input to the system, but also, a partial caption which helps to predict the next word in the sequence."
},
{
"code": null,
"e": 14692,
"s": 14562,
"text": "Since we are processing sequences, we will employ a Recurrent Neural Network to read these partial captions (more on this later)."
},
{
"code": null,
"e": 14892,
"s": 14692,
"text": "However, we have already discussed that we are not going to pass the actual English text of the caption, rather we are going to pass the sequence of indices where each index represents a unique word."
},
{
"code": null,
"e": 15044,
"s": 14892,
"text": "Since we have already created an index for each word, let’s now replace the words with their indices and understand how the data matrix will look like:"
},
{
"code": null,
"e": 15290,
"s": 15044,
"text": "Since we would be doing batch processing (explained later), we need to make sure that each sequence is of equal length. Hence we need to append 0’s (zero padding) at the end of each sequence. But how many zeros should we append in each sequence?"
},
{
"code": null,
"e": 15499,
"s": 15290,
"text": "Well, this is the reason we had calculated the maximum length of a caption, which is 34 (if you remember). So we will append those many number of zeros which will lead to every sequence having a length of 34."
},
{
"code": null,
"e": 15542,
"s": 15499,
"text": "The data matrix will then look as follows:"
},
{
"code": null,
"e": 15569,
"s": 15542,
"text": "Need for a Data Generator:"
},
{
"code": null,
"e": 15698,
"s": 15569,
"text": "I hope this gives you a good sense as to how we can prepare the dataset for this problem. However, there is a big catch in this."
},
{
"code": null,
"e": 15800,
"s": 15698,
"text": "In the above example, I have only considered 2 images and captions which have lead to 15 data points."
},
{
"code": null,
"e": 15934,
"s": 15800,
"text": "However, in our actual training dataset we have 6000 images, each having 5 captions. This makes a total of 30000 images and captions."
},
{
"code": null,
"e": 16066,
"s": 15934,
"text": "Even if we assume that each caption on an average is just 7 words long, it will lead to a total of 30000*7 i.e. 210000 data points."
},
{
"code": null,
"e": 16103,
"s": 16066,
"text": "Compute the size of the data matrix:"
},
{
"code": null,
"e": 16133,
"s": 16103,
"text": "Size of the data matrix = n*m"
},
{
"code": null,
"e": 16185,
"s": 16133,
"text": "Where n-> number of data points (assumed as 210000)"
},
{
"code": null,
"e": 16219,
"s": 16185,
"text": "And m-> length of each data point"
},
{
"code": null,
"e": 16291,
"s": 16219,
"text": "Clearly m= Length of image vector(2048) + Length of partial caption(x)."
},
{
"code": null,
"e": 16304,
"s": 16291,
"text": "m = 2048 + x"
},
{
"code": null,
"e": 16332,
"s": 16304,
"text": "But what is the value of x?"
},
{
"code": null,
"e": 16388,
"s": 16332,
"text": "Well you might think it is 34, but no wait, it’s wrong."
},
{
"code": null,
"e": 16510,
"s": 16388,
"text": "Every word (or index) will be mapped (embedded) to higher dimensional space through one of the word embedding techniques."
},
{
"code": null,
"e": 16662,
"s": 16510,
"text": "Later, during the model building stage, we will see that each word/index is mapped to a 200-long vector using a pre-trained GLOVE word embedding model."
},
{
"code": null,
"e": 16773,
"s": 16662,
"text": "Now each sequence contains 34 indices, where each index is a vector of length 200. Therefore x = 34*200 = 6800"
},
{
"code": null,
"e": 16804,
"s": 16773,
"text": "Hence, m = 2048 + 6800 = 8848."
},
{
"code": null,
"e": 16868,
"s": 16804,
"text": "Finally, size of data matrix= 210000 * 8848= 1858080000 blocks."
},
{
"code": null,
"e": 16999,
"s": 16868,
"text": "Now even if we assume that one block takes 2 byte, then, to store this data matrix, we will require more than 3 GB of main memory."
},
{
"code": null,
"e": 17137,
"s": 16999,
"text": "This is pretty huge requirement and even if we are able to manage to load this much data into the RAM, it will make the system very slow."
},
{
"code": null,
"e": 17398,
"s": 17137,
"text": "For this reason we use data generators a lot in Deep Learning. Data Generators are a functionality which is natively implemented in Python. The ImageDataGenerator class provided by the Keras API is nothing but an implementation of generator function in Python."
},
{
"code": null,
"e": 17457,
"s": 17398,
"text": "So how does using a generator function solve this problem?"
},
{
"code": null,
"e": 17655,
"s": 17457,
"text": "If you know the basics of Deep Learning, then you must know that to train a model on a particular dataset, we use some version of Stochastic Gradient Descent (SGD) like Adam, Rmsprop, Adagrad, etc."
},
{
"code": null,
"e": 17873,
"s": 17655,
"text": "With SGD, we do not calculate the loss on the entire data set to update the gradients. Rather in every iteration, we calculate the loss on a batch of data points (typically 64, 128, 256, etc.) to update the gradients."
},
{
"code": null,
"e": 18051,
"s": 17873,
"text": "This means that we do not require to store the entire dataset in the memory at once. Even if we have the current batch of points in the memory, it is sufficient for our purpose."
},
{
"code": null,
"e": 18222,
"s": 18051,
"text": "A generator function in Python is used exactly for this purpose. It’s like an iterator which resumes the functionality from the point it left the last time it was called."
},
{
"code": null,
"e": 18277,
"s": 18222,
"text": "To understand more about Generators, please read here."
},
{
"code": null,
"e": 18320,
"s": 18277,
"text": "The code for data generator is as follows:"
},
{
"code": null,
"e": 18462,
"s": 18320,
"text": "As already stated above, we will map the every word (index) to a 200-long vector and for this purpose, we will use a pre-trained GLOVE Model:"
},
{
"code": null,
"e": 18775,
"s": 18462,
"text": "# Load Glove vectorsglove_dir = 'dataset/glove'embeddings_index = {} # empty dictionaryf = open(os.path.join(glove_dir, 'glove.6B.200d.txt'), encoding=\"utf-8\")for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefsf.close()"
},
{
"code": null,
"e": 18912,
"s": 18775,
"text": "Now, for all the 1652 unique words in our vocabulary, we create an embedding matrix which will be loaded into the model before training."
},
{
"code": null,
"e": 19311,
"s": 18912,
"text": "embedding_dim = 200# Get 200-dim dense vector for each of the 10000 words in out vocabularyembedding_matrix = np.zeros((vocab_size, embedding_dim))for word, i in wordtoix.items(): #if i < max_words: embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # Words not found in the embedding index will be all zeros embedding_matrix[i] = embedding_vector"
},
{
"code": null,
"e": 19376,
"s": 19311,
"text": "To understand more about word embeddings, please refer this link"
},
{
"code": null,
"e": 19601,
"s": 19376,
"text": "Since the input consists of two parts, an image vector and a partial caption, we cannot use the Sequential API provided by the Keras library. For this reason, we use the Functional API which allows us to create Merge Models."
},
{
"code": null,
"e": 19688,
"s": 19601,
"text": "First, let’s look at the brief architecture which contains the high level sub-modules:"
},
{
"code": null,
"e": 19720,
"s": 19688,
"text": "We define the model as follows:"
},
{
"code": null,
"e": 19753,
"s": 19720,
"text": "Let’s look at the model summary:"
},
{
"code": null,
"e": 19864,
"s": 19753,
"text": "The below plot helps to visualize the structure of the network and better understand the two streams of input:"
},
{
"code": null,
"e": 20005,
"s": 19864,
"text": "The text in red on the right side are the comments provided for you to map your understanding of the data preparation to model architecture."
},
{
"code": null,
"e": 20198,
"s": 20005,
"text": "The LSTM (Long Short Term Memory) layer is nothing but a specialized Recurrent Neural Network to process the sequence input (partial captions in our case). To read more about LSTM, click here."
},
{
"code": null,
"e": 20355,
"s": 20198,
"text": "If you have followed the previous section, I think reading these comments should help you to understand the model architecture in a straight forward manner."
},
{
"code": null,
"e": 20501,
"s": 20355,
"text": "Recall that we had created an embedding matrix from a pre-trained Glove model which we need to include in the model before starting the training:"
},
{
"code": null,
"e": 20582,
"s": 20501,
"text": "model.layers[2].set_weights([embedding_matrix])model.layers[2].trainable = False"
},
{
"code": null,
"e": 20773,
"s": 20582,
"text": "Notice that since we are using a pre-trained embedding layer, we need to freeze it (trainable = False), before training the model, so that it does not get updated during the backpropagation."
},
{
"code": null,
"e": 20827,
"s": 20773,
"text": "Finally we compile the model using the adam optimizer"
},
{
"code": null,
"e": 20892,
"s": 20827,
"text": "model.compile(loss=’categorical_crossentropy’, optimizer=’adam’)"
},
{
"code": null,
"e": 21095,
"s": 20892,
"text": "Finally the weights of the model will be updated through backpropagation algorithm and the model will learn to output a word, given an image feature vector and a partial caption. So in summary, we have:"
},
{
"code": null,
"e": 21122,
"s": 21095,
"text": "Input_1 -> Partial Caption"
},
{
"code": null,
"e": 21154,
"s": 21122,
"text": "Input_2 -> Image feature vector"
},
{
"code": null,
"e": 21334,
"s": 21154,
"text": "Output -> An appropriate word, next in the sequence of partial caption provided in the input_1 (or in probability terms we say conditioned on image vector and the partial caption)"
},
{
"code": null,
"e": 21368,
"s": 21334,
"text": "Hyper parameters during training:"
},
{
"code": null,
"e": 21604,
"s": 21368,
"text": "The model was then trained for 30 epochs with the initial learning rate of 0.001 and 3 pictures per batch (batch size). However after 20 epochs, the learning rate was reduced to 0.0001 and the model was trained on 6 pictures per batch."
},
{
"code": null,
"e": 21895,
"s": 21604,
"text": "This generally makes sense because during the later stages of training, since the model is moving towards convergence, we must lower the learning rate so that we take smaller steps towards the minima. Also increasing the batch size over time helps your gradient updates to be more powerful."
},
{
"code": null,
"e": 22160,
"s": 21895,
"text": "Time Taken: I used the GPU+ Gradient Notebook on www.paperspace.com and hence it took me approximately an hour to train the model. However if you train it on a PC without GPU, it could take anywhere from 8 to 16 hours depending on the configuration of your system."
},
{
"code": null,
"e": 22400,
"s": 22160,
"text": "So till now, we have seen how to prepare the data and build the model. In the final step of this series, we will understand how do we test (infer) our model by passing in new images, i.e. how can we generate a caption for a new test image."
},
{
"code": null,
"e": 22614,
"s": 22400,
"text": "Recall that in the example where we saw how to prepare the data, we used only first two images and their captions. Now let’s use the third image and try to understand how we would like the caption to be generated."
},
{
"code": null,
"e": 22666,
"s": 22614,
"text": "The third image vector and caption were as follows:"
},
{
"code": null,
"e": 22711,
"s": 22666,
"text": "Caption -> the black cat is walking on grass"
},
{
"code": null,
"e": 22751,
"s": 22711,
"text": "Also the vocabulary in the example was:"
},
{
"code": null,
"e": 22837,
"s": 22751,
"text": "vocab = {black, cat, endseq, grass, is, on, road, sat, startseq, the, walking, white}"
},
{
"code": null,
"e": 22910,
"s": 22837,
"text": "We will generate the caption iteratively, one word at a time as follows:"
},
{
"code": null,
"e": 22923,
"s": 22910,
"text": "Iteration 1:"
},
{
"code": null,
"e": 22977,
"s": 22923,
"text": "Input: Image vector + “startseq” (as partial caption)"
},
{
"code": null,
"e": 23005,
"s": 22977,
"text": "Expected Output word: “the”"
},
{
"code": null,
"e": 23149,
"s": 23005,
"text": "(You should now understand the importance of the token ‘startseq’ which is used as the initial partial caption for any image during inference)."
},
{
"code": null,
"e": 23462,
"s": 23149,
"text": "But wait, the model generates a 12-long vector(in the sample example while 1652-long vector in the original example) which is a probability distribution across all the words in the vocabulary. For this reason we greedily select the word with the maximum probability, given the feature vector and partial caption."
},
{
"code": null,
"e": 23557,
"s": 23462,
"text": "If the model is trained well, we must expect the probability for the word “the” to be maximum:"
},
{
"code": null,
"e": 23817,
"s": 23557,
"text": "This is called as Maximum Likelihood Estimation (MLE) i.e. we select that word which is most likely according to the model for the given input. And sometimes this method is also called as Greedy Search, as we greedily select the word with maximum probability."
},
{
"code": null,
"e": 23830,
"s": 23817,
"text": "Iteration 2:"
},
{
"code": null,
"e": 23867,
"s": 23830,
"text": "Input: Image vector + “startseq the”"
},
{
"code": null,
"e": 23897,
"s": 23867,
"text": "Expected Output word: “black”"
},
{
"code": null,
"e": 23910,
"s": 23897,
"text": "Iteration 3:"
},
{
"code": null,
"e": 23953,
"s": 23910,
"text": "Input: Image vector + “startseq the black”"
},
{
"code": null,
"e": 23981,
"s": 23953,
"text": "Expected Output word: “cat”"
},
{
"code": null,
"e": 23994,
"s": 23981,
"text": "Iteration 4:"
},
{
"code": null,
"e": 24041,
"s": 23994,
"text": "Input: Image vector + “startseq the black cat”"
},
{
"code": null,
"e": 24068,
"s": 24041,
"text": "Expected Output word: “is”"
},
{
"code": null,
"e": 24081,
"s": 24068,
"text": "Iteration 5:"
},
{
"code": null,
"e": 24131,
"s": 24081,
"text": "Input: Image vector + “startseq the black cat is”"
},
{
"code": null,
"e": 24163,
"s": 24131,
"text": "Expected Output word: “walking”"
},
{
"code": null,
"e": 24176,
"s": 24163,
"text": "Iteration 6:"
},
{
"code": null,
"e": 24234,
"s": 24176,
"text": "Input: Image vector + “startseq the black cat is walking”"
},
{
"code": null,
"e": 24261,
"s": 24234,
"text": "Expected Output word: “on”"
},
{
"code": null,
"e": 24274,
"s": 24261,
"text": "Iteration 7:"
},
{
"code": null,
"e": 24335,
"s": 24274,
"text": "Input: Image vector + “startseq the black cat is walking on”"
},
{
"code": null,
"e": 24365,
"s": 24335,
"text": "Expected Output word: “grass”"
},
{
"code": null,
"e": 24378,
"s": 24365,
"text": "Iteration 8:"
},
{
"code": null,
"e": 24445,
"s": 24378,
"text": "Input: Image vector + “startseq the black cat is walking on grass”"
},
{
"code": null,
"e": 24476,
"s": 24445,
"text": "Expected Output word: “endseq”"
},
{
"code": null,
"e": 24514,
"s": 24476,
"text": "This is where we stop the iterations."
},
{
"code": null,
"e": 24573,
"s": 24514,
"text": "So we stop when either of the below two conditions is met:"
},
{
"code": null,
"e": 24735,
"s": 24573,
"text": "We encounter an ‘endseq’ token which means the model thinks that this is the end of the caption. (You should now understand the importance of the ‘endseq’ token)"
},
{
"code": null,
"e": 24811,
"s": 24735,
"text": "We reach a maximum threshold of the number of words generated by the model."
},
{
"code": null,
"e": 24987,
"s": 24811,
"text": "If any of the above conditions is met, we break the loop and report the generated caption as the output of the model for the given image. The code for inference is as follows:"
},
{
"code": null,
"e": 25154,
"s": 24987,
"text": "To understand how good the model is, let’s try to generate captions on images from the test dataset (i.e. the images which the model did not see during the training)."
},
{
"code": null,
"e": 25235,
"s": 25154,
"text": "Note: We must appreciate how the model is able to identify the colors precisely."
},
{
"code": null,
"e": 25490,
"s": 25235,
"text": "Of course, I would be fooling you if I only showed you the appropriate captions. No model in the world is ever perfect and this model also makes mistakes. Let’s look at some examples where the captions are not very relevant and sometimes even irrelevant."
},
{
"code": null,
"e": 25565,
"s": 25490,
"text": "Probably the color of the shirt got mixed with the color in the background"
},
{
"code": null,
"e": 25669,
"s": 25565,
"text": "Why does the model classify the famous Rafael Nadal as a woman :-) ? Probably because of the long hair."
},
{
"code": null,
"e": 25716,
"s": 25669,
"text": "The model gets the grammar incorrect this time"
},
{
"code": null,
"e": 25818,
"s": 25716,
"text": "Clearly, the model tried its best to understand the scenario but still the caption is not a good one."
},
{
"code": null,
"e": 25894,
"s": 25818,
"text": "Again one more example where the model fails and the caption is irrelevant."
},
{
"code": null,
"e": 26048,
"s": 25894,
"text": "So all in all, I must say that my naive first-cut model, without any rigorous hyper-parameter tuning does a decent job in generating captions for images."
},
{
"code": null,
"e": 26065,
"s": 26048,
"text": "Important Point:"
},
{
"code": null,
"e": 26492,
"s": 26065,
"text": "We must understand that the images used for testing must be semantically related to those used for training the model. For example, if we train our model on the images of cats, dogs, etc. we must not test it on images of air planes, waterfalls, etc. This is an example where the distribution of the train and test sets will be very different and in such cases no Machine Learning model in the world will give good performance."
},
{
"code": null,
"e": 26662,
"s": 26492,
"text": "Thanks a lot if you have reached here. This is my first attempt in blogging so I expect the readers to be a bit generous and ignore the minor mistakes I might have made."
},
{
"code": null,
"e": 26748,
"s": 26662,
"text": "Please refer my GitHub link here to access the full code written in Jupyter Notebook."
},
{
"code": null,
"e": 26925,
"s": 26748,
"text": "Note that due to the stochastic nature of the models, the captions generated by you (if you try to replicate the code) may not be exactly similar to those generated in my case."
},
{
"code": null,
"e": 27039,
"s": 26925,
"text": "Of course this is just a first-cut solution and a lot of modifications can be made to improve this solution like:"
},
{
"code": null,
"e": 27063,
"s": 27039,
"text": "Using a larger dataset."
},
{
"code": null,
"e": 27130,
"s": 27063,
"text": "Changing the model architecture, e.g. include an attention module."
},
{
"code": null,
"e": 27268,
"s": 27130,
"text": "Doing more hyper parameter tuning (learning rate, batch size, number of layers, number of units, dropout rate, batch normalization etc.)."
},
{
"code": null,
"e": 27324,
"s": 27268,
"text": "Use the cross validation set to understand overfitting."
},
{
"code": null,
"e": 27385,
"s": 27324,
"text": "Using Beam Search instead of Greedy Search during Inference."
},
{
"code": null,
"e": 27456,
"s": 27385,
"text": "Using BLEU Score to evaluate and measure the performance of the model."
},
{
"code": null,
"e": 27559,
"s": 27456,
"text": "Writing the code in a proper object oriented way so that it becomes easier for others to replicate :-)"
},
{
"code": null,
"e": 27876,
"s": 27559,
"text": "https://cs.stanford.edu/people/karpathy/cvpr2015.pdfhttps://arxiv.org/abs/1411.4555https://arxiv.org/abs/1703.09137https://arxiv.org/abs/1708.02043https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/https://www.youtube.com/watch?v=yk6XDFm3J2chttps://www.appliedaicourse.com/"
},
{
"code": null,
"e": 27929,
"s": 27876,
"text": "https://cs.stanford.edu/people/karpathy/cvpr2015.pdf"
},
{
"code": null,
"e": 27961,
"s": 27929,
"text": "https://arxiv.org/abs/1411.4555"
},
{
"code": null,
"e": 27994,
"s": 27961,
"text": "https://arxiv.org/abs/1703.09137"
},
{
"code": null,
"e": 28027,
"s": 27994,
"text": "https://arxiv.org/abs/1708.02043"
},
{
"code": null,
"e": 28122,
"s": 28027,
"text": "https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/"
},
{
"code": null,
"e": 28166,
"s": 28122,
"text": "https://www.youtube.com/watch?v=yk6XDFm3J2c"
},
{
"code": null,
"e": 28199,
"s": 28166,
"text": "https://www.appliedaicourse.com/"
}
] |
How to convert Date to String in Java - GeeksforGeeks
|
29 Jul, 2020
Given a date, the task is to write a Java program to convert the given date into a string.
Examples:
Input: date = “2020-07-27”Output: 2020-07-27
Input: date = “2018-02-17”Output: 2018-02-17
Approach:
Get the date to be converted.Create an instance of SimpleDateFormat class to format the string representation of the date object.Get the date using the Calendar object.Convert the given date into a string using format() method.Print the result.
Get the date to be converted.
Create an instance of SimpleDateFormat class to format the string representation of the date object.
Get the date using the Calendar object.
Convert the given date into a string using format() method.
Print the result.
Below is the implementation of the above approach:
Java
// Java program to convert Date to String import java.util.Calendar;import java.util.Date;import java.text.DateFormat;import java.text.SimpleDateFormat; class GFG { // Function to convert date to string public static String convertDateToString(String date) { // Converts the string // format to date object DateFormat df = new SimpleDateFormat(date); // Get the date using calendar object Date today = Calendar.getInstance() .getTime(); // Convert the date into a // string using format() method String dateToString = df.format(today); // Return the result return (dateToString); } // Driver Code public static void main(String args[]) { // Given Date String date = "07-27-2020"; // Convert and print the result System.out.print( convertDateToString(date)); }}
07-27-2020
Approach:
Get an instance of LocalDate from date.Convert the given date into a string using the toString() method of LocalDate class.Print the result.
Get an instance of LocalDate from date.
Convert the given date into a string using the toString() method of LocalDate class.
Print the result.
Below is the implementation of the above approach:
Java
// Java program to convert Date to String import java.time.LocalDate; class GFG { // Function to convert date to string public static String convertDateToString(String date) { // Get an instance of LocalTime // from date LocalDate givenDate = LocalDate.parse(date); // Convert the given date into a // string using toString()method String dateToString = givenDate.toString(); // Return the result return (dateToString); } // Driver Code public static void main(String args[]) { // Given Date String date = "2020-07-27"; // Convert and print the result System.out.print( convertDateToString(date)); }}
2020-07-27
Java-Date-Time
Java-LocalDate
Java-String-Programs
Java Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate through List in Java
Factory method design pattern in Java
Program to print ASCII Value of a character
Java Program to Remove Duplicate Elements From the Array
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 25777,
"s": 25749,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 25868,
"s": 25777,
"text": "Given a date, the task is to write a Java program to convert the given date into a string."
},
{
"code": null,
"e": 25878,
"s": 25868,
"text": "Examples:"
},
{
"code": null,
"e": 25923,
"s": 25878,
"text": "Input: date = “2020-07-27”Output: 2020-07-27"
},
{
"code": null,
"e": 25968,
"s": 25923,
"text": "Input: date = “2018-02-17”Output: 2018-02-17"
},
{
"code": null,
"e": 25978,
"s": 25968,
"text": "Approach:"
},
{
"code": null,
"e": 26223,
"s": 25978,
"text": "Get the date to be converted.Create an instance of SimpleDateFormat class to format the string representation of the date object.Get the date using the Calendar object.Convert the given date into a string using format() method.Print the result."
},
{
"code": null,
"e": 26253,
"s": 26223,
"text": "Get the date to be converted."
},
{
"code": null,
"e": 26354,
"s": 26253,
"text": "Create an instance of SimpleDateFormat class to format the string representation of the date object."
},
{
"code": null,
"e": 26394,
"s": 26354,
"text": "Get the date using the Calendar object."
},
{
"code": null,
"e": 26454,
"s": 26394,
"text": "Convert the given date into a string using format() method."
},
{
"code": null,
"e": 26472,
"s": 26454,
"text": "Print the result."
},
{
"code": null,
"e": 26523,
"s": 26472,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26528,
"s": 26523,
"text": "Java"
},
{
"code": "// Java program to convert Date to String import java.util.Calendar;import java.util.Date;import java.text.DateFormat;import java.text.SimpleDateFormat; class GFG { // Function to convert date to string public static String convertDateToString(String date) { // Converts the string // format to date object DateFormat df = new SimpleDateFormat(date); // Get the date using calendar object Date today = Calendar.getInstance() .getTime(); // Convert the date into a // string using format() method String dateToString = df.format(today); // Return the result return (dateToString); } // Driver Code public static void main(String args[]) { // Given Date String date = \"07-27-2020\"; // Convert and print the result System.out.print( convertDateToString(date)); }}",
"e": 27465,
"s": 26528,
"text": null
},
{
"code": null,
"e": 27477,
"s": 27465,
"text": "07-27-2020\n"
},
{
"code": null,
"e": 27487,
"s": 27477,
"text": "Approach:"
},
{
"code": null,
"e": 27628,
"s": 27487,
"text": "Get an instance of LocalDate from date.Convert the given date into a string using the toString() method of LocalDate class.Print the result."
},
{
"code": null,
"e": 27668,
"s": 27628,
"text": "Get an instance of LocalDate from date."
},
{
"code": null,
"e": 27753,
"s": 27668,
"text": "Convert the given date into a string using the toString() method of LocalDate class."
},
{
"code": null,
"e": 27771,
"s": 27753,
"text": "Print the result."
},
{
"code": null,
"e": 27822,
"s": 27771,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27827,
"s": 27822,
"text": "Java"
},
{
"code": "// Java program to convert Date to String import java.time.LocalDate; class GFG { // Function to convert date to string public static String convertDateToString(String date) { // Get an instance of LocalTime // from date LocalDate givenDate = LocalDate.parse(date); // Convert the given date into a // string using toString()method String dateToString = givenDate.toString(); // Return the result return (dateToString); } // Driver Code public static void main(String args[]) { // Given Date String date = \"2020-07-27\"; // Convert and print the result System.out.print( convertDateToString(date)); }}",
"e": 28577,
"s": 27827,
"text": null
},
{
"code": null,
"e": 28589,
"s": 28577,
"text": "2020-07-27\n"
},
{
"code": null,
"e": 28604,
"s": 28589,
"text": "Java-Date-Time"
},
{
"code": null,
"e": 28619,
"s": 28604,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 28640,
"s": 28619,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 28654,
"s": 28640,
"text": "Java Programs"
},
{
"code": null,
"e": 28662,
"s": 28654,
"text": "Strings"
},
{
"code": null,
"e": 28670,
"s": 28662,
"text": "Strings"
},
{
"code": null,
"e": 28768,
"s": 28670,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28800,
"s": 28768,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 28829,
"s": 28800,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 28867,
"s": 28829,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 28911,
"s": 28867,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 28968,
"s": 28911,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 29014,
"s": 28968,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 29039,
"s": 29014,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29099,
"s": 29039,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29114,
"s": 29099,
"text": "C++ Data Types"
}
] |
How to get a DOM Element from a jQuery Selector ? - GeeksforGeeks
|
07 Nov, 2020
The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements. If they are only one particular unique element in the HTML page we can access it by it’s tag as $(“tag”), but when we have more than one of its kind then we will access them with the ID that when $(“#id”) comes into play.
But if we want to use the raw DOM elements then we can convert them into javascript objects in that way we can use them for methods present in javascript but not in jquery.
Syntax
$(“selector”).get(0)
or
$(“selector”)[0]
Below examples illustrates the approach.
Example 1: This example will use the $(“selector”).get(0):
Javascript
<!DOCTYPE html><html> <head> <title>The jQuery DOM elements Example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { // Access with tag $("p").css("color", "red"); $("button").click(function() { // Access with id $("#d1").css("color", "purple"); $("#d2").css("color", "green"); $("#d3").css("color", "black"); // Converting into javascript object. $("#d4").get(0).reset(); }); }); </script></head> <body style="text-align:center;"> <div> <h4 id="d1">Hello</h4> <h1 id="d2">GeeksforGeeks</h1> <h3 id="d3"> A Computer Science Portal for Geeks </h3> <form id="d4"> Enter name: <input type="text" /> </form> <br> <button>Button</button> <br> <p> Clicking button will Resets the textbox and changes the background colors of the above texts. </p> </div></body> </html>
Output: As the reset() method is not available in jquery we have converted the jquery element into a javascript object or into raw DOM elements.
Example 2: This example will illustrate the use of $(“selector”)[0] selector.
Javascript
<!DOCTYPE html><html> <head> <title>The jQuery Example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { // Access with tag $("h1").css("color", "green"); $("button").click(function() { // d1 gets replaced with d4. $("#d1")[0].outerHTML = "<h3 id='d4'>A Computer Science Portal for Geeks</h3>"; $("#d4").css("color", "black"); }); }); </script></head> <body> <center> <div> <h1 id="d1">Hello Welcome to GeeksforGeeks</h1> <button>Button</button> <br> <h4> The above button changes the content of the above text. </h4> </div> </center></body> </html>
Output:
Note: As outerHTML is the HTML of an element including the element itself is not available in jquery. We have converted the jquery element into a javascript object or into raw DOM elements to access outerHTML and replace it with another heading.
Vijay Sirra
jQuery-Misc
Picked
JQuery
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
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
How to get the value in an input text box using jQuery ?
Difference Between JavaScript and jQuery
QR Code Generator using HTML, CSS and jQuery
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": 25675,
"s": 25647,
"text": "\n07 Nov, 2020"
},
{
"code": null,
"e": 26133,
"s": 25675,
"text": "The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements. If they are only one particular unique element in the HTML page we can access it by it’s tag as $(“tag”), but when we have more than one of its kind then we will access them with the ID that when $(“#id”) comes into play."
},
{
"code": null,
"e": 26306,
"s": 26133,
"text": "But if we want to use the raw DOM elements then we can convert them into javascript objects in that way we can use them for methods present in javascript but not in jquery."
},
{
"code": null,
"e": 26315,
"s": 26306,
"text": "Syntax "
},
{
"code": null,
"e": 26339,
"s": 26315,
"text": "$(“selector”).get(0)\n\n\n"
},
{
"code": null,
"e": 26344,
"s": 26339,
"text": "or "
},
{
"code": null,
"e": 26364,
"s": 26344,
"text": "$(“selector”)[0]\n\n\n"
},
{
"code": null,
"e": 26406,
"s": 26364,
"text": "Below examples illustrates the approach. "
},
{
"code": null,
"e": 26467,
"s": 26406,
"text": "Example 1: This example will use the $(“selector”).get(0): "
},
{
"code": null,
"e": 26478,
"s": 26467,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The jQuery DOM elements Example</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { // Access with tag $(\"p\").css(\"color\", \"red\"); $(\"button\").click(function() { // Access with id $(\"#d1\").css(\"color\", \"purple\"); $(\"#d2\").css(\"color\", \"green\"); $(\"#d3\").css(\"color\", \"black\"); // Converting into javascript object. $(\"#d4\").get(0).reset(); }); }); </script></head> <body style=\"text-align:center;\"> <div> <h4 id=\"d1\">Hello</h4> <h1 id=\"d2\">GeeksforGeeks</h1> <h3 id=\"d3\"> A Computer Science Portal for Geeks </h3> <form id=\"d4\"> Enter name: <input type=\"text\" /> </form> <br> <button>Button</button> <br> <p> Clicking button will Resets the textbox and changes the background colors of the above texts. </p> </div></body> </html>",
"e": 27715,
"s": 26478,
"text": null
},
{
"code": null,
"e": 27862,
"s": 27715,
"text": "Output: As the reset() method is not available in jquery we have converted the jquery element into a javascript object or into raw DOM elements. "
},
{
"code": null,
"e": 27941,
"s": 27862,
"text": "Example 2: This example will illustrate the use of $(“selector”)[0] selector. "
},
{
"code": null,
"e": 27952,
"s": 27941,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The jQuery Example</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { // Access with tag $(\"h1\").css(\"color\", \"green\"); $(\"button\").click(function() { // d1 gets replaced with d4. $(\"#d1\")[0].outerHTML = \"<h3 id='d4'>A Computer Science Portal for Geeks</h3>\"; $(\"#d4\").css(\"color\", \"black\"); }); }); </script></head> <body> <center> <div> <h1 id=\"d1\">Hello Welcome to GeeksforGeeks</h1> <button>Button</button> <br> <h4> The above button changes the content of the above text. </h4> </div> </center></body> </html>",
"e": 28858,
"s": 27952,
"text": null
},
{
"code": null,
"e": 28868,
"s": 28858,
"text": "Output: "
},
{
"code": null,
"e": 29115,
"s": 28868,
"text": "Note: As outerHTML is the HTML of an element including the element itself is not available in jquery. We have converted the jquery element into a javascript object or into raw DOM elements to access outerHTML and replace it with another heading. "
},
{
"code": null,
"e": 29127,
"s": 29115,
"text": "Vijay Sirra"
},
{
"code": null,
"e": 29139,
"s": 29127,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29146,
"s": 29139,
"text": "Picked"
},
{
"code": null,
"e": 29153,
"s": 29146,
"text": "JQuery"
},
{
"code": null,
"e": 29172,
"s": 29153,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29189,
"s": 29172,
"text": "Web Technologies"
},
{
"code": null,
"e": 29216,
"s": 29189,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29314,
"s": 29216,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29323,
"s": 29314,
"text": "Comments"
},
{
"code": null,
"e": 29336,
"s": 29323,
"text": "Old Comments"
},
{
"code": null,
"e": 29409,
"s": 29336,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 29432,
"s": 29409,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 29489,
"s": 29432,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 29530,
"s": 29489,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 29575,
"s": 29530,
"text": "QR Code Generator using HTML, CSS and jQuery"
},
{
"code": null,
"e": 29617,
"s": 29575,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29650,
"s": 29617,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29712,
"s": 29650,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29755,
"s": 29712,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Check if three straight lines are concurrent or not - GeeksforGeeks
|
05 May, 2021
Given three lines equation, a1x + b1y + c1 = 0 a2x + b2y + c2 = 0 a3x + b3y + c3 = 0The task is to check whether the given three lines are concurrent or not. Three straight lines are said to be concurrent if they pass through a point i.e., they meet at a point.Examples:
Input : a1 = 2, b1 = -3, c1 = 5
a2 = 3, b2 = 4, c2 = -7
a3 = 9, b3 = -5, c3 = 8
Output : Yes
Input : a1 = 2, b1 = -3, c1 = 5
a2 = 3, b2 = 4, c2 = -7
a3 = 9, b3 = -5, c3 = 4
Output : No
Let a1x + b1y + c1 = 0 .......... (1) a2x + b2y + c2 = 0 .......... (2) a3x + b3y + c3 = 0 .......... (3)Suppose the eqn (i) and (ii) intersects at (x1, y1). Then (x1, y1) will satisfy both the equations. Therefore, solving (i) and (ii) using method of cross-multiplication, we get, (x1/b1c2 – b2c1) = (y1/c1a2 – c2a1) = (1/a1b2 – a2b1)Therefore, x1 = (b1c2 – b2c1/a1b2 – a2b1) and y1 = (c1a2 – c2a1/a1b2 – a2b1), a1b2 – a2b1 != 0Therefore, the required coordinates of the point of intersection of the lines (i) and (ii) are (b1c2 – b2c1/a1b2 – a2b1, c1a2 – c2a1/a1b2 – a2b1)For, three of line to be concurrent, (x1, y1) must satisfy the equation (iii) as well. So, a3x + b3y + c3 = 0 => a3(b1c2 – b2c1/a1b2 – a2b1) + b3(c1a2 – c2a1/a1b2 – a2b1) + c3 = 0 => a3(b1c2 – b2c1) + b3(c1a2 – c2a1) + c3(a1b2 – a2b1) = 0So, we only need to check if above condition satisfy or not.Below is the implementation of this approach:
C++
Java
Python 3
C#
PHP
Javascript
// CPP Program to check if three straight// line are concurrent or not#include <bits/stdc++.h>using namespace std; // Return true if three line are concurrent,// else false.bool checkConcurrent(int a1, int b1, int c1, int a2, int b2, int c2, int a3, int b3, int c3){ return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0);} // Driven Programint main(){ int a1 = 2, b1 = -3, c1 = 5; int a2 = 3, b2 = 4, c2 = -7; int a3 = 9, b3 = -5, c3 = 8; (checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3) ? (cout << "Yes") : (cout << "No")); return 0;}
// Java Program to check if three straight// line are concurrent or noimport java.io.*; class GFG { // Return true if three line are concurrent, // else false. static boolean checkConcurrent(int a1, int b1, int c1, int a2, int b2, int c2, int a3, int b3, int c3) { return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0); } // Driven Program public static void main (String[] args) { int a1 = 2, b1 = -3, c1 = 5; int a2 = 3, b2 = 4, c2 = -7; int a3 = 9, b3 = -5, c3 = 8; if(checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3)) System.out.println( "Yes"); else System.out.println( "No"); }} // This code is contributed by anuj_67.
# Python3 Program to check if three straight# line are concurrent or not # Return true if three line are concurrent,# else false.def checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3): return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0) # Driven Programa1 = 2b1 = -3c1 = 5a2 = 3b2 = 4c2 = -7a3 = 9b3 = -5c3 = 8 if(checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3)): print("Yes")else: print("No") # This code is contributed by Smitha
// C# Program to check if three straight// line are concurrent or nousing System; class GFG { // Return true if three line are concurrent, // else false. static bool checkConcurrent(int a1, int b1, int c1, int a2, int b2, int c2, int a3, int b3, int c3) { return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0); } // Driven Program public static void Main () { int a1 = 2, b1 = -3, c1 = 5; int a2 = 3, b2 = 4, c2 = -7; int a3 = 9, b3 = -5, c3 = 8; if(checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3)) Console.WriteLine( "Yes"); else Console.WriteLine( "No"); }} // This code is contributed by anuj_67.
<?php// PHP Program to check if three straight// line are concurrent or not // Return true if three line are// concurrent, else false.function checkConcurrent($a1, $b1, $c1, $a2, $b2, $c2, $a3, $b3, $c3){ return ($a3 * ($b1 * $c2 - $b2 * $c1) + $b3 * ($c1 * $a2 - $c2 * $a1) + $c3 * ($a1 * $b2 - $a2 * $b1) == 0);} // Driver Code $a1 = 2; $b1 = -3; $c1 = 5; $a2 = 3; $b2 = 4; $c2 = -7; $a3 = 9; $b3 = -5; $c3 = 8; if(checkConcurrent($a1, $b1, $c1, $a2, $b2, $c2, $a3, $b3, $c3)) echo "Yes"; else echo "No"; // This code is contributed by anuj_67.?>
<script> // Javascript Program to check if three straight// line are concurrent or not // Return true if three line are concurrent,// else false.function checkConcurrent( a1, b1, c1, a2, b2, c2, a3, b3, c3){ return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0);} // Driven Programa1 = 2, b1 = -3, c1 = 5;a2 = 3, b2 = 4, c2 = -7;a3 = 9, b3 = -5, c3 = 8;(checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3) ? (document.write( "Yes")) : (document.write( "No"))); </script>
Yes
vt_m
Smitha Dinesh Semwal
rutvik_56
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull using Divide and Conquer Algorithm
Orientation of 3 ordered points
Equation of circle when three points on the circle are given
Program to find slope of a line
Program to find line passing through 2 Points
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25378,
"s": 25350,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 25651,
"s": 25378,
"text": "Given three lines equation, a1x + b1y + c1 = 0 a2x + b2y + c2 = 0 a3x + b3y + c3 = 0The task is to check whether the given three lines are concurrent or not. Three straight lines are said to be concurrent if they pass through a point i.e., they meet at a point.Examples: "
},
{
"code": null,
"e": 25869,
"s": 25651,
"text": "Input : a1 = 2, b1 = -3, c1 = 5\n a2 = 3, b2 = 4, c2 = -7\n a3 = 9, b3 = -5, c3 = 8\nOutput : Yes\n\nInput : a1 = 2, b1 = -3, c1 = 5\n a2 = 3, b2 = 4, c2 = -7\n a3 = 9, b3 = -5, c3 = 4\nOutput : No"
},
{
"code": null,
"e": 26790,
"s": 25869,
"text": "Let a1x + b1y + c1 = 0 .......... (1) a2x + b2y + c2 = 0 .......... (2) a3x + b3y + c3 = 0 .......... (3)Suppose the eqn (i) and (ii) intersects at (x1, y1). Then (x1, y1) will satisfy both the equations. Therefore, solving (i) and (ii) using method of cross-multiplication, we get, (x1/b1c2 – b2c1) = (y1/c1a2 – c2a1) = (1/a1b2 – a2b1)Therefore, x1 = (b1c2 – b2c1/a1b2 – a2b1) and y1 = (c1a2 – c2a1/a1b2 – a2b1), a1b2 – a2b1 != 0Therefore, the required coordinates of the point of intersection of the lines (i) and (ii) are (b1c2 – b2c1/a1b2 – a2b1, c1a2 – c2a1/a1b2 – a2b1)For, three of line to be concurrent, (x1, y1) must satisfy the equation (iii) as well. So, a3x + b3y + c3 = 0 => a3(b1c2 – b2c1/a1b2 – a2b1) + b3(c1a2 – c2a1/a1b2 – a2b1) + c3 = 0 => a3(b1c2 – b2c1) + b3(c1a2 – c2a1) + c3(a1b2 – a2b1) = 0So, we only need to check if above condition satisfy or not.Below is the implementation of this approach: "
},
{
"code": null,
"e": 26794,
"s": 26790,
"text": "C++"
},
{
"code": null,
"e": 26799,
"s": 26794,
"text": "Java"
},
{
"code": null,
"e": 26808,
"s": 26799,
"text": "Python 3"
},
{
"code": null,
"e": 26811,
"s": 26808,
"text": "C#"
},
{
"code": null,
"e": 26815,
"s": 26811,
"text": "PHP"
},
{
"code": null,
"e": 26826,
"s": 26815,
"text": "Javascript"
},
{
"code": "// CPP Program to check if three straight// line are concurrent or not#include <bits/stdc++.h>using namespace std; // Return true if three line are concurrent,// else false.bool checkConcurrent(int a1, int b1, int c1, int a2, int b2, int c2, int a3, int b3, int c3){ return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0);} // Driven Programint main(){ int a1 = 2, b1 = -3, c1 = 5; int a2 = 3, b2 = 4, c2 = -7; int a3 = 9, b3 = -5, c3 = 8; (checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3) ? (cout << \"Yes\") : (cout << \"No\")); return 0;}",
"e": 27493,
"s": 26826,
"text": null
},
{
"code": "// Java Program to check if three straight// line are concurrent or noimport java.io.*; class GFG { // Return true if three line are concurrent, // else false. static boolean checkConcurrent(int a1, int b1, int c1, int a2, int b2, int c2, int a3, int b3, int c3) { return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0); } // Driven Program public static void main (String[] args) { int a1 = 2, b1 = -3, c1 = 5; int a2 = 3, b2 = 4, c2 = -7; int a3 = 9, b3 = -5, c3 = 8; if(checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3)) System.out.println( \"Yes\"); else System.out.println( \"No\"); }} // This code is contributed by anuj_67.",
"e": 28366,
"s": 27493,
"text": null
},
{
"code": "# Python3 Program to check if three straight# line are concurrent or not # Return true if three line are concurrent,# else false.def checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3): return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0) # Driven Programa1 = 2b1 = -3c1 = 5a2 = 3b2 = 4c2 = -7a3 = 9b3 = -5c3 = 8 if(checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3)): print(\"Yes\")else: print(\"No\") # This code is contributed by Smitha",
"e": 28938,
"s": 28366,
"text": null
},
{
"code": "// C# Program to check if three straight// line are concurrent or nousing System; class GFG { // Return true if three line are concurrent, // else false. static bool checkConcurrent(int a1, int b1, int c1, int a2, int b2, int c2, int a3, int b3, int c3) { return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0); } // Driven Program public static void Main () { int a1 = 2, b1 = -3, c1 = 5; int a2 = 3, b2 = 4, c2 = -7; int a3 = 9, b3 = -5, c3 = 8; if(checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3)) Console.WriteLine( \"Yes\"); else Console.WriteLine( \"No\"); }} // This code is contributed by anuj_67.",
"e": 29778,
"s": 28938,
"text": null
},
{
"code": "<?php// PHP Program to check if three straight// line are concurrent or not // Return true if three line are// concurrent, else false.function checkConcurrent($a1, $b1, $c1, $a2, $b2, $c2, $a3, $b3, $c3){ return ($a3 * ($b1 * $c2 - $b2 * $c1) + $b3 * ($c1 * $a2 - $c2 * $a1) + $c3 * ($a1 * $b2 - $a2 * $b1) == 0);} // Driver Code $a1 = 2; $b1 = -3; $c1 = 5; $a2 = 3; $b2 = 4; $c2 = -7; $a3 = 9; $b3 = -5; $c3 = 8; if(checkConcurrent($a1, $b1, $c1, $a2, $b2, $c2, $a3, $b3, $c3)) echo \"Yes\"; else echo \"No\"; // This code is contributed by anuj_67.?>",
"e": 30462,
"s": 29778,
"text": null
},
{
"code": "<script> // Javascript Program to check if three straight// line are concurrent or not // Return true if three line are concurrent,// else false.function checkConcurrent( a1, b1, c1, a2, b2, c2, a3, b3, c3){ return (a3 * (b1 * c2 - b2 * c1) + b3 * (c1 * a2 - c2 * a1) + c3 * (a1 * b2 - a2 * b1) == 0);} // Driven Programa1 = 2, b1 = -3, c1 = 5;a2 = 3, b2 = 4, c2 = -7;a3 = 9, b3 = -5, c3 = 8;(checkConcurrent(a1, b1, c1, a2, b2, c2, a3, b3, c3) ? (document.write( \"Yes\")) : (document.write( \"No\"))); </script>",
"e": 31048,
"s": 30462,
"text": null
},
{
"code": null,
"e": 31052,
"s": 31048,
"text": "Yes"
},
{
"code": null,
"e": 31059,
"s": 31054,
"text": "vt_m"
},
{
"code": null,
"e": 31080,
"s": 31059,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 31090,
"s": 31080,
"text": "rutvik_56"
},
{
"code": null,
"e": 31100,
"s": 31090,
"text": "Geometric"
},
{
"code": null,
"e": 31113,
"s": 31100,
"text": "Mathematical"
},
{
"code": null,
"e": 31126,
"s": 31113,
"text": "Mathematical"
},
{
"code": null,
"e": 31136,
"s": 31126,
"text": "Geometric"
},
{
"code": null,
"e": 31234,
"s": 31136,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31281,
"s": 31234,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 31313,
"s": 31281,
"text": "Orientation of 3 ordered points"
},
{
"code": null,
"e": 31374,
"s": 31313,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 31406,
"s": 31374,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 31452,
"s": 31406,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 31482,
"s": 31452,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31542,
"s": 31482,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31557,
"s": 31542,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31600,
"s": 31557,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Flutter - Expansion Panel - GeeksforGeeks
|
14 May, 2021
When we want to expand and collapse things then we can do this with the help of an expansion panel. This Expansion panel list is mostly used in the apps and provides extra features to the app. We can create a list of children and wrap it with an Expansion Panel List. We can also create more than one expansion panel in our app. We can control whether the panel is open or not by isExpanded property.
Follow the below steps to implement the Expansion Panel in Flutter:
ExpansionPanel(
{required ExpansionPanelHeaderBuilder headerBuilder,
required Widget body,
bool isExpanded: false,
bool canTapOnHeader: false,
Color? backgroundColor}
)
headerBuilder: It is the widget builder to build the expansion panel.
body: The body of the expansion panel.
isExpanded: It is the boolean value to check whether the expansion panel is expanded or not.
canTapOnHeader: It is a boolean value that can expand the panel if given true.
backgroundColor: The background color of the expansion panel.
Example:
The homePage.dart file
Dart
import 'package:flutter/material.dart';import 'package:sports_app/items.dart';import 'package:velocity_x/velocity_x.dart'; class Homepage extends StatefulWidget { @override _HomepageState createState() => _HomepageState();} class _HomepageState extends State<Homepage> { bool active = false; String exTitle = "Sport Categories"; @override Widget build(BuildContext context) { return Column( children: [ ExpansionPanelList( expansionCallback: (panelIndex, isExpanded) { active = !active; if(exTitle=="Sport Categories") exTitle="Contract"; else exTitle="Sport Categories"; setState(() { }); }, children: <ExpansionPanel>[ ExpansionPanel( headerBuilder: (context, isExpanded) { return exTitle.text.gray500.make().centered(); }, body: Wrap( alignment: WrapAlignment.spaceBetween, spacing: 7, children: [ ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) return Colors.red; // Use the component's default. return Colors.black; }, ), ), onPressed: () => null, child: "All".text.make(), ), ElevatedButton( onPressed: null, child: "Basketball".text.black.make(), ), ElevatedButton( onPressed: null, child: "Football".text.black.make()), ElevatedButton( onPressed: null, child: "Tennis".text.black.make()), ElevatedButton( onPressed: null, child: "Fencing".text.black.make()), ElevatedButton( onPressed: null, child: "Swimming".text.black.make()), ElevatedButton( onPressed: null, child: "Hockey".text.black.make()), ElevatedButton( onPressed: null, child: "Karate".text.black.make()), ], ), isExpanded: active, canTapOnHeader: true ) ], ), for (int i = 0; i < items.length; i++) items[i] ], ); }}
Explanation:
Expansion panel is created using header builder to create a header of the Expansion Panel.
The Expansion Panel is wrapped with an Expansion panel list to create a list of Expansion panels.
In the Expansion Panel, the body is made with some Elevated Buttons.
isExpaned property is used to manage the expansion panel.
canTapOnHeader is set to True so that Expansion Panel can be opened by tapping on the header.
Output:
If we tap dropdown button or header then Expansion Panel will open as shown:
Flutter UI-components
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Android Studio Setup for Flutter Development
Flutter - Flexible Widget
What is widgets in Flutter?
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - BorderRadius Widget
|
[
{
"code": null,
"e": 24036,
"s": 24008,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 24438,
"s": 24036,
"text": "When we want to expand and collapse things then we can do this with the help of an expansion panel. This Expansion panel list is mostly used in the apps and provides extra features to the app. We can create a list of children and wrap it with an Expansion Panel List. We can also create more than one expansion panel in our app. We can control whether the panel is open or not by isExpanded property. "
},
{
"code": null,
"e": 24506,
"s": 24438,
"text": "Follow the below steps to implement the Expansion Panel in Flutter:"
},
{
"code": null,
"e": 24675,
"s": 24506,
"text": "ExpansionPanel(\n{required ExpansionPanelHeaderBuilder headerBuilder,\nrequired Widget body,\nbool isExpanded: false,\nbool canTapOnHeader: false,\nColor? backgroundColor}\n)"
},
{
"code": null,
"e": 24745,
"s": 24675,
"text": "headerBuilder: It is the widget builder to build the expansion panel."
},
{
"code": null,
"e": 24784,
"s": 24745,
"text": "body: The body of the expansion panel."
},
{
"code": null,
"e": 24877,
"s": 24784,
"text": "isExpanded: It is the boolean value to check whether the expansion panel is expanded or not."
},
{
"code": null,
"e": 24956,
"s": 24877,
"text": "canTapOnHeader: It is a boolean value that can expand the panel if given true."
},
{
"code": null,
"e": 25018,
"s": 24956,
"text": "backgroundColor: The background color of the expansion panel."
},
{
"code": null,
"e": 25027,
"s": 25018,
"text": "Example:"
},
{
"code": null,
"e": 25050,
"s": 25027,
"text": "The homePage.dart file"
},
{
"code": null,
"e": 25055,
"s": 25050,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:sports_app/items.dart';import 'package:velocity_x/velocity_x.dart'; class Homepage extends StatefulWidget { @override _HomepageState createState() => _HomepageState();} class _HomepageState extends State<Homepage> { bool active = false; String exTitle = \"Sport Categories\"; @override Widget build(BuildContext context) { return Column( children: [ ExpansionPanelList( expansionCallback: (panelIndex, isExpanded) { active = !active; if(exTitle==\"Sport Categories\") exTitle=\"Contract\"; else exTitle=\"Sport Categories\"; setState(() { }); }, children: <ExpansionPanel>[ ExpansionPanel( headerBuilder: (context, isExpanded) { return exTitle.text.gray500.make().centered(); }, body: Wrap( alignment: WrapAlignment.spaceBetween, spacing: 7, children: [ ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) return Colors.red; // Use the component's default. return Colors.black; }, ), ), onPressed: () => null, child: \"All\".text.make(), ), ElevatedButton( onPressed: null, child: \"Basketball\".text.black.make(), ), ElevatedButton( onPressed: null, child: \"Football\".text.black.make()), ElevatedButton( onPressed: null, child: \"Tennis\".text.black.make()), ElevatedButton( onPressed: null, child: \"Fencing\".text.black.make()), ElevatedButton( onPressed: null, child: \"Swimming\".text.black.make()), ElevatedButton( onPressed: null, child: \"Hockey\".text.black.make()), ElevatedButton( onPressed: null, child: \"Karate\".text.black.make()), ], ), isExpanded: active, canTapOnHeader: true ) ], ), for (int i = 0; i < items.length; i++) items[i] ], ); }}",
"e": 27872,
"s": 25055,
"text": null
},
{
"code": null,
"e": 27885,
"s": 27872,
"text": "Explanation:"
},
{
"code": null,
"e": 27976,
"s": 27885,
"text": "Expansion panel is created using header builder to create a header of the Expansion Panel."
},
{
"code": null,
"e": 28074,
"s": 27976,
"text": "The Expansion Panel is wrapped with an Expansion panel list to create a list of Expansion panels."
},
{
"code": null,
"e": 28143,
"s": 28074,
"text": "In the Expansion Panel, the body is made with some Elevated Buttons."
},
{
"code": null,
"e": 28201,
"s": 28143,
"text": "isExpaned property is used to manage the expansion panel."
},
{
"code": null,
"e": 28295,
"s": 28201,
"text": "canTapOnHeader is set to True so that Expansion Panel can be opened by tapping on the header."
},
{
"code": null,
"e": 28303,
"s": 28295,
"text": "Output:"
},
{
"code": null,
"e": 28380,
"s": 28303,
"text": "If we tap dropdown button or header then Expansion Panel will open as shown:"
},
{
"code": null,
"e": 28402,
"s": 28380,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 28407,
"s": 28402,
"text": "Dart"
},
{
"code": null,
"e": 28415,
"s": 28407,
"text": "Flutter"
},
{
"code": null,
"e": 28513,
"s": 28415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28522,
"s": 28513,
"text": "Comments"
},
{
"code": null,
"e": 28535,
"s": 28522,
"text": "Old Comments"
},
{
"code": null,
"e": 28574,
"s": 28535,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28600,
"s": 28574,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 28645,
"s": 28600,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 28671,
"s": 28645,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 28699,
"s": 28671,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 28738,
"s": 28699,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28755,
"s": 28738,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 28781,
"s": 28755,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 28804,
"s": 28781,
"text": "Flutter - Stack Widget"
}
] |
Twitter US Airline Sentiment Analysis | by Sohail Hosseini | Towards Data Science
|
The objective here is to analyze how travelers mentioned their feelings on Twitter in February 2015. It would be fascinating for airlines to use this free data to provide better service to their customers. This Dataset can be downloaded from here.
How can we analyze it?
I have uploaded the data saved in the local directory in Python:
tweets = pd.read_csv('Tweets.csv')
Let’s look at features included in dataset:
tweets.head()
What we are looking for here is the column named “airline_sentiment” and how we can predict it based on travelers’ tweets. This is called Sentiment Analysis.
To have better pictures of observations and features, we can run the following command, and it will provide us with each feature’s character.
tweets.info()
Let’s visualize the number of expressed feelings as negative, neutral, and positive.
plt.figure(figsize=(3,5))sns.countplot(tweets['airline_sentiment'], order =tweets.airline_sentiment.value_counts().index,palette= 'plasma')plt.show()
Majorities are negative, and it would be great/free feedback to airlines to provide appropriate responses. We can also show sentiments for each airline.
g = sns.FacetGrid(tweets, col=”airline”, col_wrap=3, height=5, aspect =0.7) g = g.map(sns.countplot, “airline_sentiment”,order =tweets.airline_sentiment.value_counts().index, palette=’plasma’) plt.show()
To do sentiment analysis, we need to import a few libraries. Since this is a classification problem, I use LGBMClassifier.
from lightgbm import LGBMClassifier
We need to convert these tweets (texts) to a matrix of token counts.
from sklearn.feature_extraction.text import CountVectorizer
The next step is to normalize the count matrix using tf-idf representation.
from sklearn.feature_extraction.text import TfidfTransformer
I used the pipeline function to do all steps together.
twitter_sentiment = Pipeline([('CVec', CountVectorizer(CountVectorizer(stop_words='english'))), ('Tfidf', TfidfTransformer()), ('norm', Normalizer()), ('tSVD', TruncatedSVD(n_components=100)), ('lgb', LGBMClassifier(n_jobs=-1))])
In the end, CROSS_VALIDATE is used with ROC_AUC metrics.
%%time cv_pred = cross_validate(twitter_sentiment, tweets[‘text’], tweets[‘airline_sentiment’], cv=5, scoring=(‘roc_auc_ovr’))
The results we have measured using ROC_AUS are as follows.
The complete code can be accessed through this link.
|
[
{
"code": null,
"e": 420,
"s": 172,
"text": "The objective here is to analyze how travelers mentioned their feelings on Twitter in February 2015. It would be fascinating for airlines to use this free data to provide better service to their customers. This Dataset can be downloaded from here."
},
{
"code": null,
"e": 443,
"s": 420,
"text": "How can we analyze it?"
},
{
"code": null,
"e": 508,
"s": 443,
"text": "I have uploaded the data saved in the local directory in Python:"
},
{
"code": null,
"e": 543,
"s": 508,
"text": "tweets = pd.read_csv('Tweets.csv')"
},
{
"code": null,
"e": 587,
"s": 543,
"text": "Let’s look at features included in dataset:"
},
{
"code": null,
"e": 601,
"s": 587,
"text": "tweets.head()"
},
{
"code": null,
"e": 759,
"s": 601,
"text": "What we are looking for here is the column named “airline_sentiment” and how we can predict it based on travelers’ tweets. This is called Sentiment Analysis."
},
{
"code": null,
"e": 901,
"s": 759,
"text": "To have better pictures of observations and features, we can run the following command, and it will provide us with each feature’s character."
},
{
"code": null,
"e": 915,
"s": 901,
"text": "tweets.info()"
},
{
"code": null,
"e": 1000,
"s": 915,
"text": "Let’s visualize the number of expressed feelings as negative, neutral, and positive."
},
{
"code": null,
"e": 1150,
"s": 1000,
"text": "plt.figure(figsize=(3,5))sns.countplot(tweets['airline_sentiment'], order =tweets.airline_sentiment.value_counts().index,palette= 'plasma')plt.show()"
},
{
"code": null,
"e": 1303,
"s": 1150,
"text": "Majorities are negative, and it would be great/free feedback to airlines to provide appropriate responses. We can also show sentiments for each airline."
},
{
"code": null,
"e": 1507,
"s": 1303,
"text": "g = sns.FacetGrid(tweets, col=”airline”, col_wrap=3, height=5, aspect =0.7) g = g.map(sns.countplot, “airline_sentiment”,order =tweets.airline_sentiment.value_counts().index, palette=’plasma’) plt.show()"
},
{
"code": null,
"e": 1630,
"s": 1507,
"text": "To do sentiment analysis, we need to import a few libraries. Since this is a classification problem, I use LGBMClassifier."
},
{
"code": null,
"e": 1666,
"s": 1630,
"text": "from lightgbm import LGBMClassifier"
},
{
"code": null,
"e": 1735,
"s": 1666,
"text": "We need to convert these tweets (texts) to a matrix of token counts."
},
{
"code": null,
"e": 1795,
"s": 1735,
"text": "from sklearn.feature_extraction.text import CountVectorizer"
},
{
"code": null,
"e": 1871,
"s": 1795,
"text": "The next step is to normalize the count matrix using tf-idf representation."
},
{
"code": null,
"e": 1932,
"s": 1871,
"text": "from sklearn.feature_extraction.text import TfidfTransformer"
},
{
"code": null,
"e": 1987,
"s": 1932,
"text": "I used the pipeline function to do all steps together."
},
{
"code": null,
"e": 2297,
"s": 1987,
"text": "twitter_sentiment = Pipeline([('CVec', CountVectorizer(CountVectorizer(stop_words='english'))), ('Tfidf', TfidfTransformer()), ('norm', Normalizer()), ('tSVD', TruncatedSVD(n_components=100)), ('lgb', LGBMClassifier(n_jobs=-1))])"
},
{
"code": null,
"e": 2354,
"s": 2297,
"text": "In the end, CROSS_VALIDATE is used with ROC_AUC metrics."
},
{
"code": null,
"e": 2481,
"s": 2354,
"text": "%%time cv_pred = cross_validate(twitter_sentiment, tweets[‘text’], tweets[‘airline_sentiment’], cv=5, scoring=(‘roc_auc_ovr’))"
},
{
"code": null,
"e": 2540,
"s": 2481,
"text": "The results we have measured using ROC_AUS are as follows."
}
] |
Bitwise right shift operators in C#
|
Bitwise operator works on bits and performs bit by bit operation. In Bitwise right shift operator the value of the left operand is moved right by the number of bits specified by the right operand.
In the below code, we have the value −
60 i.e. 0011 1100
On the right shift %minus;
c = a >> 2;
It converts into 15 after right shift twice −
15 i.e. 0000 1111
You can try to run the following code to implement Bitwise right shift operator in C# −
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
class toBinary {
static void Main(string[] args) {
int a = 60; /* 60 = 0011 1100 */
int b = 0;
c = a >> 2; /* 15 = 0000 1111 */
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}
|
[
{
"code": null,
"e": 1259,
"s": 1062,
"text": "Bitwise operator works on bits and performs bit by bit operation. In Bitwise right shift operator the value of the left operand is moved right by the number of bits specified by the right operand."
},
{
"code": null,
"e": 1298,
"s": 1259,
"text": "In the below code, we have the value −"
},
{
"code": null,
"e": 1316,
"s": 1298,
"text": "60 i.e. 0011 1100"
},
{
"code": null,
"e": 1343,
"s": 1316,
"text": "On the right shift %minus;"
},
{
"code": null,
"e": 1355,
"s": 1343,
"text": "c = a >> 2;"
},
{
"code": null,
"e": 1401,
"s": 1355,
"text": "It converts into 15 after right shift twice −"
},
{
"code": null,
"e": 1419,
"s": 1401,
"text": "15 i.e. 0000 1111"
},
{
"code": null,
"e": 1507,
"s": 1419,
"text": "You can try to run the following code to implement Bitwise right shift operator in C# −"
},
{
"code": null,
"e": 1857,
"s": 1507,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace Demo {\n class toBinary {\n static void Main(string[] args) {\n int a = 60; /* 60 = 0011 1100 */\n int b = 0;\n c = a >> 2; /* 15 = 0000 1111 */\n Console.WriteLine(\"Value of b is {0}\", b);\n Console.ReadLine();\n }\n }\n}"
}
] |
MongoDB query to update all documents matching specific IDs
|
Use the updateMany() function to update all documents that match the filter criteria. Let us create a collection with documents −
> db.demo476.insertOne({_id:1,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo476.insertOne({_id:2,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo476.insertOne({_id:3,"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.demo476.insertOne({_id:4,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 4 }
Display all documents from a collection with the help of find() method −
> db.demo476.find();
This will produce the following output −
{ "_id" : 1, "Name" : "Chris" }
{ "_id" : 2, "Name" : "David" }
{ "_id" : 3, "Name" : "Bob" }
{ "_id" : 4, "Name" : "Carol" }
Following is the query to update all documents matching specific IDs −
> db.demo476.updateMany({_id:{$in:[1,3]}},{$set:{Name:"Robert"}});
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Display all documents from a collection with the help of find() method −
> db.demo476.find();
This will produce the following output −
{ "_id" : 1, "Name" : "Robert" }
{ "_id" : 2, "Name" : "David" }
{ "_id" : 3, "Name" : "Robert" }
{ "_id" : 4, "Name" : "Carol" }
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "Use the updateMany() function to update all documents that match the filter criteria. Let us create a collection with documents −"
},
{
"code": null,
"e": 1558,
"s": 1192,
"text": "> db.demo476.insertOne({_id:1,\"Name\":\"Chris\"});\n{ \"acknowledged\" : true, \"insertedId\" : 1 }\n> db.demo476.insertOne({_id:2,\"Name\":\"David\"});\n{ \"acknowledged\" : true, \"insertedId\" : 2 }\n> db.demo476.insertOne({_id:3,\"Name\":\"Bob\"});\n{ \"acknowledged\" : true, \"insertedId\" : 3 }\n> db.demo476.insertOne({_id:4,\"Name\":\"Carol\"});\n{ \"acknowledged\" : true, \"insertedId\" : 4 }"
},
{
"code": null,
"e": 1631,
"s": 1558,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1652,
"s": 1631,
"text": "> db.demo476.find();"
},
{
"code": null,
"e": 1693,
"s": 1652,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1819,
"s": 1693,
"text": "{ \"_id\" : 1, \"Name\" : \"Chris\" }\n{ \"_id\" : 2, \"Name\" : \"David\" }\n{ \"_id\" : 3, \"Name\" : \"Bob\" }\n{ \"_id\" : 4, \"Name\" : \"Carol\" }"
},
{
"code": null,
"e": 1890,
"s": 1819,
"text": "Following is the query to update all documents matching specific IDs −"
},
{
"code": null,
"e": 2024,
"s": 1890,
"text": "> db.demo476.updateMany({_id:{$in:[1,3]}},{$set:{Name:\"Robert\"}});\n{ \"acknowledged\" : true, \"matchedCount\" : 2, \"modifiedCount\" : 2 }"
},
{
"code": null,
"e": 2097,
"s": 2024,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2118,
"s": 2097,
"text": "> db.demo476.find();"
},
{
"code": null,
"e": 2159,
"s": 2118,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2289,
"s": 2159,
"text": "{ \"_id\" : 1, \"Name\" : \"Robert\" }\n{ \"_id\" : 2, \"Name\" : \"David\" }\n{ \"_id\" : 3, \"Name\" : \"Robert\" }\n{ \"_id\" : 4, \"Name\" : \"Carol\" }"
}
] |
Display message when hovering over something with mouse cursor in Tkinter Python
|
Let us suppose we want to create an application where we want to add some description on tkinter widgets such that it displays tooltip text while hovering on the button widget. It can be achieved by adding a tooltip or popup.
Tooltips are useful in applications where User Interaction is required. We can define the tooltip by instantiating the constructor of Balloon(win). After that, we can bind the button with the tooltip message that applies on the widget.
#Import the tkinter library
from tkinter import *
from tkinter.tix import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("400x200")
#Create a tooltip
tip= Balloon(win)
#Create a Button widget
my_button=Button(win, text= "Python", font=('Helvetica bold', 20))
my_button.pack(pady=20)
#Bind the tooltip with button
tip.bind_widget(my_button,balloonmsg="Python is an interpreted, high-level
and general-purpose programming language")
win.mainloop()
Running the above code will display a window with a button. Now, hover on the Button “Python” and it will display a tooltip text.
|
[
{
"code": null,
"e": 1288,
"s": 1062,
"text": "Let us suppose we want to create an application where we want to add some description on tkinter widgets such that it displays tooltip text while hovering on the button widget. It can be achieved by adding a tooltip or popup."
},
{
"code": null,
"e": 1524,
"s": 1288,
"text": "Tooltips are useful in applications where User Interaction is required. We can define the tooltip by instantiating the constructor of Balloon(win). After that, we can bind the button with the tooltip message that applies on the widget."
},
{
"code": null,
"e": 2009,
"s": 1524,
"text": "#Import the tkinter library\nfrom tkinter import *\nfrom tkinter.tix import *\n\n#Create an instance of tkinter frame\nwin = Tk()\n#Set the geometry\nwin.geometry(\"400x200\")\n\n#Create a tooltip\ntip= Balloon(win)\n\n#Create a Button widget\nmy_button=Button(win, text= \"Python\", font=('Helvetica bold', 20))\nmy_button.pack(pady=20)\n\n#Bind the tooltip with button\ntip.bind_widget(my_button,balloonmsg=\"Python is an interpreted, high-level\nand general-purpose programming language\")\n\nwin.mainloop()"
},
{
"code": null,
"e": 2139,
"s": 2009,
"text": "Running the above code will display a window with a button. Now, hover on the Button “Python” and it will display a tooltip text."
}
] |
Check if one string can be converted to another - GeeksforGeeks
|
20 Dec, 2021
Given two strings str and str1, the task is to check whether one string can be converted to other by using the following operation:
Convert all the presence of a character by a different character.
For example, if str = “abacd” and operation is to change character ‘a’ to ‘k’, then the resultant str = “kbkcd”Examples:
Input: str = “abbcaa”; str1 = “bccdbb” Output: Yes Explanation: The mappings of the characters are: c –> d b –> c a –> bInput: str = “abbc”; str1 = “bcca” Output: No Explanation: The mapping of characters are: a –> b b –> c c –> a Here, due to the presence of a cycle, a specific order cannot be found.
Approach:
According to the given operation, every unique character should map to a unique character may be same or different.
This can easily be checked by a Hashmap.
However, this fails in cases where there is a cycle in mapping and a specific order cannot be determined.
One example of such case is Example 2 above.
Therefore, for mapping, the first and final characters are stored as edges in a hashmap.
For finding cycle with the edges, these edges are mapped one by one to a parent and are checked for cycle using Union and Find Algorithm.
Below is the implementation of the above approach.
CPP
Java
Python3
C#
Javascript
// C++ implementation of the above approach.#include <bits/stdc++.h>using namespace std;int parent[26];// Function for find// from Disjoint set algorithmint find(int x){ if (x != parent[x]) return parent[x] = find(parent[x]); return x;} // Function for the union// from Disjoint set algorithmvoid join(int x, int y){ int px = find(x); int pz = find(y); if (px != pz) { parent[pz] = px; }}// Function to check if one string// can be converted to another.bool convertible(string s1, string s2){ // All the characters are checked whether // it's either not replaced or replaced // by a similar character using a map. map<int, int> mp; for (int i = 0; i < s1.size(); i++) { if (mp.find(s1[i] - 'a') == mp.end()) { mp[s1[i] - 'a'] = s2[i] - 'a'; } else { if (mp[s1[i] - 'a'] != s2[i] - 'a') return false; } } // To check if there are cycles. // If yes, then they are not convertible. // Else, they are convertible. for (auto it : mp) { if (it.first == it.second) continue; else { if (find(it.first) == find(it.second)) return false; else join(it.first, it.second); } } return true;} // Function to initialize parent array// for union and find algorithm.void initialize(){ for (int i = 0; i < 26; i++) { parent[i] = i; }}// Driver codeint main(){ // Your C++ Code string s1, s2; s1 = "abbcaa"; s2 = "bccdbb"; initialize(); if (convertible(s1, s2)) cout << "Yes" << endl; else cout << "No" << endl; return 0;}
// Java implementation of the above approach.import java.util.*; class GFG{ static int []parent = new int[26]; // Function for find// from Disjoint set algorithmstatic int find(int x){ if (x != parent[x]) return parent[x] = find(parent[x]); return x;} // Function for the union// from Disjoint set algorithmstatic void join(int x, int y){ int px = find(x); int pz = find(y); if (px != pz) { parent[pz] = px; }}// Function to check if one String// can be converted to another.static boolean convertible(String s1, String s2){ // All the characters are checked whether // it's either not replaced or replaced // by a similar character using a map. HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); for (int i = 0; i < s1.length(); i++) { if (!mp.containsKey(s1.charAt(i) - 'a')) { mp.put(s1.charAt(i) - 'a', s2.charAt(i) - 'a'); } else { if (mp.get(s1.charAt(i) - 'a') != s2.charAt(i) - 'a') return false; } } // To check if there are cycles. // If yes, then they are not convertible. // Else, they are convertible. for (Map.Entry<Integer, Integer> it : mp.entrySet()) { if (it.getKey() == it.getValue()) continue; else { if (find(it.getKey()) == find(it.getValue())) return false; else join(it.getKey(), it.getValue()); } } return true;} // Function to initialize parent array// for union and find algorithm.static void initialize(){ for (int i = 0; i < 26; i++) { parent[i] = i; }} // Driver codepublic static void main(String[] args){ String s1, s2; s1 = "abbcaa"; s2 = "bccdbb"; initialize(); if (convertible(s1, s2)) System.out.print("Yes" + "\n"); else System.out.print("No" + "\n");}} // This code is contributed by 29AjayKumar
# Python3 implementation of the above approach.parent = [0] * 256 # Function for find# from Disjoset algorithmdef find(x): if (x != parent[x]): parent[x] = find(parent[x]) return parent[x] return x # Function for the union# from Disjoset algorithmdef join(x, y): px = find(x) pz = find(y) if (px != pz): parent[pz] = px # Function to check if one string# can be converted to another.def convertible(s1, s2): # All the characters are checked whether # it's either not replaced or replaced # by a similar character using a map. mp = dict() for i in range(len(s1)): if (s1[i] in mp): mp[s1[i]] = s2[i] else: if s1[i] in mp and mp[s1[i]] != s2[i]: return False # To check if there are cycles. # If yes, then they are not convertible. # Else, they are convertible. for it in mp: if (it == mp[it]): continue else : if (find(ord(it)) == find(ord(it))): return False else: join(ord(it), ord(it)) return True # Function to initialize parent array# for union and find algorithm.def initialize(): for i in range(256): parent[i] = i # Driver codes1 = "abbcaa"s2 = "bccdbb"initialize()if (convertible(s1, s2)): print("Yes")else: print("No") # This code is contributed by mohit kumar 29
// C# implementation of the above approach.using System;using System.Collections.Generic; class GFG{ static int []parent = new int[26]; // Function for find// from Disjoint set algorithmstatic int find(int x){ if (x != parent[x]) return parent[x] = find(parent[x]); return x;} // Function for the union// from Disjoint set algorithmstatic void join(int x, int y){ int px = find(x); int pz = find(y); if (px != pz) { parent[pz] = px; }} // Function to check if one String// can be converted to another.static bool convertible(String s1, String s2){ // All the characters are checked whether // it's either not replaced or replaced // by a similar character using a map. Dictionary<int,int> mp = new Dictionary<int,int>(); for (int i = 0; i < s1.Length; i++) { if (!mp.ContainsKey(s1[i] - 'a')) { mp.Add(s1[i] - 'a', s2[i] - 'a'); } else { if (mp[s1[i] - 'a'] != s2[i] - 'a') return false; } } // To check if there are cycles. // If yes, then they are not convertible. // Else, they are convertible. foreach(KeyValuePair<int, int> it in mp) { if (it.Key == it.Value) continue; else { if (find(it.Key) == find(it.Value)) return false; else join(it.Key, it.Value); } } return true;} // Function to initialize parent array// for union and find algorithm.static void initialize(){ for (int i = 0; i < 26; i++) { parent[i] = i; }} // Driver codepublic static void Main(String[] args){ String s1, s2; s1 = "abbcaa"; s2 = "bccdbb"; initialize(); if (convertible(s1, s2)) Console.Write("Yes" + "\n"); else Console.Write("No" + "\n");}} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation of the above approach. var parent = new Array(26).fill(0); // Function for find // from Disjoint set algorithm function find(x) { if (x !== parent[x]) return (parent[x] = find(parent[x])); return x; } // Function for the union // from Disjoint set algorithm function join(x, y) { var px = find(x); var pz = find(y); if (px !== pz) { parent[pz] = px; } } // Function to check if one String // can be converted to another. function convertible(s1, s2) { // All the characters are checked whether // it's either not replaced or replaced // by a similar character using a map. var mp = {}; for (var i = 0; i < s1.length; i++) { if (!mp.hasOwnProperty(s1[i].charCodeAt(0) - "a".charCodeAt(0))) { mp[s1[i].charCodeAt(0) - "a".charCodeAt(0)] = s2[i].charCodeAt(0) - "a".charCodeAt(0); } else { if ( mp[s1[i].charCodeAt(0) - "a".charCodeAt(0)] !== s2[i].charCodeAt(0) - "a".charCodeAt(0) ) return false; } } // To check if there are cycles. // If yes, then they are not convertible. // Else, they are convertible. for (const [key, value] of Object.entries(mp)) { if (key === value) continue; else { if (find(key) == find(value)) return false; else join(key, value); } } return true; } // Function to initialize parent array // for union and find algorithm. function initialize() { for (var i = 0; i < 26; i++) { parent[i] = i; } } // Driver code var s1, s2; s1 = "abbcaa"; s2 = "bccdbb"; initialize(); if (convertible(s1, s2)) document.write("Yes" + "<br>"); else document.write("No" + "<br>"); </script>
Yes
Time Complexity: O(N * logN), where N is the length of string s1.Auxiliary Space: O(N)
mohit kumar 29
29AjayKumar
princiraj1992
rdtank
pankajsharmagfg
amartyaghoshgfg
union-find
Algorithms
Hash
Strings
Hash
Strings
Algorithms
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
How to write a Pseudo Code?
Difference between Informed and Uninformed Search in AI
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 24509,
"s": 24481,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 24643,
"s": 24509,
"text": "Given two strings str and str1, the task is to check whether one string can be converted to other by using the following operation: "
},
{
"code": null,
"e": 24709,
"s": 24643,
"text": "Convert all the presence of a character by a different character."
},
{
"code": null,
"e": 24832,
"s": 24709,
"text": "For example, if str = “abacd” and operation is to change character ‘a’ to ‘k’, then the resultant str = “kbkcd”Examples: "
},
{
"code": null,
"e": 25137,
"s": 24832,
"text": "Input: str = “abbcaa”; str1 = “bccdbb” Output: Yes Explanation: The mappings of the characters are: c –> d b –> c a –> bInput: str = “abbc”; str1 = “bcca” Output: No Explanation: The mapping of characters are: a –> b b –> c c –> a Here, due to the presence of a cycle, a specific order cannot be found. "
},
{
"code": null,
"e": 25151,
"s": 25139,
"text": "Approach: "
},
{
"code": null,
"e": 25267,
"s": 25151,
"text": "According to the given operation, every unique character should map to a unique character may be same or different."
},
{
"code": null,
"e": 25308,
"s": 25267,
"text": "This can easily be checked by a Hashmap."
},
{
"code": null,
"e": 25414,
"s": 25308,
"text": "However, this fails in cases where there is a cycle in mapping and a specific order cannot be determined."
},
{
"code": null,
"e": 25459,
"s": 25414,
"text": "One example of such case is Example 2 above."
},
{
"code": null,
"e": 25548,
"s": 25459,
"text": "Therefore, for mapping, the first and final characters are stored as edges in a hashmap."
},
{
"code": null,
"e": 25686,
"s": 25548,
"text": "For finding cycle with the edges, these edges are mapped one by one to a parent and are checked for cycle using Union and Find Algorithm."
},
{
"code": null,
"e": 25739,
"s": 25686,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 25743,
"s": 25739,
"text": "CPP"
},
{
"code": null,
"e": 25748,
"s": 25743,
"text": "Java"
},
{
"code": null,
"e": 25756,
"s": 25748,
"text": "Python3"
},
{
"code": null,
"e": 25759,
"s": 25756,
"text": "C#"
},
{
"code": null,
"e": 25770,
"s": 25759,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach.#include <bits/stdc++.h>using namespace std;int parent[26];// Function for find// from Disjoint set algorithmint find(int x){ if (x != parent[x]) return parent[x] = find(parent[x]); return x;} // Function for the union// from Disjoint set algorithmvoid join(int x, int y){ int px = find(x); int pz = find(y); if (px != pz) { parent[pz] = px; }}// Function to check if one string// can be converted to another.bool convertible(string s1, string s2){ // All the characters are checked whether // it's either not replaced or replaced // by a similar character using a map. map<int, int> mp; for (int i = 0; i < s1.size(); i++) { if (mp.find(s1[i] - 'a') == mp.end()) { mp[s1[i] - 'a'] = s2[i] - 'a'; } else { if (mp[s1[i] - 'a'] != s2[i] - 'a') return false; } } // To check if there are cycles. // If yes, then they are not convertible. // Else, they are convertible. for (auto it : mp) { if (it.first == it.second) continue; else { if (find(it.first) == find(it.second)) return false; else join(it.first, it.second); } } return true;} // Function to initialize parent array// for union and find algorithm.void initialize(){ for (int i = 0; i < 26; i++) { parent[i] = i; }}// Driver codeint main(){ // Your C++ Code string s1, s2; s1 = \"abbcaa\"; s2 = \"bccdbb\"; initialize(); if (convertible(s1, s2)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}",
"e": 27442,
"s": 25770,
"text": null
},
{
"code": "// Java implementation of the above approach.import java.util.*; class GFG{ static int []parent = new int[26]; // Function for find// from Disjoint set algorithmstatic int find(int x){ if (x != parent[x]) return parent[x] = find(parent[x]); return x;} // Function for the union// from Disjoint set algorithmstatic void join(int x, int y){ int px = find(x); int pz = find(y); if (px != pz) { parent[pz] = px; }}// Function to check if one String// can be converted to another.static boolean convertible(String s1, String s2){ // All the characters are checked whether // it's either not replaced or replaced // by a similar character using a map. HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); for (int i = 0; i < s1.length(); i++) { if (!mp.containsKey(s1.charAt(i) - 'a')) { mp.put(s1.charAt(i) - 'a', s2.charAt(i) - 'a'); } else { if (mp.get(s1.charAt(i) - 'a') != s2.charAt(i) - 'a') return false; } } // To check if there are cycles. // If yes, then they are not convertible. // Else, they are convertible. for (Map.Entry<Integer, Integer> it : mp.entrySet()) { if (it.getKey() == it.getValue()) continue; else { if (find(it.getKey()) == find(it.getValue())) return false; else join(it.getKey(), it.getValue()); } } return true;} // Function to initialize parent array// for union and find algorithm.static void initialize(){ for (int i = 0; i < 26; i++) { parent[i] = i; }} // Driver codepublic static void main(String[] args){ String s1, s2; s1 = \"abbcaa\"; s2 = \"bccdbb\"; initialize(); if (convertible(s1, s2)) System.out.print(\"Yes\" + \"\\n\"); else System.out.print(\"No\" + \"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 29397,
"s": 27442,
"text": null
},
{
"code": "# Python3 implementation of the above approach.parent = [0] * 256 # Function for find# from Disjoset algorithmdef find(x): if (x != parent[x]): parent[x] = find(parent[x]) return parent[x] return x # Function for the union# from Disjoset algorithmdef join(x, y): px = find(x) pz = find(y) if (px != pz): parent[pz] = px # Function to check if one string# can be converted to another.def convertible(s1, s2): # All the characters are checked whether # it's either not replaced or replaced # by a similar character using a map. mp = dict() for i in range(len(s1)): if (s1[i] in mp): mp[s1[i]] = s2[i] else: if s1[i] in mp and mp[s1[i]] != s2[i]: return False # To check if there are cycles. # If yes, then they are not convertible. # Else, they are convertible. for it in mp: if (it == mp[it]): continue else : if (find(ord(it)) == find(ord(it))): return False else: join(ord(it), ord(it)) return True # Function to initialize parent array# for union and find algorithm.def initialize(): for i in range(256): parent[i] = i # Driver codes1 = \"abbcaa\"s2 = \"bccdbb\"initialize()if (convertible(s1, s2)): print(\"Yes\")else: print(\"No\") # This code is contributed by mohit kumar 29",
"e": 30792,
"s": 29397,
"text": null
},
{
"code": "// C# implementation of the above approach.using System;using System.Collections.Generic; class GFG{ static int []parent = new int[26]; // Function for find// from Disjoint set algorithmstatic int find(int x){ if (x != parent[x]) return parent[x] = find(parent[x]); return x;} // Function for the union// from Disjoint set algorithmstatic void join(int x, int y){ int px = find(x); int pz = find(y); if (px != pz) { parent[pz] = px; }} // Function to check if one String// can be converted to another.static bool convertible(String s1, String s2){ // All the characters are checked whether // it's either not replaced or replaced // by a similar character using a map. Dictionary<int,int> mp = new Dictionary<int,int>(); for (int i = 0; i < s1.Length; i++) { if (!mp.ContainsKey(s1[i] - 'a')) { mp.Add(s1[i] - 'a', s2[i] - 'a'); } else { if (mp[s1[i] - 'a'] != s2[i] - 'a') return false; } } // To check if there are cycles. // If yes, then they are not convertible. // Else, they are convertible. foreach(KeyValuePair<int, int> it in mp) { if (it.Key == it.Value) continue; else { if (find(it.Key) == find(it.Value)) return false; else join(it.Key, it.Value); } } return true;} // Function to initialize parent array// for union and find algorithm.static void initialize(){ for (int i = 0; i < 26; i++) { parent[i] = i; }} // Driver codepublic static void Main(String[] args){ String s1, s2; s1 = \"abbcaa\"; s2 = \"bccdbb\"; initialize(); if (convertible(s1, s2)) Console.Write(\"Yes\" + \"\\n\"); else Console.Write(\"No\" + \"\\n\");}} // This code is contributed by PrinciRaj1992",
"e": 32673,
"s": 30792,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach. var parent = new Array(26).fill(0); // Function for find // from Disjoint set algorithm function find(x) { if (x !== parent[x]) return (parent[x] = find(parent[x])); return x; } // Function for the union // from Disjoint set algorithm function join(x, y) { var px = find(x); var pz = find(y); if (px !== pz) { parent[pz] = px; } } // Function to check if one String // can be converted to another. function convertible(s1, s2) { // All the characters are checked whether // it's either not replaced or replaced // by a similar character using a map. var mp = {}; for (var i = 0; i < s1.length; i++) { if (!mp.hasOwnProperty(s1[i].charCodeAt(0) - \"a\".charCodeAt(0))) { mp[s1[i].charCodeAt(0) - \"a\".charCodeAt(0)] = s2[i].charCodeAt(0) - \"a\".charCodeAt(0); } else { if ( mp[s1[i].charCodeAt(0) - \"a\".charCodeAt(0)] !== s2[i].charCodeAt(0) - \"a\".charCodeAt(0) ) return false; } } // To check if there are cycles. // If yes, then they are not convertible. // Else, they are convertible. for (const [key, value] of Object.entries(mp)) { if (key === value) continue; else { if (find(key) == find(value)) return false; else join(key, value); } } return true; } // Function to initialize parent array // for union and find algorithm. function initialize() { for (var i = 0; i < 26; i++) { parent[i] = i; } } // Driver code var s1, s2; s1 = \"abbcaa\"; s2 = \"bccdbb\"; initialize(); if (convertible(s1, s2)) document.write(\"Yes\" + \"<br>\"); else document.write(\"No\" + \"<br>\"); </script>",
"e": 34684,
"s": 32673,
"text": null
},
{
"code": null,
"e": 34688,
"s": 34684,
"text": "Yes"
},
{
"code": null,
"e": 34777,
"s": 34690,
"text": "Time Complexity: O(N * logN), where N is the length of string s1.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 34792,
"s": 34777,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34804,
"s": 34792,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34818,
"s": 34804,
"text": "princiraj1992"
},
{
"code": null,
"e": 34825,
"s": 34818,
"text": "rdtank"
},
{
"code": null,
"e": 34841,
"s": 34825,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 34857,
"s": 34841,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 34868,
"s": 34857,
"text": "union-find"
},
{
"code": null,
"e": 34879,
"s": 34868,
"text": "Algorithms"
},
{
"code": null,
"e": 34884,
"s": 34879,
"text": "Hash"
},
{
"code": null,
"e": 34892,
"s": 34884,
"text": "Strings"
},
{
"code": null,
"e": 34897,
"s": 34892,
"text": "Hash"
},
{
"code": null,
"e": 34905,
"s": 34897,
"text": "Strings"
},
{
"code": null,
"e": 34916,
"s": 34905,
"text": "Algorithms"
},
{
"code": null,
"e": 34927,
"s": 34916,
"text": "union-find"
},
{
"code": null,
"e": 35025,
"s": 34927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35034,
"s": 35025,
"text": "Comments"
},
{
"code": null,
"e": 35047,
"s": 35034,
"text": "Old Comments"
},
{
"code": null,
"e": 35096,
"s": 35047,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 35121,
"s": 35096,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 35148,
"s": 35121,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 35176,
"s": 35148,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 35232,
"s": 35176,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 35317,
"s": 35232,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 35353,
"s": 35317,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 35384,
"s": 35353,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 35411,
"s": 35384,
"text": "Count pairs with given sum"
}
] |
Display all records except one in MySQL
|
You can use IN() to display all records except one in MySQL. Let us first create a table −
mysql> create table DemoTable
(
Id int,
FirstName varchar(20)
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,'Larry');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable values(10,'Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(110,'Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(90,'David');
Query OK, 1 row affected (0.20 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+-----------+
| Id | FirstName |
+------+-----------+
| 100 | Larry |
| 10 | Chris |
| 110 | Robert |
| 90 | David |
+------+-----------+
4 rows in set (0.00 sec)
Here is the query to display all records except one in MySQL −
mysql> select *from DemoTable where Id IN(110,90,100);
This will produce the following output −
+------+-----------+
| Id | FirstName |
+------+-----------+
| 100 | Larry |
| 110 | Robert |
| 90 | David |
+------+-----------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "You can use IN() to display all records except one in MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1261,
"s": 1153,
"text": "mysql> create table DemoTable\n(\n Id int,\n FirstName varchar(20)\n);\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1317,
"s": 1261,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1660,
"s": 1317,
"text": "mysql> insert into DemoTable values(100,'Larry');\nQuery OK, 1 row affected (0.31 sec)\nmysql> insert into DemoTable values(10,'Chris');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values(110,'Robert');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(90,'David');\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 1746,
"s": 1660,
"text": "Following is the query to display all records from the table using select statement −"
},
{
"code": null,
"e": 1777,
"s": 1746,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1818,
"s": 1777,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2011,
"s": 1818,
"text": "+------+-----------+\n| Id | FirstName |\n+------+-----------+\n| 100 | Larry |\n| 10 | Chris |\n| 110 | Robert |\n| 90 | David |\n+------+-----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2074,
"s": 2011,
"text": "Here is the query to display all records except one in MySQL −"
},
{
"code": null,
"e": 2129,
"s": 2074,
"text": "mysql> select *from DemoTable where Id IN(110,90,100);"
},
{
"code": null,
"e": 2170,
"s": 2129,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2342,
"s": 2170,
"text": "+------+-----------+\n| Id | FirstName |\n+------+-----------+\n| 100 | Larry |\n| 110 | Robert |\n| 90 | David |\n+------+-----------+\n3 rows in set (0.00 sec)"
}
] |
Introducing Jupytext. Jupyter notebooks are interactive... | by Marc Wouts | Towards Data Science
|
Jupyter notebooks are interactive documents that contain code, narratives, plots. They are an excellent place for experimenting with code and data. Notebooks are easily shared, and the 2.6M notebooks on GitHub just tell how popular notebooks are!
Jupyter notebooks are great, but they often are huge files, with a very specific JSON file format. Let us introduce Jupytext, a Jupyter plugin that reads and writes notebooks as plain text files: either Julia, Python, R scripts, Markdown, or R Markdown documents.
We wrote Jupytext to work on Jupyter notebooks just like we work on text files. With Jupytext,
refactoring a notebook (represented as e.g. a plain Python script) in your favorite text editor or IDE becomes a real option,
writing notebooks directly as scripts or Markdown is another option, and
collaborating on Jupyter notebooks with Git becomes straightforward.
The text representation of a notebook focuses on the part that we have actually written: cell inputs. We value inputs more than outputs. Often they are the only part of the notebook that we want to have under version control. Inputs are incomparably lighter than outputs (commonly kilobytes versus megabytes).
We also value outputs. Preserving outputs is possible with paired notebooks. In that configuration, Jupyter saves the notebook as a traditional .ipynb file, in addition to the script or Markdown document. The text representation can be edited outside of Jupyter. When reloading the notebook in Jupyter, cell inputs are taken from the text file, and matching outputs are loaded from the .ipynb file.
In this first animation we show how your favorite text editor or IDE can be used to edit your Jupyter notebooks. IDEs are more convenient than Jupyter for navigating through code, editing and executing cells or fractions of cells, and debugging.
Animation script:
We start with a Jupyter notebook.
The notebook includes a plot of the world population. The plot legend is not in order of decreasing population, we’ll fix this.
We want the notebook to be saved as both a .ipynb and a .py file: we add a "jupytext_formats": "ipynb,py", entry to the notebook metadata.
The Python script can be opened with PyCharm:
Navigating in the code and documentation is easier than in Jupyter.
The console is convenient for quick tests. We don’t need to create cells for this.
We find out that the columns of the data frame were not in the correct order. We update the corresponding cell, and get the correct plot.
The Jupyter notebook is refreshed in the browser. Modified inputs are loaded from the Python script. Outputs and variables are preserved. We finally rerun the code and get the correct plot.
With Jupytext, every Julia, Python or R script, R Markdown or Markdown document becomes a potential Jupyter notebook. Write your notebooks as text, and render them in Jupyter when desired.
In the animation below,
Jupyter notebook (not lab, stay tuned) opens our plain Python script as a Jupyter notebook.
Saving from Jupyter adds a YAML header to the otherwise unchanged file.
Adding a cell to the notebook contributes a very simple diff.
Refreshing the notebook preserves the variables, but not the outputs. Outputs are not stored in text files.
We pair the script with a traditional Jupyter notebook by adding a "jupytext_formats": "ipynb,py", entry to the notebook metadata. When we save, a new ipynb file is created.
Thanks to the ipynb file, outputs are preserved when the notebook is refreshed or reloaded.
Have you ever tried to merge Jupyter notebooks? You should either use nbdime, or get prepared for a Unreadable Notebook: NotJSONError if a comma or parenthesis is missing in the merged JSON!
With Jupytext, collaborating on notebooks becomes just as easy as collaborating on scripts.
Check in the text version only. Enjoy easy merges and meaningful diffs!
Jupytext is available on pypi. Install the python package and configure Jupyter to use Jupytext’s content manager:
# Get Jupytext from pippip install jupytext --upgrade# Append this to .jupyter/jupyter_notebook_config.py c.NotebookApp.contents_manager_class="jupytext.TextFileContentsManager"# And restart your notebook serverjupyter notebook
Associate a Python script to your Jupyter notebook, or an ipynb file to your Python script (for the convenience of preserving cell outputs), by adding "jupytext_formats": "ipynb,py", in the notebook metadata (replace py with your favorite extension). If you plan to keep Jupyter open while you edit the text file outside of Jupyter, turn off Jupyter's autosave by running %autosave 0 in a cell.
The idea of working on Jupyter notebooks as text is not new. Alternative converters implemented in Python include:
notedown: Jupyter notebooks as Markdown documents,
ipymd: Jupyter notebooks as Markdown documents, Python scripts, and OpenDocument files,
A fork of ipymd that adds the support of R Markdown and R HTML notebooks,
pynb: Jupyter notebooks as Python scripts.
We are following with much interest the Hydrogen plugin for Atom, and the Jupyter extension for Visual Studio Code. These extensions turn scripts (with explicit cell markers which we hope to support in Jupytext at some point) into interactive notebook-like environments.
Jupytext is my first significant open source contribution. Working on an open source project was a great experience. I asked many questions around and really appreciated the helpful answers, suggestions and also collaborations.
Especially, I want to thank Gregor Sturm for his great idea that we could pair text notebooks with the traditional Jupyter notebooks, and for his feedback on the project. Eric Lebigot and François Wouts’ advices on how to advance and communicate on the project were very helpful. Finally, I’d like to thank the early beta testers for the time spent on experimenting new ways of collaborating on Jupyter notebooks with Jupytext.
Jupytext owes much to the feedback of its users. Suggestions and questions are welcome: please use the issue tracker on our GitHub project for suggesting improvements in either the program or the documentation. See you there!
|
[
{
"code": null,
"e": 418,
"s": 171,
"text": "Jupyter notebooks are interactive documents that contain code, narratives, plots. They are an excellent place for experimenting with code and data. Notebooks are easily shared, and the 2.6M notebooks on GitHub just tell how popular notebooks are!"
},
{
"code": null,
"e": 682,
"s": 418,
"text": "Jupyter notebooks are great, but they often are huge files, with a very specific JSON file format. Let us introduce Jupytext, a Jupyter plugin that reads and writes notebooks as plain text files: either Julia, Python, R scripts, Markdown, or R Markdown documents."
},
{
"code": null,
"e": 777,
"s": 682,
"text": "We wrote Jupytext to work on Jupyter notebooks just like we work on text files. With Jupytext,"
},
{
"code": null,
"e": 903,
"s": 777,
"text": "refactoring a notebook (represented as e.g. a plain Python script) in your favorite text editor or IDE becomes a real option,"
},
{
"code": null,
"e": 976,
"s": 903,
"text": "writing notebooks directly as scripts or Markdown is another option, and"
},
{
"code": null,
"e": 1045,
"s": 976,
"text": "collaborating on Jupyter notebooks with Git becomes straightforward."
},
{
"code": null,
"e": 1355,
"s": 1045,
"text": "The text representation of a notebook focuses on the part that we have actually written: cell inputs. We value inputs more than outputs. Often they are the only part of the notebook that we want to have under version control. Inputs are incomparably lighter than outputs (commonly kilobytes versus megabytes)."
},
{
"code": null,
"e": 1754,
"s": 1355,
"text": "We also value outputs. Preserving outputs is possible with paired notebooks. In that configuration, Jupyter saves the notebook as a traditional .ipynb file, in addition to the script or Markdown document. The text representation can be edited outside of Jupyter. When reloading the notebook in Jupyter, cell inputs are taken from the text file, and matching outputs are loaded from the .ipynb file."
},
{
"code": null,
"e": 2000,
"s": 1754,
"text": "In this first animation we show how your favorite text editor or IDE can be used to edit your Jupyter notebooks. IDEs are more convenient than Jupyter for navigating through code, editing and executing cells or fractions of cells, and debugging."
},
{
"code": null,
"e": 2018,
"s": 2000,
"text": "Animation script:"
},
{
"code": null,
"e": 2052,
"s": 2018,
"text": "We start with a Jupyter notebook."
},
{
"code": null,
"e": 2180,
"s": 2052,
"text": "The notebook includes a plot of the world population. The plot legend is not in order of decreasing population, we’ll fix this."
},
{
"code": null,
"e": 2319,
"s": 2180,
"text": "We want the notebook to be saved as both a .ipynb and a .py file: we add a \"jupytext_formats\": \"ipynb,py\", entry to the notebook metadata."
},
{
"code": null,
"e": 2365,
"s": 2319,
"text": "The Python script can be opened with PyCharm:"
},
{
"code": null,
"e": 2433,
"s": 2365,
"text": "Navigating in the code and documentation is easier than in Jupyter."
},
{
"code": null,
"e": 2516,
"s": 2433,
"text": "The console is convenient for quick tests. We don’t need to create cells for this."
},
{
"code": null,
"e": 2654,
"s": 2516,
"text": "We find out that the columns of the data frame were not in the correct order. We update the corresponding cell, and get the correct plot."
},
{
"code": null,
"e": 2844,
"s": 2654,
"text": "The Jupyter notebook is refreshed in the browser. Modified inputs are loaded from the Python script. Outputs and variables are preserved. We finally rerun the code and get the correct plot."
},
{
"code": null,
"e": 3033,
"s": 2844,
"text": "With Jupytext, every Julia, Python or R script, R Markdown or Markdown document becomes a potential Jupyter notebook. Write your notebooks as text, and render them in Jupyter when desired."
},
{
"code": null,
"e": 3057,
"s": 3033,
"text": "In the animation below,"
},
{
"code": null,
"e": 3149,
"s": 3057,
"text": "Jupyter notebook (not lab, stay tuned) opens our plain Python script as a Jupyter notebook."
},
{
"code": null,
"e": 3221,
"s": 3149,
"text": "Saving from Jupyter adds a YAML header to the otherwise unchanged file."
},
{
"code": null,
"e": 3283,
"s": 3221,
"text": "Adding a cell to the notebook contributes a very simple diff."
},
{
"code": null,
"e": 3391,
"s": 3283,
"text": "Refreshing the notebook preserves the variables, but not the outputs. Outputs are not stored in text files."
},
{
"code": null,
"e": 3565,
"s": 3391,
"text": "We pair the script with a traditional Jupyter notebook by adding a \"jupytext_formats\": \"ipynb,py\", entry to the notebook metadata. When we save, a new ipynb file is created."
},
{
"code": null,
"e": 3657,
"s": 3565,
"text": "Thanks to the ipynb file, outputs are preserved when the notebook is refreshed or reloaded."
},
{
"code": null,
"e": 3848,
"s": 3657,
"text": "Have you ever tried to merge Jupyter notebooks? You should either use nbdime, or get prepared for a Unreadable Notebook: NotJSONError if a comma or parenthesis is missing in the merged JSON!"
},
{
"code": null,
"e": 3940,
"s": 3848,
"text": "With Jupytext, collaborating on notebooks becomes just as easy as collaborating on scripts."
},
{
"code": null,
"e": 4012,
"s": 3940,
"text": "Check in the text version only. Enjoy easy merges and meaningful diffs!"
},
{
"code": null,
"e": 4127,
"s": 4012,
"text": "Jupytext is available on pypi. Install the python package and configure Jupyter to use Jupytext’s content manager:"
},
{
"code": null,
"e": 4356,
"s": 4127,
"text": "# Get Jupytext from pippip install jupytext --upgrade# Append this to .jupyter/jupyter_notebook_config.py c.NotebookApp.contents_manager_class=\"jupytext.TextFileContentsManager\"# And restart your notebook serverjupyter notebook "
},
{
"code": null,
"e": 4751,
"s": 4356,
"text": "Associate a Python script to your Jupyter notebook, or an ipynb file to your Python script (for the convenience of preserving cell outputs), by adding \"jupytext_formats\": \"ipynb,py\", in the notebook metadata (replace py with your favorite extension). If you plan to keep Jupyter open while you edit the text file outside of Jupyter, turn off Jupyter's autosave by running %autosave 0 in a cell."
},
{
"code": null,
"e": 4866,
"s": 4751,
"text": "The idea of working on Jupyter notebooks as text is not new. Alternative converters implemented in Python include:"
},
{
"code": null,
"e": 4917,
"s": 4866,
"text": "notedown: Jupyter notebooks as Markdown documents,"
},
{
"code": null,
"e": 5005,
"s": 4917,
"text": "ipymd: Jupyter notebooks as Markdown documents, Python scripts, and OpenDocument files,"
},
{
"code": null,
"e": 5079,
"s": 5005,
"text": "A fork of ipymd that adds the support of R Markdown and R HTML notebooks,"
},
{
"code": null,
"e": 5122,
"s": 5079,
"text": "pynb: Jupyter notebooks as Python scripts."
},
{
"code": null,
"e": 5393,
"s": 5122,
"text": "We are following with much interest the Hydrogen plugin for Atom, and the Jupyter extension for Visual Studio Code. These extensions turn scripts (with explicit cell markers which we hope to support in Jupytext at some point) into interactive notebook-like environments."
},
{
"code": null,
"e": 5621,
"s": 5393,
"text": "Jupytext is my first significant open source contribution. Working on an open source project was a great experience. I asked many questions around and really appreciated the helpful answers, suggestions and also collaborations."
},
{
"code": null,
"e": 6050,
"s": 5621,
"text": "Especially, I want to thank Gregor Sturm for his great idea that we could pair text notebooks with the traditional Jupyter notebooks, and for his feedback on the project. Eric Lebigot and François Wouts’ advices on how to advance and communicate on the project were very helpful. Finally, I’d like to thank the early beta testers for the time spent on experimenting new ways of collaborating on Jupyter notebooks with Jupytext."
}
] |
OrientDB - Insert Record
|
OrientDB is a NoSQL database that can store the documents and graph-oriented data. NoSQL database does not contain any table, so how can you insert data as a record. Here you can see the table data in the form of class, property, vertex, and edge meaning classes are like tables, and properties are like files in the tables.
We can define all these entities using schema in OrientDB. Property data can be inserted into a class. Insert command creates a new record in the database schema. Records can be schema-less or follow some specified rules.
The following statement is the basic syntax of the Insert Record command.
INSERT INTO [class:]<class>|cluster:<cluster>|index:<index>
[(<field>[,]*) VALUES (<expression>[,]*)[,]*]|
[SET <field> = <expression>|<sub-command>[,]*]|
[CONTENT {<JSON>}]
[RETURN <expression>]
[FROM <query>]
Following are the details about the options in the above syntax.
SET − Defines each field along with the value.
CONTENT − Defines JSON data to set field values. This is optional.
RETURN − Defines the expression to return instead of number of records inserted. The most common use cases are −
@rid − Returns the Record ID of the new record.
@rid − Returns the Record ID of the new record.
@this − Returns the entire new record.
@this − Returns the entire new record.
FROM − Where you want to insert the record or a result set.
Let us consider a Customer table with the following fields and types.
You can create the Schema (table) by executing the following commands.
CREATE DATABASE PLOCAL:/opt/orientdb/databases/sales
CREATE CLASS Customer
CREATE PROPERTY Customer.id integer
CREATE PROPERTY Customer.name String
CREATE PROPERTY Customer.age integer
After executing all the commands, you will get the table name Customer with id, name, and age fields. You can check the table by executing select query into the Customer table.
OrientDB provides different ways to insert a record. Consider the following Customer table containing the sample records.
The following command is to insert the first record into the Customer table.
INSERT INTO Customer (id, name, age) VALUES (01,'satish', 25)
If the above command is successfully executed, you will get the following output.
Inserted record 'Customer#11:0{id:1,name:satish,age:25} v1' in 0.069000 sec(s).
The following command is to insert the second record into the Customer table.
INSERT INTO Customer SET id = 02, name = 'krishna', age = 26
If the above command is successfully executed, you will get the following output.
Inserted record 'Customer#11:1{id:2,age:26,name:krishna} v1' in 0.005000 sec(s).
The following command is to insert the third record into the Customer table.
INSERT INTO Customer CONTENT {"id": "03", "name": "kiran", "age": "29"}
If the above command is successfully executed, you will get the following output.
Inserted record 'Customer#11:2{id:3,name:kiran,age:29} v1' in 0.004000 sec(s).
The following command is to insert the next two records into the Customer table.
INSERT INTO Customer (id, name, age) VALUES (04,'javeed', 21), (05,'raja', 29)
If the above command is successfully executed, you will get the following output.
Inserted record '[Customer#11:3{id:4,name:javeed,age:21} v1,
Customer#11:4{id:5,name:raja,age:29} v1]' in 0.007000 sec(s).
You can check if all these records are inserted or not by executing the following command.
SELECT FROM Customer
If the above command is successfully executed, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:0|Customer|1 |satish |25
1 |#11:1|Customer|2 |krishna|26
2 |#11:2|Customer|3 |kiran |29
3 |#11:3|Customer|4 |javeed |21
4 |#11:4|Customer|5 |raja |29
----+-----+--------+----+-------+----
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3619,
"s": 3294,
"text": "OrientDB is a NoSQL database that can store the documents and graph-oriented data. NoSQL database does not contain any table, so how can you insert data as a record. Here you can see the table data in the form of class, property, vertex, and edge meaning classes are like tables, and properties are like files in the tables."
},
{
"code": null,
"e": 3841,
"s": 3619,
"text": "We can define all these entities using schema in OrientDB. Property data can be inserted into a class. Insert command creates a new record in the database schema. Records can be schema-less or follow some specified rules."
},
{
"code": null,
"e": 3915,
"s": 3841,
"text": "The following statement is the basic syntax of the Insert Record command."
},
{
"code": null,
"e": 4149,
"s": 3915,
"text": "INSERT INTO [class:]<class>|cluster:<cluster>|index:<index> \n [(<field>[,]*) VALUES (<expression>[,]*)[,]*]| \n [SET <field> = <expression>|<sub-command>[,]*]| \n [CONTENT {<JSON>}] \n [RETURN <expression>] \n [FROM <query>] \n"
},
{
"code": null,
"e": 4214,
"s": 4149,
"text": "Following are the details about the options in the above syntax."
},
{
"code": null,
"e": 4261,
"s": 4214,
"text": "SET − Defines each field along with the value."
},
{
"code": null,
"e": 4328,
"s": 4261,
"text": "CONTENT − Defines JSON data to set field values. This is optional."
},
{
"code": null,
"e": 4441,
"s": 4328,
"text": "RETURN − Defines the expression to return instead of number of records inserted. The most common use cases are −"
},
{
"code": null,
"e": 4489,
"s": 4441,
"text": "@rid − Returns the Record ID of the new record."
},
{
"code": null,
"e": 4537,
"s": 4489,
"text": "@rid − Returns the Record ID of the new record."
},
{
"code": null,
"e": 4576,
"s": 4537,
"text": "@this − Returns the entire new record."
},
{
"code": null,
"e": 4615,
"s": 4576,
"text": "@this − Returns the entire new record."
},
{
"code": null,
"e": 4675,
"s": 4615,
"text": "FROM − Where you want to insert the record or a result set."
},
{
"code": null,
"e": 4745,
"s": 4675,
"text": "Let us consider a Customer table with the following fields and types."
},
{
"code": null,
"e": 4816,
"s": 4745,
"text": "You can create the Schema (table) by executing the following commands."
},
{
"code": null,
"e": 5005,
"s": 4816,
"text": "CREATE DATABASE PLOCAL:/opt/orientdb/databases/sales \nCREATE CLASS Customer \nCREATE PROPERTY Customer.id integer \nCREATE PROPERTY Customer.name String \nCREATE PROPERTY Customer.age integer"
},
{
"code": null,
"e": 5182,
"s": 5005,
"text": "After executing all the commands, you will get the table name Customer with id, name, and age fields. You can check the table by executing select query into the Customer table."
},
{
"code": null,
"e": 5304,
"s": 5182,
"text": "OrientDB provides different ways to insert a record. Consider the following Customer table containing the sample records."
},
{
"code": null,
"e": 5381,
"s": 5304,
"text": "The following command is to insert the first record into the Customer table."
},
{
"code": null,
"e": 5444,
"s": 5381,
"text": "INSERT INTO Customer (id, name, age) VALUES (01,'satish', 25) "
},
{
"code": null,
"e": 5526,
"s": 5444,
"text": "If the above command is successfully executed, you will get the following output."
},
{
"code": null,
"e": 5608,
"s": 5526,
"text": "Inserted record 'Customer#11:0{id:1,name:satish,age:25} v1' in 0.069000 sec(s). \n"
},
{
"code": null,
"e": 5686,
"s": 5608,
"text": "The following command is to insert the second record into the Customer table."
},
{
"code": null,
"e": 5748,
"s": 5686,
"text": "INSERT INTO Customer SET id = 02, name = 'krishna', age = 26 "
},
{
"code": null,
"e": 5830,
"s": 5748,
"text": "If the above command is successfully executed, you will get the following output."
},
{
"code": null,
"e": 5912,
"s": 5830,
"text": "Inserted record 'Customer#11:1{id:2,age:26,name:krishna} v1' in 0.005000 sec(s).\n"
},
{
"code": null,
"e": 5989,
"s": 5912,
"text": "The following command is to insert the third record into the Customer table."
},
{
"code": null,
"e": 6061,
"s": 5989,
"text": "INSERT INTO Customer CONTENT {\"id\": \"03\", \"name\": \"kiran\", \"age\": \"29\"}"
},
{
"code": null,
"e": 6143,
"s": 6061,
"text": "If the above command is successfully executed, you will get the following output."
},
{
"code": null,
"e": 6223,
"s": 6143,
"text": "Inserted record 'Customer#11:2{id:3,name:kiran,age:29} v1' in 0.004000 sec(s).\n"
},
{
"code": null,
"e": 6304,
"s": 6223,
"text": "The following command is to insert the next two records into the Customer table."
},
{
"code": null,
"e": 6384,
"s": 6304,
"text": "INSERT INTO Customer (id, name, age) VALUES (04,'javeed', 21), (05,'raja', 29) "
},
{
"code": null,
"e": 6466,
"s": 6384,
"text": "If the above command is successfully executed, you will get the following output."
},
{
"code": null,
"e": 6590,
"s": 6466,
"text": "Inserted record '[Customer#11:3{id:4,name:javeed,age:21} v1,\nCustomer#11:4{id:5,name:raja,age:29} v1]' in 0.007000 sec(s).\n"
},
{
"code": null,
"e": 6681,
"s": 6590,
"text": "You can check if all these records are inserted or not by executing the following command."
},
{
"code": null,
"e": 6702,
"s": 6681,
"text": "SELECT FROM Customer"
},
{
"code": null,
"e": 6784,
"s": 6702,
"text": "If the above command is successfully executed, you will get the following output."
},
{
"code": null,
"e": 7132,
"s": 6784,
"text": "----+-----+--------+----+-------+---- \n# |@RID |@CLASS |id |name |age \n----+-----+--------+----+-------+---- \n0 |#11:0|Customer|1 |satish |25 \n1 |#11:1|Customer|2 |krishna|26 \n2 |#11:2|Customer|3 |kiran |29 \n3 |#11:3|Customer|4 |javeed |21 \n4 |#11:4|Customer|5 |raja |29 \n----+-----+--------+----+-------+---- \n"
},
{
"code": null,
"e": 7139,
"s": 7132,
"text": " Print"
},
{
"code": null,
"e": 7150,
"s": 7139,
"text": " Add Notes"
}
] |
Maximum sum increasing subsequence | Practice | GeeksforGeeks
|
Given an array of n positive integers. Find the sum of the maximum sum subsequence of the given array such that the integers in the subsequence are sorted in increasing order i.e. increasing subsequence.
Example 1:
Input: N = 5, arr[] = {1, 101, 2, 3, 100}
Output: 106
Explanation:The maximum sum of a
increasing sequence is obtained from
{1, 2, 3, 100}
Example 2:
Input: N = 3, arr[] = {1, 2, 3}
Output: 6
Explanation:The maximum sum of a
increasing sequence is obtained from
{1, 2, 3}
Your Task:
You don't need to read input or print anything. Complete the function maxSumIS() which takes N and array arr as input parameters and returns the maximum value.
Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 103
1 ≤ arr[i] ≤ 105
+1
sanketbhagat1 week ago
SIMPLE JAVA SOLUTION
class Solution{
public int maxSumIS(int arr[], int n) {
//code here.
int dp[] = new int[n];
for(int i=0;i<n;i++) dp[i] = arr[i];
int ans = arr[0];
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(arr[i]>arr[j]){
dp[i] = Math.max(dp[i],arr[i]+dp[j]);
}
}
ans = Math.max(ans,dp[i]);
}
return ans;
}
}
0
milindprajapatmst192 weeks ago
class Solution{
public:
unordered_map<int, int> M;
int maxSumIS(int arr[], int n) {
for (int i = 0; i < n; i++) {
M[arr[i]] = max(M[arr[i]], arr[i]);
for (auto& itr : M) {
if (itr.first < arr[i])
M[arr[i]] = max(M[arr[i]], itr.second + arr[i]);
}
}
int result = 0;
for (auto& itr : M)
result = max(result, itr.second);
return result;
}
};
0
jainmuskan5653 weeks ago
int lis_help(int prev,int curr, int arr[],int n,vector<vector<int>> &dp){ if(curr==n){ return 0; } if(dp[prev+1][curr]!=-1){ return dp[prev+1][curr]; } int maxSum= lis_help(prev,curr+1,arr,n,dp); if(prev==-1 || arr[prev]<arr[curr]){ maxSum=max(maxSum,arr[curr]+lis_help(curr,curr+1,arr,n,dp)); } return dp[prev+1][curr]= maxSum;}int maxSumIS(int arr[], int n) { vector<vector<int>> dp(n+1,vector<int> (n+1,-1)); return lis_help(-1,0,arr,n,dp);}
+1
adityagagtiwari1 month ago
Ez pz java code. Runs in nlogn.
class Solution{public int maxSumIS(int arr[], int n) { //code here. int[] dp =new int[n]; int max = 0; dp[0] = arr[0]; for(int i=1;i<n;i++) { max = 0; for(int j=0;j<i;j++) { if(arr[i]>arr[j]) { max = Math.max(dp[j],max); } } dp[i] = max + arr[i]; } max = 0; for(int i=0;i<n;i++) { max = Math.max(dp[i],max); } return max;} }
0
officialshivaji0071 month ago
int lis(int n,int cur,int maxTillNowIdx,int a[],vector<vector<int>> &dp){ if(cur == n-1) { if(maxTillNowIdx == -1){ return a[cur]; } if(a[cur]> a[maxTillNowIdx]){ return a[cur]; }else return 0; } if(dp[cur][maxTillNowIdx+1]!=-1) return dp[cur][maxTillNowIdx+1]; if(maxTillNowIdx == -1){ return dp[cur][maxTillNowIdx+1]= max(a[cur]+lis(n,cur+1,cur,a,dp),lis(n,cur+1,maxTillNowIdx,a,dp)); } if(a[cur]> a[maxTillNowIdx]){ return dp[cur][maxTillNowIdx+1]=max(a[cur]+lis(n,cur+1,cur,a,dp),lis(n,cur+1,maxTillNowIdx,a,dp)); } return dp[cur][maxTillNowIdx+1]=lis(n,cur+1,maxTillNowIdx,a,dp); }
public:int maxSumIS(int arr[], int n) { // Your code goes here vector<vector<int>> dp(n+2,vector<int>(n+2,-1)); return lis(n,0,-1,arr,dp);}
0
hamidnourashraf1 month ago
class Solution:
def maxSumIS(self, Arr, n):
dp = Arr.copy()
for i in range(1, n):
for j in range(0, i):
if Arr[i] > Arr[j]:
dp[i] = max(dp[i], dp[j]+Arr[i])
return max(dp)
0
annanyamathur1 month ago
int maxSumIS(int arr[], int n)
{
int maxis[n];
maxis[0]=arr[0];
for(int i=1;i<n;i++)
{ maxis[i]=arr[i];
for(int j=0;j<i;j++)
{
if(arr[j]<arr[i])
maxis[i]=max(maxis[i],maxis[j]+arr[i]);
}
}
int res=maxis[0];
for(int i=1;i<n;i++)
{
res=max(res,maxis[i]);
}
return res;
}
0
ash_code2 months ago
testcases are wrong GFGHow come the answer for the following testcase is 138 ? It should be 130 for the subsequence [20, 27, 37, 46]
7
20 8 27 37 9 12 46
0
raghav20892 months ago
int solve(int prev, int currIndex, int arr[], int n, vector<vector<int>> &dp) { if(currIndex >= n) return 0; if(dp[prev + 1][currIndex] != -1) return dp[prev + 1][currIndex]; int notPick = solve(prev, currIndex + 1, arr, n, dp); int pick = 0; if(prev == -1 or arr[prev] < arr[currIndex]) { pick = arr[currIndex] + solve(currIndex, currIndex + 1, arr, n, dp); } return dp[prev + 1][currIndex] = max(pick, notPick);}int maxSumIS(int arr[], int n) { // Your code goes here vector<vector<int>> dp(n + 1, vector<int>(n+1, -1)); return solve(-1, 0, arr, n, dp);}
0
lindan1232 months ago
public:
int maxSumIS(int arr[], int n)
{
int dp[n+1];
int ans = arr[0];
if(n==1)
{
return arr[0];
}
for(int i=0;i<n;i++)
{
dp[i] = arr[i];
}
for(int i=1;i<n;i++)
{
for(int j=0;j<i;j++)
{
if(arr[i]>arr[j] and dp[j]+arr[i]>dp[i])
{
dp[i] = dp[j]+arr[i];
}
}
ans = max(ans,dp[i]);
}
return ans;
}
Time Taken : 0.0
Cpp
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": 443,
"s": 238,
"text": "Given an array of n positive integers. Find the sum of the maximum sum subsequence of the given array such that the integers in the subsequence are sorted in increasing order i.e. increasing subsequence. "
},
{
"code": null,
"e": 454,
"s": 443,
"text": "Example 1:"
},
{
"code": null,
"e": 594,
"s": 454,
"text": "Input: N = 5, arr[] = {1, 101, 2, 3, 100} \nOutput: 106\nExplanation:The maximum sum of a\nincreasing sequence is obtained from\n{1, 2, 3, 100}"
},
{
"code": null,
"e": 605,
"s": 594,
"text": "Example 2:"
},
{
"code": null,
"e": 727,
"s": 605,
"text": "Input: N = 3, arr[] = {1, 2, 3}\nOutput: 6\nExplanation:The maximum sum of a\nincreasing sequence is obtained from\n{1, 2, 3}"
},
{
"code": null,
"e": 901,
"s": 727,
"text": "\nYour Task: \nYou don't need to read input or print anything. Complete the function maxSumIS() which takes N and array arr as input parameters and returns the maximum value."
},
{
"code": null,
"e": 965,
"s": 901,
"text": "\nExpected Time Complexity: O(N2)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1008,
"s": 965,
"text": "\nConstraints:\n1 ≤ N ≤ 103\n1 ≤ arr[i] ≤ 105"
},
{
"code": null,
"e": 1011,
"s": 1008,
"text": "+1"
},
{
"code": null,
"e": 1034,
"s": 1011,
"text": "sanketbhagat1 week ago"
},
{
"code": null,
"e": 1055,
"s": 1034,
"text": "SIMPLE JAVA SOLUTION"
},
{
"code": null,
"e": 1464,
"s": 1055,
"text": "class Solution{\n\tpublic int maxSumIS(int arr[], int n) { \n\t //code here.\n\t int dp[] = new int[n];\n\t for(int i=0;i<n;i++) dp[i] = arr[i];\n\t int ans = arr[0];\n\t for(int i=1;i<n;i++){\n\t for(int j=0;j<i;j++){\n\t if(arr[i]>arr[j]){\n\t dp[i] = Math.max(dp[i],arr[i]+dp[j]);\n\t }\n\t }\n\t ans = Math.max(ans,dp[i]);\n\t }\n\t return ans;\n\t} \n}"
},
{
"code": null,
"e": 1466,
"s": 1464,
"text": "0"
},
{
"code": null,
"e": 1497,
"s": 1466,
"text": "milindprajapatmst192 weeks ago"
},
{
"code": null,
"e": 1936,
"s": 1497,
"text": "class Solution{\n\tpublic:\n\tunordered_map<int, int> M;\n\tint maxSumIS(int arr[], int n) { \n\t for (int i = 0; i < n; i++) {\n\t M[arr[i]] = max(M[arr[i]], arr[i]);\n\t for (auto& itr : M) {\n\t if (itr.first < arr[i]) \n\t M[arr[i]] = max(M[arr[i]], itr.second + arr[i]);\n\t }\n\t }\n\t int result = 0;\n\t for (auto& itr : M)\n\t result = max(result, itr.second);\n\t return result;\n\t} \n};"
},
{
"code": null,
"e": 1938,
"s": 1936,
"text": "0"
},
{
"code": null,
"e": 1963,
"s": 1938,
"text": "jainmuskan5653 weeks ago"
},
{
"code": null,
"e": 2462,
"s": 1963,
"text": "int lis_help(int prev,int curr, int arr[],int n,vector<vector<int>> &dp){ if(curr==n){ return 0; } if(dp[prev+1][curr]!=-1){ return dp[prev+1][curr]; } int maxSum= lis_help(prev,curr+1,arr,n,dp); if(prev==-1 || arr[prev]<arr[curr]){ maxSum=max(maxSum,arr[curr]+lis_help(curr,curr+1,arr,n,dp)); } return dp[prev+1][curr]= maxSum;}int maxSumIS(int arr[], int n) { vector<vector<int>> dp(n+1,vector<int> (n+1,-1)); return lis_help(-1,0,arr,n,dp);}"
},
{
"code": null,
"e": 2465,
"s": 2462,
"text": "+1"
},
{
"code": null,
"e": 2492,
"s": 2465,
"text": "adityagagtiwari1 month ago"
},
{
"code": null,
"e": 2525,
"s": 2492,
"text": "Ez pz java code. Runs in nlogn. "
},
{
"code": null,
"e": 2980,
"s": 2525,
"text": "class Solution{public int maxSumIS(int arr[], int n) { //code here. int[] dp =new int[n]; int max = 0; dp[0] = arr[0]; for(int i=1;i<n;i++) { max = 0; for(int j=0;j<i;j++) { if(arr[i]>arr[j]) { max = Math.max(dp[j],max); } } dp[i] = max + arr[i]; } max = 0; for(int i=0;i<n;i++) { max = Math.max(dp[i],max); } return max;} }"
},
{
"code": null,
"e": 2982,
"s": 2980,
"text": "0"
},
{
"code": null,
"e": 3012,
"s": 2982,
"text": "officialshivaji0071 month ago"
},
{
"code": null,
"e": 3770,
"s": 3012,
"text": " int lis(int n,int cur,int maxTillNowIdx,int a[],vector<vector<int>> &dp){ if(cur == n-1) { if(maxTillNowIdx == -1){ return a[cur]; } if(a[cur]> a[maxTillNowIdx]){ return a[cur]; }else return 0; } if(dp[cur][maxTillNowIdx+1]!=-1) return dp[cur][maxTillNowIdx+1]; if(maxTillNowIdx == -1){ return dp[cur][maxTillNowIdx+1]= max(a[cur]+lis(n,cur+1,cur,a,dp),lis(n,cur+1,maxTillNowIdx,a,dp)); } if(a[cur]> a[maxTillNowIdx]){ return dp[cur][maxTillNowIdx+1]=max(a[cur]+lis(n,cur+1,cur,a,dp),lis(n,cur+1,maxTillNowIdx,a,dp)); } return dp[cur][maxTillNowIdx+1]=lis(n,cur+1,maxTillNowIdx,a,dp); }"
},
{
"code": null,
"e": 3927,
"s": 3770,
"text": "public:int maxSumIS(int arr[], int n) { // Your code goes here vector<vector<int>> dp(n+2,vector<int>(n+2,-1)); return lis(n,0,-1,arr,dp);} "
},
{
"code": null,
"e": 3929,
"s": 3927,
"text": "0"
},
{
"code": null,
"e": 3956,
"s": 3929,
"text": "hamidnourashraf1 month ago"
},
{
"code": null,
"e": 4165,
"s": 3956,
"text": "class Solution:\n\tdef maxSumIS(self, Arr, n):\n\t\tdp = Arr.copy()\n\t\tfor i in range(1, n):\n\t\t for j in range(0, i):\n\t\t if Arr[i] > Arr[j]:\n\t\t dp[i] = max(dp[i], dp[j]+Arr[i])\n\t\treturn max(dp)"
},
{
"code": null,
"e": 4167,
"s": 4165,
"text": "0"
},
{
"code": null,
"e": 4192,
"s": 4167,
"text": "annanyamathur1 month ago"
},
{
"code": null,
"e": 4587,
"s": 4192,
"text": "int maxSumIS(int arr[], int n) \n\t{ \n\t int maxis[n];\n\t maxis[0]=arr[0];\n\t for(int i=1;i<n;i++)\n\t { maxis[i]=arr[i];\n\t for(int j=0;j<i;j++)\n\t {\n\t if(arr[j]<arr[i])\n\t maxis[i]=max(maxis[i],maxis[j]+arr[i]);\n\t }\n\t }\n\t int res=maxis[0];\n\t for(int i=1;i<n;i++)\n\t {\n\t res=max(res,maxis[i]);\n\t }\n\t \n\t return res;\n\t} "
},
{
"code": null,
"e": 4589,
"s": 4587,
"text": "0"
},
{
"code": null,
"e": 4610,
"s": 4589,
"text": "ash_code2 months ago"
},
{
"code": null,
"e": 4743,
"s": 4610,
"text": "testcases are wrong GFGHow come the answer for the following testcase is 138 ? It should be 130 for the subsequence [20, 27, 37, 46]"
},
{
"code": null,
"e": 4764,
"s": 4743,
"text": "7\n20 8 27 37 9 12 46"
},
{
"code": null,
"e": 4766,
"s": 4764,
"text": "0"
},
{
"code": null,
"e": 4789,
"s": 4766,
"text": "raghav20892 months ago"
},
{
"code": null,
"e": 5407,
"s": 4789,
"text": "int solve(int prev, int currIndex, int arr[], int n, vector<vector<int>> &dp) { if(currIndex >= n) return 0; if(dp[prev + 1][currIndex] != -1) return dp[prev + 1][currIndex]; int notPick = solve(prev, currIndex + 1, arr, n, dp); int pick = 0; if(prev == -1 or arr[prev] < arr[currIndex]) { pick = arr[currIndex] + solve(currIndex, currIndex + 1, arr, n, dp); } return dp[prev + 1][currIndex] = max(pick, notPick);}int maxSumIS(int arr[], int n) { // Your code goes here vector<vector<int>> dp(n + 1, vector<int>(n+1, -1)); return solve(-1, 0, arr, n, dp);} "
},
{
"code": null,
"e": 5409,
"s": 5407,
"text": "0"
},
{
"code": null,
"e": 5431,
"s": 5409,
"text": "lindan1232 months ago"
},
{
"code": null,
"e": 5922,
"s": 5431,
"text": "public:\n\tint maxSumIS(int arr[], int n) \n\t{ \n\t int dp[n+1];\n\t int ans = arr[0];\n\t \n\t if(n==1)\n\t {\n\t return arr[0];\n\t }\n\t \n\t for(int i=0;i<n;i++)\n\t {\n\t dp[i] = arr[i];\n\t }\n\t \n\t for(int i=1;i<n;i++)\n\t {\n\t for(int j=0;j<i;j++)\n\t {\n\t if(arr[i]>arr[j] and dp[j]+arr[i]>dp[i])\n\t {\n\t dp[i] = dp[j]+arr[i];\n\t }\n\t }\n\t ans = max(ans,dp[i]);\n\t }\n\t return ans;\n\t} "
},
{
"code": null,
"e": 5939,
"s": 5922,
"text": "Time Taken : 0.0"
},
{
"code": null,
"e": 5943,
"s": 5939,
"text": "Cpp"
},
{
"code": null,
"e": 6089,
"s": 5943,
"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": 6125,
"s": 6089,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6135,
"s": 6125,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6145,
"s": 6135,
"text": "\nContest\n"
},
{
"code": null,
"e": 6208,
"s": 6145,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6356,
"s": 6208,
"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": 6564,
"s": 6356,
"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": 6670,
"s": 6564,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Exploratory Data Analysis with BigQuery SQL? Easy! | by 💡Mike Shakhomirov | Towards Data Science
|
Can we perform Exploratory Data Analysis with SQL?
— Yes, we can.
It is about Exploratory Data Analysis (EDA) and aims to answer the following questions:
What is Exploratory Data Analysis (EDA)?
How to perform Exploratory Data Analysis (EDA) in Pandas (Python)?
How to perform Exploratory Data Analysis (EDA) in BigQuery SQL and how is it different from Pandas?
How to use dynamic SQL in BigQuery for Exploratory Data Analysis (EDA)?
How to create visualisations to explore your dataset in BigQuery / Pandas?
How to use Pandas/ BigQuery SQL to analyse relationships between variables for feature selection?
Who is this article for?
Marketers who might want to analyse the data like Data scientists and create dashboards.
Analysts who have been asked to perform EDA and cleanse the data.
Machine learning and AI practitioners who have been always using Python before.
Very often it is easier to perform analysis using SQL on data you have right in the tables and then move forward to ML/AI/Data science and engineering. These days you can even create machine learning models with SQL. Just check what BigQuery ML can do. Everything seems to be moving to data warehouses.
In this tutorial I will be using user churn dataset from Kaggle to analyse, cleanse and prepare it for Machine learning.
There is a Python notebook attached to this article. I will talk you through each query and explain how to do the same thing using SQL (I will be using BigQuery standard SQL).
Clone the repo: git clone https://github.com/mshakhomirov/eda_user_churn.gitUse ./Churn.csv to create a table in BigQuery:
Clone the repo: git clone https://github.com/mshakhomirov/eda_user_churn.git
Use ./Churn.csv to create a table in BigQuery:
You can create table easily by simply uploading the Churn.csv file from the repository:
Click your dataset -> Create Table -> upload:
Exploratory Data Analysis (EDA), also known as Data Exploration, is a step in the Data Analysis Process, where would normally use different techniques to better understand the data we have.
This can refer to a number of things including:
Identifying outliers, missing values, human error or biased sampling.
Understanding importance of the variables and removing useless ones.
Analysing the relationship between dataset features (variables).
Ultimately, getting as much as possible from your data and maximising the insights.
Ultimately Data Analysis aims to achieve two goals:
- Provide an insight into the relationships between variables.
- Describe the dataset using various stats.
We’ll use a user churn dataset obtained from Kaggle. It contains data about customers who are withdrawing their account from a bank. In other words we’ll be analysing churn.
To me, there are main components of exploring data:
Understanding your variables- Import Data from Database — do we really need this if it’s already there?- Get Summary Statistics- Data with Group Filtering- Data with Time Series- Data with Window CalculationAnalyzing relationships between variables- Visualization (usually helps straight away)- Correlation analysis (that’s what seasoned data scientists would normally do before moving to machine learning)
Understanding your variables- Import Data from Database — do we really need this if it’s already there?- Get Summary Statistics- Data with Group Filtering- Data with Time Series- Data with Window Calculation
Analyzing relationships between variables- Visualization (usually helps straight away)- Correlation analysis (that’s what seasoned data scientists would normally do before moving to machine learning)
These steps help to identify outliers, missing values, input and measurment errors, dataset imbalance, biased data collection and analyze a range for Categorical/Contionious features to select only valid ones.
Python:
#Import Librariesimport numpy as npimport pandas as pdimport matplotlib.pylab as pltimport seaborn as sns#Understanding my variablesdf.shapedf.head()df.columnsdf.dtypes
SQL:
Same in BigQuery Standard SQL (we will be using standard SQL) for df.shape:
SELECT count(distinct column_name) , (select count(*) from `your-client.staging.churn`)FROM `your-client.staging.INFORMATION_SCHEMA.COLUMNS`WHERE table_name = 'churn'
Columns and variable types for df.dtypes and df.columns
You can now use INFORMATION_SCHEMA — a series of views that provide access to metadata about datasets, tables, and views:
SELECT * EXCEPT(is_generated, generation_expression, is_stored, is_updatable)FROM `your-project.staging.INFORMATION_SCHEMA.COLUMNS`WHERE table_name = 'churn'
Python:
df.nunique(axis=0)
Just one line of code in Python. Let’s see if we could do the same in SQL.
SQL:
This is where it starts falling apart. It is beautiful in Python. SQL is not designed for high level data analysis.df.nunique function gives us stats for each column in our table with just using one (!) function.
You now can get unique values for each column in SQL with just one operation.
Just run this code in BigQuery (replace your-client with your project name):
Result:
How to describe a dataframe or a table with Python?
How to do the same with just SQL?
Python:
df.describe().apply(lambda s: s.apply(lambda x: format(x, 'f')))
SQL:
Remember this describe function works for numerical features only. Let’s create our own function to use in BigQuery SQL.
Firstly we need to adjust our SET columns variable to use only numerical columns from table schema:
SET columns = (WITH all_columns AS (SELECT column_nameFROM `your-client.staging.INFORMATION_SCHEMA.COLUMNS`WHERE table_name = 'churn'and data_type IN ('INT64','FLOAT64'))SELECT ARRAY_AGG((column_name) ) AS columns FROM all_columns);
There is an easy way to get Pandas like nifty describe() statistics for your BigQuery table using standard SQL.
Then I will add mean, max, min, median, 0.75 tile, 0.25 tile so the final SQL would be like this:
Result:
Probably worth adding ROUND() for better reading. Now you have your own funtion which returns Pandas like describe() result for your BigQuery table.
Let’s check if we have any missing values.
Python:
df.isnull().sum()
SQL:
Same script as we ran before. Just add:
countif(your-column is null)
Dynamic SQL in BigQuery simplifies and speeds up Exploratory Data Analysis
This is to remove any values outside of the set boundaries.
How to identify these boundaries? Well that’s a good question. The first approach is to simply remove, for example, first 5 and the last 5 percentiles of your sample. The second thing we could do here is to calculate the mean and standard deviation of a given sample, then calculate the cut-off for identifying outliers as more than 3 standard deviations from the mean. Lastly you could simpy use your intuition and cut off the rows where you think the values are too high/low.
Try these outlier detection methods:
Interquartile Range Method
Standard Deviation Method
Automatic Outlier Detection
Let’s check outliers for estimated salary if it’s more than 3 standard deviations from the mean.
Python:
Result:
We can see that one salary [301348.88] is way higher than the others. It might be good to remove this one as it might affect something, for example, if we decide to perform Churn prediction later.
So you might want to clean your Pandas df like so (this will delete the rows containing outliers):
df_cleaned = df_cleaned[df_cleaned['EstimatedSalary']<272738.696]
SQL:
We know the standard deviation for Estimated Salary column already, right? So simple select query will do the job:
SELECT * from `your-client.staging.churn` WHERE EstimatedSalary > 272738.696--OR EstimatedSalary < -72518.216; -- Salary can't be negative. So our cut_off parameter probably needs tweaking.
Or we could use dynamic SQL:
Removing Rows with Null Values
Python:
df = df.dropna(axis=0)
SQL:
SELECT * FROM `your-client.staging.churn` WHERE column IS NULL;
Oh, hold on a sec, is it just one column? We can use dynamic SQL here to do it in one go for all of them:
I think this is not the best way to do it though. I would rather generate a WHERE clause with IS NOT NULL check for each column and then just run it with one SELECT query.
Remember DELETE in SQL performs a table scan each time and might be expensive.
We expect to be able to see how different features affect customer churn. Let’s see how many customers have churn:
Python:
Result:
Here we used the following libraries to create that chart:
import matplotlib.pyplot as pltimport seaborn as snsimport matplotlib.cm as cm%matplotlib inline
Looks like a lot of code and you really need to spend quite a time to learn how to use this. Especially if you are not a Data Scientist and never used python before.
Let’s see what BigQuery SQL can offer.
SQL:
Result:
SQL looks way more intuitive. Let’s explore and visualise the data with Data Studio. It will generate the chart we need even without SQL. Let’s go to our churn table, click it , then click Explore with Data Studio and add exited column into dimensions.
If you need to see a percentage of churn and retained users next to exact amount it can be done too. Just run this SQL and then click Explore with Data Studio:
Then change dimensions to exited_category and metrics as shown on the image below. Then click Add chart at the top and add Bar and Pie charts:
Very simple. It’s up to you to decide which way to use Python or BigQuery SQL.
BigQuery with Data Studio makes exploring your data with visuals really simple.
It is important to know if our dataset suffers from data imbalance, which usually reflects an unequal distribution of classes within a dataset.
Often dataset imbalance is caused by a sampling bias or measurement error, for example, all the sample were collected in one geographical region. This may affect classification problem drastically.
So these simple groupings help us to understand if our dataset is imbalanced or not.
It’s very important for classification models.
Most of the contemporary works in class imbalance concentrate on imbalance ratios ranging from 1:4 up to 1:100. [...] In real-life applications such as fraud detection or cheminformatics we may deal with problems with imbalance ratio ranging from 1:1000 up to 1:5000.
— Learning from imbalanced data — Open challenges and future directions, 2016.
A slight imbalance is often not a concern, and the problem can often be treated like a normal classification predictive modeling problem. A severe imbalance of the classes can be challenging to model and may require the use of specialized techniques.
Any dataset with an unequal class distribution is technically imbalanced. Performing this group analysis help us to understand the nature of imbalance and if there was any bias or collection errors.
We can see that our dataset doesn’t suffer from severe imbalance as all the features are distrubuted more or less equally across two main categories of exited.
Let’s see how it works and take a quick look into categorical variables we have, e.g. ‘gender’, ‘country’, ‘owns_credit_card’, ‘is_active_member’.
Python:
Result:
Again, if you want to do these plots in Python you really need to know Python. What if you just want to know if there is a relationship between features? What if you just want to know which category of customers that churn is greater (e.g. female/male, which country or those are more active than the others)? It’s a simple question and you don’t need to be a data scientist to answer it.
SQL:
SELECT * FROM `your-client.staging.churn`;
Explore in Data Studio:
You can see that simple drag and drop does the same thing. Data Studio charts are interactive so you can click a category and it will filter the dashboard based on your selection. You can do all types of groupings and drill downs too.
You can create interactive graphs and charts like a Data scientist! I think it’s beautiful, especially when it’s free.
Me personally, I find it way quicker to create exploratory graphs with Seaborn or Matplotlib.
Data Studio allows you to create a dashboard and forget about re-running your Python notebook if data in tables have changed.
It will update the graphs itself.
I like correlation matrix because it’s a quick way to display relationshp between variables.
Correlation is usually defined as a measure of the linear relationship between two quantitative variables (e.g., height and weight). The higher the weight more greater the affect on the target variable (if one change the other one will follow) and the higher the relationship between two of them.
Let’s create a correlation matrix.
Python:
Result:
We can see that there is a positive correlation between Exited and Age and some negative correlation between Exited and isActiveMember. Also you can see how different features correlate with each other.
Google BigQuery has done a great job on their statistical functions.
Now when we have dynamic SQL in BigQuery we can have a correlation matrix same way Data scientists would normally do it in Python.
Let’s run a simple SQL query to check how CORR() funtion works in BigQuery:
SELECT corr(CreditScore,Balance) FROM `your-client.staging.churn`
Result: 0.006268381616013866
So we simply need to automate this function run for all the columns we have in the table (except those we want to exclude).
SQL:
Voilà!
In theory if there is a relationship between features you will be able to see it straight away from the graphs:
Scatterplot is great way to visualize the realtionship between two variables, e.g. Age and Salary. It can be very useful and helps to quickly identify outliers. It will also show if a relationship exists or not.
Python:
df.plot(kind='scatter', x='CreditScore', y='Balance')
We can see that there is no visible correlation between CreditScore and Balance.
There is a way to create scatterplots between all your variables in one go.
Python:
sns.pairplot(df)
Nothing shows up. Now let’s see how to do the same in SQL.
Google Data Studio:
Let’s go back to our Explore with Data Studio example. We will have to add scatterplots for our features one by one. Then just colour the bubbles by exited_category in any colour you like.
Box plots are usful when we need to check a distribution of a variable
A box plot (or box-and-whisker plot) shows the distribution of quantitative data in a way that facilitates comparisons between variables or across levels of a categorical variable. The box shows the quartiles of the dataset while the whiskers extend to show the rest of the distribution, except for points that are determined to be “outliers” using a method that is a function of the inter-quartile range.
A box plot consist of 5 things.
Minimum
First Quartile or 25%
Median (Second Quartile) or 50%
Third Quartile or 75%
Maximum
Python:
Nice and easy we can create automated box plots for each varibale:
This helps to viasualise and explain the relationship between continuous variables and the target variable. You can see straight away that customers that churn are older than those who are retained. It also helps to compare median levels of each variable. For example, there is no difference in the median for credit score or tenure between lost and retained customers.
Most of the customers who churn still have a significant balance in their bank account. Estimated salary and the number of products seem not to have any visible effect on customer churn.
Let’s see how to create box plot data in BigQuery. We need data first.
SQL:
Result:
You can now visualise it with Data Studio using a bar chart.
At the moment when this article was written box plots didn’t exist in Data Studio. It can be created with custom visualisations though. Let me know if you are interested and I will create one.
We’ll use histogram when we need to see the distribution of just one variable.
Python:
df['age'].plot(kind='hist', bins=10, figsize=(12,6))
SQL:
If we need equal bucket we can simply do this.
SELECT count(*) frequency, bucket FROM ( SELECT customerId, round(Age / 10)* 10 as bucket FROM `your-client.staging.churn`)GROUP BY bucketorder by 2
Click Explore with Data Studio and you can build a nice Histogram.
After BigQuery announced dynamic SQL feature many things became possible. With that scripting ability we can now automate queries, perform Exploratory Data Analysis and visualise results in Data Studio.
Python still remains a major tool for Data Scientists and provides great scripting features too. However, if we are talking about just getting the numbers BigQuery can do the same thing! When it comes to visualising the results Python definitelly helps to create grpahs quicker when Data Studio provides greater dashboarding experience. You can simply forget about rerunning the queries (or notebooks) when the dashboard is set up. So we just need to create it once.
I hope you enjoyed the reading!
|
[
{
"code": null,
"e": 223,
"s": 172,
"text": "Can we perform Exploratory Data Analysis with SQL?"
},
{
"code": null,
"e": 238,
"s": 223,
"text": "— Yes, we can."
},
{
"code": null,
"e": 326,
"s": 238,
"text": "It is about Exploratory Data Analysis (EDA) and aims to answer the following questions:"
},
{
"code": null,
"e": 367,
"s": 326,
"text": "What is Exploratory Data Analysis (EDA)?"
},
{
"code": null,
"e": 434,
"s": 367,
"text": "How to perform Exploratory Data Analysis (EDA) in Pandas (Python)?"
},
{
"code": null,
"e": 534,
"s": 434,
"text": "How to perform Exploratory Data Analysis (EDA) in BigQuery SQL and how is it different from Pandas?"
},
{
"code": null,
"e": 606,
"s": 534,
"text": "How to use dynamic SQL in BigQuery for Exploratory Data Analysis (EDA)?"
},
{
"code": null,
"e": 681,
"s": 606,
"text": "How to create visualisations to explore your dataset in BigQuery / Pandas?"
},
{
"code": null,
"e": 779,
"s": 681,
"text": "How to use Pandas/ BigQuery SQL to analyse relationships between variables for feature selection?"
},
{
"code": null,
"e": 804,
"s": 779,
"text": "Who is this article for?"
},
{
"code": null,
"e": 893,
"s": 804,
"text": "Marketers who might want to analyse the data like Data scientists and create dashboards."
},
{
"code": null,
"e": 959,
"s": 893,
"text": "Analysts who have been asked to perform EDA and cleanse the data."
},
{
"code": null,
"e": 1039,
"s": 959,
"text": "Machine learning and AI practitioners who have been always using Python before."
},
{
"code": null,
"e": 1342,
"s": 1039,
"text": "Very often it is easier to perform analysis using SQL on data you have right in the tables and then move forward to ML/AI/Data science and engineering. These days you can even create machine learning models with SQL. Just check what BigQuery ML can do. Everything seems to be moving to data warehouses."
},
{
"code": null,
"e": 1463,
"s": 1342,
"text": "In this tutorial I will be using user churn dataset from Kaggle to analyse, cleanse and prepare it for Machine learning."
},
{
"code": null,
"e": 1639,
"s": 1463,
"text": "There is a Python notebook attached to this article. I will talk you through each query and explain how to do the same thing using SQL (I will be using BigQuery standard SQL)."
},
{
"code": null,
"e": 1762,
"s": 1639,
"text": "Clone the repo: git clone https://github.com/mshakhomirov/eda_user_churn.gitUse ./Churn.csv to create a table in BigQuery:"
},
{
"code": null,
"e": 1839,
"s": 1762,
"text": "Clone the repo: git clone https://github.com/mshakhomirov/eda_user_churn.git"
},
{
"code": null,
"e": 1886,
"s": 1839,
"text": "Use ./Churn.csv to create a table in BigQuery:"
},
{
"code": null,
"e": 1974,
"s": 1886,
"text": "You can create table easily by simply uploading the Churn.csv file from the repository:"
},
{
"code": null,
"e": 2020,
"s": 1974,
"text": "Click your dataset -> Create Table -> upload:"
},
{
"code": null,
"e": 2210,
"s": 2020,
"text": "Exploratory Data Analysis (EDA), also known as Data Exploration, is a step in the Data Analysis Process, where would normally use different techniques to better understand the data we have."
},
{
"code": null,
"e": 2258,
"s": 2210,
"text": "This can refer to a number of things including:"
},
{
"code": null,
"e": 2328,
"s": 2258,
"text": "Identifying outliers, missing values, human error or biased sampling."
},
{
"code": null,
"e": 2397,
"s": 2328,
"text": "Understanding importance of the variables and removing useless ones."
},
{
"code": null,
"e": 2462,
"s": 2397,
"text": "Analysing the relationship between dataset features (variables)."
},
{
"code": null,
"e": 2546,
"s": 2462,
"text": "Ultimately, getting as much as possible from your data and maximising the insights."
},
{
"code": null,
"e": 2598,
"s": 2546,
"text": "Ultimately Data Analysis aims to achieve two goals:"
},
{
"code": null,
"e": 2661,
"s": 2598,
"text": "- Provide an insight into the relationships between variables."
},
{
"code": null,
"e": 2705,
"s": 2661,
"text": "- Describe the dataset using various stats."
},
{
"code": null,
"e": 2879,
"s": 2705,
"text": "We’ll use a user churn dataset obtained from Kaggle. It contains data about customers who are withdrawing their account from a bank. In other words we’ll be analysing churn."
},
{
"code": null,
"e": 2931,
"s": 2879,
"text": "To me, there are main components of exploring data:"
},
{
"code": null,
"e": 3338,
"s": 2931,
"text": "Understanding your variables- Import Data from Database — do we really need this if it’s already there?- Get Summary Statistics- Data with Group Filtering- Data with Time Series- Data with Window CalculationAnalyzing relationships between variables- Visualization (usually helps straight away)- Correlation analysis (that’s what seasoned data scientists would normally do before moving to machine learning)"
},
{
"code": null,
"e": 3546,
"s": 3338,
"text": "Understanding your variables- Import Data from Database — do we really need this if it’s already there?- Get Summary Statistics- Data with Group Filtering- Data with Time Series- Data with Window Calculation"
},
{
"code": null,
"e": 3746,
"s": 3546,
"text": "Analyzing relationships between variables- Visualization (usually helps straight away)- Correlation analysis (that’s what seasoned data scientists would normally do before moving to machine learning)"
},
{
"code": null,
"e": 3956,
"s": 3746,
"text": "These steps help to identify outliers, missing values, input and measurment errors, dataset imbalance, biased data collection and analyze a range for Categorical/Contionious features to select only valid ones."
},
{
"code": null,
"e": 3964,
"s": 3956,
"text": "Python:"
},
{
"code": null,
"e": 4133,
"s": 3964,
"text": "#Import Librariesimport numpy as npimport pandas as pdimport matplotlib.pylab as pltimport seaborn as sns#Understanding my variablesdf.shapedf.head()df.columnsdf.dtypes"
},
{
"code": null,
"e": 4138,
"s": 4133,
"text": "SQL:"
},
{
"code": null,
"e": 4214,
"s": 4138,
"text": "Same in BigQuery Standard SQL (we will be using standard SQL) for df.shape:"
},
{
"code": null,
"e": 4389,
"s": 4214,
"text": "SELECT count(distinct column_name) , (select count(*) from `your-client.staging.churn`)FROM `your-client.staging.INFORMATION_SCHEMA.COLUMNS`WHERE table_name = 'churn'"
},
{
"code": null,
"e": 4445,
"s": 4389,
"text": "Columns and variable types for df.dtypes and df.columns"
},
{
"code": null,
"e": 4567,
"s": 4445,
"text": "You can now use INFORMATION_SCHEMA — a series of views that provide access to metadata about datasets, tables, and views:"
},
{
"code": null,
"e": 4725,
"s": 4567,
"text": "SELECT * EXCEPT(is_generated, generation_expression, is_stored, is_updatable)FROM `your-project.staging.INFORMATION_SCHEMA.COLUMNS`WHERE table_name = 'churn'"
},
{
"code": null,
"e": 4733,
"s": 4725,
"text": "Python:"
},
{
"code": null,
"e": 4752,
"s": 4733,
"text": "df.nunique(axis=0)"
},
{
"code": null,
"e": 4827,
"s": 4752,
"text": "Just one line of code in Python. Let’s see if we could do the same in SQL."
},
{
"code": null,
"e": 4832,
"s": 4827,
"text": "SQL:"
},
{
"code": null,
"e": 5045,
"s": 4832,
"text": "This is where it starts falling apart. It is beautiful in Python. SQL is not designed for high level data analysis.df.nunique function gives us stats for each column in our table with just using one (!) function."
},
{
"code": null,
"e": 5123,
"s": 5045,
"text": "You now can get unique values for each column in SQL with just one operation."
},
{
"code": null,
"e": 5200,
"s": 5123,
"text": "Just run this code in BigQuery (replace your-client with your project name):"
},
{
"code": null,
"e": 5208,
"s": 5200,
"text": "Result:"
},
{
"code": null,
"e": 5260,
"s": 5208,
"text": "How to describe a dataframe or a table with Python?"
},
{
"code": null,
"e": 5294,
"s": 5260,
"text": "How to do the same with just SQL?"
},
{
"code": null,
"e": 5302,
"s": 5294,
"text": "Python:"
},
{
"code": null,
"e": 5367,
"s": 5302,
"text": "df.describe().apply(lambda s: s.apply(lambda x: format(x, 'f')))"
},
{
"code": null,
"e": 5372,
"s": 5367,
"text": "SQL:"
},
{
"code": null,
"e": 5493,
"s": 5372,
"text": "Remember this describe function works for numerical features only. Let’s create our own function to use in BigQuery SQL."
},
{
"code": null,
"e": 5593,
"s": 5493,
"text": "Firstly we need to adjust our SET columns variable to use only numerical columns from table schema:"
},
{
"code": null,
"e": 5827,
"s": 5593,
"text": "SET columns = (WITH all_columns AS (SELECT column_nameFROM `your-client.staging.INFORMATION_SCHEMA.COLUMNS`WHERE table_name = 'churn'and data_type IN ('INT64','FLOAT64'))SELECT ARRAY_AGG((column_name) ) AS columns FROM all_columns);"
},
{
"code": null,
"e": 5939,
"s": 5827,
"text": "There is an easy way to get Pandas like nifty describe() statistics for your BigQuery table using standard SQL."
},
{
"code": null,
"e": 6037,
"s": 5939,
"text": "Then I will add mean, max, min, median, 0.75 tile, 0.25 tile so the final SQL would be like this:"
},
{
"code": null,
"e": 6045,
"s": 6037,
"text": "Result:"
},
{
"code": null,
"e": 6194,
"s": 6045,
"text": "Probably worth adding ROUND() for better reading. Now you have your own funtion which returns Pandas like describe() result for your BigQuery table."
},
{
"code": null,
"e": 6237,
"s": 6194,
"text": "Let’s check if we have any missing values."
},
{
"code": null,
"e": 6245,
"s": 6237,
"text": "Python:"
},
{
"code": null,
"e": 6263,
"s": 6245,
"text": "df.isnull().sum()"
},
{
"code": null,
"e": 6268,
"s": 6263,
"text": "SQL:"
},
{
"code": null,
"e": 6308,
"s": 6268,
"text": "Same script as we ran before. Just add:"
},
{
"code": null,
"e": 6338,
"s": 6308,
"text": " countif(your-column is null)"
},
{
"code": null,
"e": 6413,
"s": 6338,
"text": "Dynamic SQL in BigQuery simplifies and speeds up Exploratory Data Analysis"
},
{
"code": null,
"e": 6473,
"s": 6413,
"text": "This is to remove any values outside of the set boundaries."
},
{
"code": null,
"e": 6951,
"s": 6473,
"text": "How to identify these boundaries? Well that’s a good question. The first approach is to simply remove, for example, first 5 and the last 5 percentiles of your sample. The second thing we could do here is to calculate the mean and standard deviation of a given sample, then calculate the cut-off for identifying outliers as more than 3 standard deviations from the mean. Lastly you could simpy use your intuition and cut off the rows where you think the values are too high/low."
},
{
"code": null,
"e": 6988,
"s": 6951,
"text": "Try these outlier detection methods:"
},
{
"code": null,
"e": 7015,
"s": 6988,
"text": "Interquartile Range Method"
},
{
"code": null,
"e": 7041,
"s": 7015,
"text": "Standard Deviation Method"
},
{
"code": null,
"e": 7069,
"s": 7041,
"text": "Automatic Outlier Detection"
},
{
"code": null,
"e": 7166,
"s": 7069,
"text": "Let’s check outliers for estimated salary if it’s more than 3 standard deviations from the mean."
},
{
"code": null,
"e": 7174,
"s": 7166,
"text": "Python:"
},
{
"code": null,
"e": 7182,
"s": 7174,
"text": "Result:"
},
{
"code": null,
"e": 7379,
"s": 7182,
"text": "We can see that one salary [301348.88] is way higher than the others. It might be good to remove this one as it might affect something, for example, if we decide to perform Churn prediction later."
},
{
"code": null,
"e": 7478,
"s": 7379,
"text": "So you might want to clean your Pandas df like so (this will delete the rows containing outliers):"
},
{
"code": null,
"e": 7544,
"s": 7478,
"text": "df_cleaned = df_cleaned[df_cleaned['EstimatedSalary']<272738.696]"
},
{
"code": null,
"e": 7549,
"s": 7544,
"text": "SQL:"
},
{
"code": null,
"e": 7664,
"s": 7549,
"text": "We know the standard deviation for Estimated Salary column already, right? So simple select query will do the job:"
},
{
"code": null,
"e": 7855,
"s": 7664,
"text": "SELECT * from `your-client.staging.churn` WHERE EstimatedSalary > 272738.696--OR EstimatedSalary < -72518.216; -- Salary can't be negative. So our cut_off parameter probably needs tweaking."
},
{
"code": null,
"e": 7884,
"s": 7855,
"text": "Or we could use dynamic SQL:"
},
{
"code": null,
"e": 7915,
"s": 7884,
"text": "Removing Rows with Null Values"
},
{
"code": null,
"e": 7923,
"s": 7915,
"text": "Python:"
},
{
"code": null,
"e": 7946,
"s": 7923,
"text": "df = df.dropna(axis=0)"
},
{
"code": null,
"e": 7951,
"s": 7946,
"text": "SQL:"
},
{
"code": null,
"e": 8015,
"s": 7951,
"text": "SELECT * FROM `your-client.staging.churn` WHERE column IS NULL;"
},
{
"code": null,
"e": 8121,
"s": 8015,
"text": "Oh, hold on a sec, is it just one column? We can use dynamic SQL here to do it in one go for all of them:"
},
{
"code": null,
"e": 8293,
"s": 8121,
"text": "I think this is not the best way to do it though. I would rather generate a WHERE clause with IS NOT NULL check for each column and then just run it with one SELECT query."
},
{
"code": null,
"e": 8372,
"s": 8293,
"text": "Remember DELETE in SQL performs a table scan each time and might be expensive."
},
{
"code": null,
"e": 8487,
"s": 8372,
"text": "We expect to be able to see how different features affect customer churn. Let’s see how many customers have churn:"
},
{
"code": null,
"e": 8495,
"s": 8487,
"text": "Python:"
},
{
"code": null,
"e": 8503,
"s": 8495,
"text": "Result:"
},
{
"code": null,
"e": 8562,
"s": 8503,
"text": "Here we used the following libraries to create that chart:"
},
{
"code": null,
"e": 8659,
"s": 8562,
"text": "import matplotlib.pyplot as pltimport seaborn as snsimport matplotlib.cm as cm%matplotlib inline"
},
{
"code": null,
"e": 8825,
"s": 8659,
"text": "Looks like a lot of code and you really need to spend quite a time to learn how to use this. Especially if you are not a Data Scientist and never used python before."
},
{
"code": null,
"e": 8864,
"s": 8825,
"text": "Let’s see what BigQuery SQL can offer."
},
{
"code": null,
"e": 8869,
"s": 8864,
"text": "SQL:"
},
{
"code": null,
"e": 8877,
"s": 8869,
"text": "Result:"
},
{
"code": null,
"e": 9130,
"s": 8877,
"text": "SQL looks way more intuitive. Let’s explore and visualise the data with Data Studio. It will generate the chart we need even without SQL. Let’s go to our churn table, click it , then click Explore with Data Studio and add exited column into dimensions."
},
{
"code": null,
"e": 9290,
"s": 9130,
"text": "If you need to see a percentage of churn and retained users next to exact amount it can be done too. Just run this SQL and then click Explore with Data Studio:"
},
{
"code": null,
"e": 9433,
"s": 9290,
"text": "Then change dimensions to exited_category and metrics as shown on the image below. Then click Add chart at the top and add Bar and Pie charts:"
},
{
"code": null,
"e": 9512,
"s": 9433,
"text": "Very simple. It’s up to you to decide which way to use Python or BigQuery SQL."
},
{
"code": null,
"e": 9592,
"s": 9512,
"text": "BigQuery with Data Studio makes exploring your data with visuals really simple."
},
{
"code": null,
"e": 9736,
"s": 9592,
"text": "It is important to know if our dataset suffers from data imbalance, which usually reflects an unequal distribution of classes within a dataset."
},
{
"code": null,
"e": 9934,
"s": 9736,
"text": "Often dataset imbalance is caused by a sampling bias or measurement error, for example, all the sample were collected in one geographical region. This may affect classification problem drastically."
},
{
"code": null,
"e": 10019,
"s": 9934,
"text": "So these simple groupings help us to understand if our dataset is imbalanced or not."
},
{
"code": null,
"e": 10066,
"s": 10019,
"text": "It’s very important for classification models."
},
{
"code": null,
"e": 10334,
"s": 10066,
"text": "Most of the contemporary works in class imbalance concentrate on imbalance ratios ranging from 1:4 up to 1:100. [...] In real-life applications such as fraud detection or cheminformatics we may deal with problems with imbalance ratio ranging from 1:1000 up to 1:5000."
},
{
"code": null,
"e": 10413,
"s": 10334,
"text": "— Learning from imbalanced data — Open challenges and future directions, 2016."
},
{
"code": null,
"e": 10664,
"s": 10413,
"text": "A slight imbalance is often not a concern, and the problem can often be treated like a normal classification predictive modeling problem. A severe imbalance of the classes can be challenging to model and may require the use of specialized techniques."
},
{
"code": null,
"e": 10863,
"s": 10664,
"text": "Any dataset with an unequal class distribution is technically imbalanced. Performing this group analysis help us to understand the nature of imbalance and if there was any bias or collection errors."
},
{
"code": null,
"e": 11023,
"s": 10863,
"text": "We can see that our dataset doesn’t suffer from severe imbalance as all the features are distrubuted more or less equally across two main categories of exited."
},
{
"code": null,
"e": 11170,
"s": 11023,
"text": "Let’s see how it works and take a quick look into categorical variables we have, e.g. ‘gender’, ‘country’, ‘owns_credit_card’, ‘is_active_member’."
},
{
"code": null,
"e": 11178,
"s": 11170,
"text": "Python:"
},
{
"code": null,
"e": 11186,
"s": 11178,
"text": "Result:"
},
{
"code": null,
"e": 11575,
"s": 11186,
"text": "Again, if you want to do these plots in Python you really need to know Python. What if you just want to know if there is a relationship between features? What if you just want to know which category of customers that churn is greater (e.g. female/male, which country or those are more active than the others)? It’s a simple question and you don’t need to be a data scientist to answer it."
},
{
"code": null,
"e": 11580,
"s": 11575,
"text": "SQL:"
},
{
"code": null,
"e": 11623,
"s": 11580,
"text": "SELECT * FROM `your-client.staging.churn`;"
},
{
"code": null,
"e": 11647,
"s": 11623,
"text": "Explore in Data Studio:"
},
{
"code": null,
"e": 11882,
"s": 11647,
"text": "You can see that simple drag and drop does the same thing. Data Studio charts are interactive so you can click a category and it will filter the dashboard based on your selection. You can do all types of groupings and drill downs too."
},
{
"code": null,
"e": 12001,
"s": 11882,
"text": "You can create interactive graphs and charts like a Data scientist! I think it’s beautiful, especially when it’s free."
},
{
"code": null,
"e": 12095,
"s": 12001,
"text": "Me personally, I find it way quicker to create exploratory graphs with Seaborn or Matplotlib."
},
{
"code": null,
"e": 12221,
"s": 12095,
"text": "Data Studio allows you to create a dashboard and forget about re-running your Python notebook if data in tables have changed."
},
{
"code": null,
"e": 12255,
"s": 12221,
"text": "It will update the graphs itself."
},
{
"code": null,
"e": 12348,
"s": 12255,
"text": "I like correlation matrix because it’s a quick way to display relationshp between variables."
},
{
"code": null,
"e": 12645,
"s": 12348,
"text": "Correlation is usually defined as a measure of the linear relationship between two quantitative variables (e.g., height and weight). The higher the weight more greater the affect on the target variable (if one change the other one will follow) and the higher the relationship between two of them."
},
{
"code": null,
"e": 12680,
"s": 12645,
"text": "Let’s create a correlation matrix."
},
{
"code": null,
"e": 12688,
"s": 12680,
"text": "Python:"
},
{
"code": null,
"e": 12696,
"s": 12688,
"text": "Result:"
},
{
"code": null,
"e": 12899,
"s": 12696,
"text": "We can see that there is a positive correlation between Exited and Age and some negative correlation between Exited and isActiveMember. Also you can see how different features correlate with each other."
},
{
"code": null,
"e": 12968,
"s": 12899,
"text": "Google BigQuery has done a great job on their statistical functions."
},
{
"code": null,
"e": 13099,
"s": 12968,
"text": "Now when we have dynamic SQL in BigQuery we can have a correlation matrix same way Data scientists would normally do it in Python."
},
{
"code": null,
"e": 13175,
"s": 13099,
"text": "Let’s run a simple SQL query to check how CORR() funtion works in BigQuery:"
},
{
"code": null,
"e": 13242,
"s": 13175,
"text": "SELECT corr(CreditScore,Balance) FROM `your-client.staging.churn`"
},
{
"code": null,
"e": 13271,
"s": 13242,
"text": "Result: 0.006268381616013866"
},
{
"code": null,
"e": 13395,
"s": 13271,
"text": "So we simply need to automate this function run for all the columns we have in the table (except those we want to exclude)."
},
{
"code": null,
"e": 13400,
"s": 13395,
"text": "SQL:"
},
{
"code": null,
"e": 13408,
"s": 13400,
"text": "Voilà!"
},
{
"code": null,
"e": 13520,
"s": 13408,
"text": "In theory if there is a relationship between features you will be able to see it straight away from the graphs:"
},
{
"code": null,
"e": 13732,
"s": 13520,
"text": "Scatterplot is great way to visualize the realtionship between two variables, e.g. Age and Salary. It can be very useful and helps to quickly identify outliers. It will also show if a relationship exists or not."
},
{
"code": null,
"e": 13740,
"s": 13732,
"text": "Python:"
},
{
"code": null,
"e": 13794,
"s": 13740,
"text": "df.plot(kind='scatter', x='CreditScore', y='Balance')"
},
{
"code": null,
"e": 13875,
"s": 13794,
"text": "We can see that there is no visible correlation between CreditScore and Balance."
},
{
"code": null,
"e": 13951,
"s": 13875,
"text": "There is a way to create scatterplots between all your variables in one go."
},
{
"code": null,
"e": 13959,
"s": 13951,
"text": "Python:"
},
{
"code": null,
"e": 13976,
"s": 13959,
"text": "sns.pairplot(df)"
},
{
"code": null,
"e": 14035,
"s": 13976,
"text": "Nothing shows up. Now let’s see how to do the same in SQL."
},
{
"code": null,
"e": 14055,
"s": 14035,
"text": "Google Data Studio:"
},
{
"code": null,
"e": 14244,
"s": 14055,
"text": "Let’s go back to our Explore with Data Studio example. We will have to add scatterplots for our features one by one. Then just colour the bubbles by exited_category in any colour you like."
},
{
"code": null,
"e": 14315,
"s": 14244,
"text": "Box plots are usful when we need to check a distribution of a variable"
},
{
"code": null,
"e": 14721,
"s": 14315,
"text": "A box plot (or box-and-whisker plot) shows the distribution of quantitative data in a way that facilitates comparisons between variables or across levels of a categorical variable. The box shows the quartiles of the dataset while the whiskers extend to show the rest of the distribution, except for points that are determined to be “outliers” using a method that is a function of the inter-quartile range."
},
{
"code": null,
"e": 14753,
"s": 14721,
"text": "A box plot consist of 5 things."
},
{
"code": null,
"e": 14761,
"s": 14753,
"text": "Minimum"
},
{
"code": null,
"e": 14783,
"s": 14761,
"text": "First Quartile or 25%"
},
{
"code": null,
"e": 14815,
"s": 14783,
"text": "Median (Second Quartile) or 50%"
},
{
"code": null,
"e": 14837,
"s": 14815,
"text": "Third Quartile or 75%"
},
{
"code": null,
"e": 14845,
"s": 14837,
"text": "Maximum"
},
{
"code": null,
"e": 14853,
"s": 14845,
"text": "Python:"
},
{
"code": null,
"e": 14920,
"s": 14853,
"text": "Nice and easy we can create automated box plots for each varibale:"
},
{
"code": null,
"e": 15290,
"s": 14920,
"text": "This helps to viasualise and explain the relationship between continuous variables and the target variable. You can see straight away that customers that churn are older than those who are retained. It also helps to compare median levels of each variable. For example, there is no difference in the median for credit score or tenure between lost and retained customers."
},
{
"code": null,
"e": 15477,
"s": 15290,
"text": "Most of the customers who churn still have a significant balance in their bank account. Estimated salary and the number of products seem not to have any visible effect on customer churn."
},
{
"code": null,
"e": 15548,
"s": 15477,
"text": "Let’s see how to create box plot data in BigQuery. We need data first."
},
{
"code": null,
"e": 15553,
"s": 15548,
"text": "SQL:"
},
{
"code": null,
"e": 15561,
"s": 15553,
"text": "Result:"
},
{
"code": null,
"e": 15622,
"s": 15561,
"text": "You can now visualise it with Data Studio using a bar chart."
},
{
"code": null,
"e": 15815,
"s": 15622,
"text": "At the moment when this article was written box plots didn’t exist in Data Studio. It can be created with custom visualisations though. Let me know if you are interested and I will create one."
},
{
"code": null,
"e": 15894,
"s": 15815,
"text": "We’ll use histogram when we need to see the distribution of just one variable."
},
{
"code": null,
"e": 15902,
"s": 15894,
"text": "Python:"
},
{
"code": null,
"e": 15955,
"s": 15902,
"text": "df['age'].plot(kind='hist', bins=10, figsize=(12,6))"
},
{
"code": null,
"e": 15960,
"s": 15955,
"text": "SQL:"
},
{
"code": null,
"e": 16007,
"s": 15960,
"text": "If we need equal bucket we can simply do this."
},
{
"code": null,
"e": 16159,
"s": 16007,
"text": "SELECT count(*) frequency, bucket FROM ( SELECT customerId, round(Age / 10)* 10 as bucket FROM `your-client.staging.churn`)GROUP BY bucketorder by 2"
},
{
"code": null,
"e": 16226,
"s": 16159,
"text": "Click Explore with Data Studio and you can build a nice Histogram."
},
{
"code": null,
"e": 16429,
"s": 16226,
"text": "After BigQuery announced dynamic SQL feature many things became possible. With that scripting ability we can now automate queries, perform Exploratory Data Analysis and visualise results in Data Studio."
},
{
"code": null,
"e": 16896,
"s": 16429,
"text": "Python still remains a major tool for Data Scientists and provides great scripting features too. However, if we are talking about just getting the numbers BigQuery can do the same thing! When it comes to visualising the results Python definitelly helps to create grpahs quicker when Data Studio provides greater dashboarding experience. You can simply forget about rerunning the queries (or notebooks) when the dashboard is set up. So we just need to create it once."
}
] |
5 Frameworks for Reinforcement Learning on Python | by Mauricio Fadel Argerich | Towards Data Science
|
There are lots of standard libraries for supervised and unsupervised machine learning like Scikit-learn, XGBoost or even Tensorflow, that can get you started in no time and you can find log nads of support online. Sadly, for Reinforcement Learning (RL) this is not the case.
It is not that there are no frameworks, as a matter of fact, there are many frameworks for RL out there. The problem is that there is no standard yet, and so finding support online for starting, fixing a problem or customizing a solution is not easily found. This is probably caused by the fact that, while RL is a very popular research topic, it is still in its early days of being implemented and used in the industry.
But this doesn’t mean there are no great frameworks out there that can help you start and use RL for solving any problem you like. I have made a list here of some frameworks I have come to know and use along time, with their benefits and cons. I hope this gives you a quick overview about some of the RL frameworks currently available, so you can choose the one that better fits your needs.
I have to admit from the whole list, this is my favorite. I believe it is by far the simplest to understand code implementation of several RL algorithms including Deep Q Learning (DQN), Double DQN, Deep Deterministic Policy Gradient (DDPG), Continuous DQN (CDQN or NAF), Cross-Entropy Method (CEM), Dueling DQN) and SARSA. When I say “simplest to understand code” I refer not to use, but to customize it and utilize it as a building block for your project*. The Keras-RL github also contains some examples that you can use to get started in no time. It uses Keras of course, and you can use it along with Tensorflow or PyTorch.
Unfortunately, Keras-RL has not been well-maintained for a while already and its official documentation is not the best. This has given light to a fork of this project called Keras-RL2.
(*) What did I use this framework for? Well, I’m glad you asked — or was it me? I have used this framework to create a customized Tutored DQN agent, you can read more about it here.
Keras-RL2 is a fork from Keras-RL and as such it shares support for the same agents as Keras-RL2 and is easily customizable. The big change here is that Keras-RL2 is better maintained and uses Tensorflow 2.1.0. Unfortunately, there is no documentation for this library, even though the documentation for Keras-RL can be easily used for this fork too.
OpenAI Baselines is a set of high-quality implementations of RL algorithms by OpenAI, one of the leading companies in research and development of AI and in particular RL. It was conceived so researchers could compare their RL algorithms easily, using as a baseline the state-of-the-art implementations from OpenAI — thus the name. The framework contains implementations of many popular agents such as A2C, DDPG, DQN, PPO2 and TRPO.
On the downside, OpenAI Baselines is not well documented, even though there are lots of useful comments on the code. In addition, since it was developed to be used as a baseline and not as a building block, the code is not so friendly if you want to customize or modify some of the agents for your projects. In fact, the next framework is a fork from this and solves most of these issues.
Stable Baselines is a fork of OpenAI Baselines, with a major structural refactoring and code cleanups. The changes listed in their official documentation site are the following:
Unified structure for all algorithms
PEP8 compliant (unified code style)
Documented functions and classes
More tests & more code coverage
Additional algorithms: SAC and TD3 (+ HER support for DQN, DDPG, SAC and TD3)
I have personally used Stable Baselines in the past and I can confirm it is really well documented and easy to use. It is even possible to train an agent for OpenAI Gym environments with a one liner:
from stable_baselines import PPO2model = PPO2('MlpPolicy', 'CartPole-v1').learn(10000)
Acme comes from DeepMind, probably the most well-known company working on RL in research. As such, it has been developed for building readable, efficient, research-oriented RL algorithms and contains implementations of several state-of-the-art agents such as D4PG, DQN, R2D2, R2D3 and more. Acme uses Tensorflow as backend and also some agent implementations use a combination of JAX and Tensorflow.
Acme was developed keeping in mind to make its code as re-usable as possible, so its design is modular and easy to customize. Its documentation is not abundant but enough to give you a nice introduction to the library and there are also some examples to get you started in Jupyter notebooks.
All of the frameworks listed here are solid options for any RL project; deciding which one to use depends on your preferences and what you want to do with it exactly. To visualize better each framework and its pros and cons, I’ve made the following visual summary:
Choices of RL algorithms: ☆☆☆Documentation: ☆☆☆Customization: ☆☆☆☆☆Maintenance: ☆Backend: Keras and Tensorflow 1.14.
Choices of RL algorithms: ☆☆☆Documentation: Not availableCustomization: ☆☆☆☆☆Maintenance: ☆☆☆Backend: Keras and Tensorflow 2.1.0.
Choices of RL algorithms: ☆☆☆Documentation: ☆☆Customization: ☆☆Maintenance: ☆☆☆Backend: Tensorflow 1.14.
Choices of RL algorithms: ☆☆☆☆Documentation: ☆☆☆☆☆Customization: ☆☆☆Maintained: ☆☆☆☆☆Backend: Tensorflow 1.14.
Choices of RL algorithms: ☆☆☆☆Documentation: ☆☆☆Customization: ☆☆☆☆Maintenance: ☆☆☆☆☆Backend: Tensorflow v2+ and JAX
If you have already decided on what framework to use, all you need now is an environment. You can start using OpenAI Gym, which is already used in most examples of these frameworks, but if you want to try RL on other tasks such as Trading stocks, networking or producing recommendations, you can find a comprehensible list of ready-to-use environments here:
medium.com
If you know about any other good RL framework, please let me know in responses below! Thanks for reading! :)
|
[
{
"code": null,
"e": 446,
"s": 171,
"text": "There are lots of standard libraries for supervised and unsupervised machine learning like Scikit-learn, XGBoost or even Tensorflow, that can get you started in no time and you can find log nads of support online. Sadly, for Reinforcement Learning (RL) this is not the case."
},
{
"code": null,
"e": 867,
"s": 446,
"text": "It is not that there are no frameworks, as a matter of fact, there are many frameworks for RL out there. The problem is that there is no standard yet, and so finding support online for starting, fixing a problem or customizing a solution is not easily found. This is probably caused by the fact that, while RL is a very popular research topic, it is still in its early days of being implemented and used in the industry."
},
{
"code": null,
"e": 1258,
"s": 867,
"text": "But this doesn’t mean there are no great frameworks out there that can help you start and use RL for solving any problem you like. I have made a list here of some frameworks I have come to know and use along time, with their benefits and cons. I hope this gives you a quick overview about some of the RL frameworks currently available, so you can choose the one that better fits your needs."
},
{
"code": null,
"e": 1886,
"s": 1258,
"text": "I have to admit from the whole list, this is my favorite. I believe it is by far the simplest to understand code implementation of several RL algorithms including Deep Q Learning (DQN), Double DQN, Deep Deterministic Policy Gradient (DDPG), Continuous DQN (CDQN or NAF), Cross-Entropy Method (CEM), Dueling DQN) and SARSA. When I say “simplest to understand code” I refer not to use, but to customize it and utilize it as a building block for your project*. The Keras-RL github also contains some examples that you can use to get started in no time. It uses Keras of course, and you can use it along with Tensorflow or PyTorch."
},
{
"code": null,
"e": 2072,
"s": 1886,
"text": "Unfortunately, Keras-RL has not been well-maintained for a while already and its official documentation is not the best. This has given light to a fork of this project called Keras-RL2."
},
{
"code": null,
"e": 2254,
"s": 2072,
"text": "(*) What did I use this framework for? Well, I’m glad you asked — or was it me? I have used this framework to create a customized Tutored DQN agent, you can read more about it here."
},
{
"code": null,
"e": 2605,
"s": 2254,
"text": "Keras-RL2 is a fork from Keras-RL and as such it shares support for the same agents as Keras-RL2 and is easily customizable. The big change here is that Keras-RL2 is better maintained and uses Tensorflow 2.1.0. Unfortunately, there is no documentation for this library, even though the documentation for Keras-RL can be easily used for this fork too."
},
{
"code": null,
"e": 3037,
"s": 2605,
"text": "OpenAI Baselines is a set of high-quality implementations of RL algorithms by OpenAI, one of the leading companies in research and development of AI and in particular RL. It was conceived so researchers could compare their RL algorithms easily, using as a baseline the state-of-the-art implementations from OpenAI — thus the name. The framework contains implementations of many popular agents such as A2C, DDPG, DQN, PPO2 and TRPO."
},
{
"code": null,
"e": 3426,
"s": 3037,
"text": "On the downside, OpenAI Baselines is not well documented, even though there are lots of useful comments on the code. In addition, since it was developed to be used as a baseline and not as a building block, the code is not so friendly if you want to customize or modify some of the agents for your projects. In fact, the next framework is a fork from this and solves most of these issues."
},
{
"code": null,
"e": 3604,
"s": 3426,
"text": "Stable Baselines is a fork of OpenAI Baselines, with a major structural refactoring and code cleanups. The changes listed in their official documentation site are the following:"
},
{
"code": null,
"e": 3641,
"s": 3604,
"text": "Unified structure for all algorithms"
},
{
"code": null,
"e": 3677,
"s": 3641,
"text": "PEP8 compliant (unified code style)"
},
{
"code": null,
"e": 3710,
"s": 3677,
"text": "Documented functions and classes"
},
{
"code": null,
"e": 3742,
"s": 3710,
"text": "More tests & more code coverage"
},
{
"code": null,
"e": 3820,
"s": 3742,
"text": "Additional algorithms: SAC and TD3 (+ HER support for DQN, DDPG, SAC and TD3)"
},
{
"code": null,
"e": 4020,
"s": 3820,
"text": "I have personally used Stable Baselines in the past and I can confirm it is really well documented and easy to use. It is even possible to train an agent for OpenAI Gym environments with a one liner:"
},
{
"code": null,
"e": 4107,
"s": 4020,
"text": "from stable_baselines import PPO2model = PPO2('MlpPolicy', 'CartPole-v1').learn(10000)"
},
{
"code": null,
"e": 4507,
"s": 4107,
"text": "Acme comes from DeepMind, probably the most well-known company working on RL in research. As such, it has been developed for building readable, efficient, research-oriented RL algorithms and contains implementations of several state-of-the-art agents such as D4PG, DQN, R2D2, R2D3 and more. Acme uses Tensorflow as backend and also some agent implementations use a combination of JAX and Tensorflow."
},
{
"code": null,
"e": 4799,
"s": 4507,
"text": "Acme was developed keeping in mind to make its code as re-usable as possible, so its design is modular and easy to customize. Its documentation is not abundant but enough to give you a nice introduction to the library and there are also some examples to get you started in Jupyter notebooks."
},
{
"code": null,
"e": 5064,
"s": 4799,
"text": "All of the frameworks listed here are solid options for any RL project; deciding which one to use depends on your preferences and what you want to do with it exactly. To visualize better each framework and its pros and cons, I’ve made the following visual summary:"
},
{
"code": null,
"e": 5181,
"s": 5064,
"text": "Choices of RL algorithms: ☆☆☆Documentation: ☆☆☆Customization: ☆☆☆☆☆Maintenance: ☆Backend: Keras and Tensorflow 1.14."
},
{
"code": null,
"e": 5311,
"s": 5181,
"text": "Choices of RL algorithms: ☆☆☆Documentation: Not availableCustomization: ☆☆☆☆☆Maintenance: ☆☆☆Backend: Keras and Tensorflow 2.1.0."
},
{
"code": null,
"e": 5416,
"s": 5311,
"text": "Choices of RL algorithms: ☆☆☆Documentation: ☆☆Customization: ☆☆Maintenance: ☆☆☆Backend: Tensorflow 1.14."
},
{
"code": null,
"e": 5527,
"s": 5416,
"text": "Choices of RL algorithms: ☆☆☆☆Documentation: ☆☆☆☆☆Customization: ☆☆☆Maintained: ☆☆☆☆☆Backend: Tensorflow 1.14."
},
{
"code": null,
"e": 5644,
"s": 5527,
"text": "Choices of RL algorithms: ☆☆☆☆Documentation: ☆☆☆Customization: ☆☆☆☆Maintenance: ☆☆☆☆☆Backend: Tensorflow v2+ and JAX"
},
{
"code": null,
"e": 6002,
"s": 5644,
"text": "If you have already decided on what framework to use, all you need now is an environment. You can start using OpenAI Gym, which is already used in most examples of these frameworks, but if you want to try RL on other tasks such as Trading stocks, networking or producing recommendations, you can find a comprehensible list of ready-to-use environments here:"
},
{
"code": null,
"e": 6013,
"s": 6002,
"text": "medium.com"
}
] |
How to select Python Tuple/Dictionary Values for a given Index?
|
Items in tuple are indexed. Slice operator allows item of certain index to be accessed
>>> T1=(12, "Ravi", "B.Com FY", 78.50)
>>> print (T1[2])
B.Com FY
Items in dictionary are not indexed. Value associated with a certain key is obtained by putting in square bracket. The get() method of dictionary also returns associated value.
>>> D1={"Rollno":12, "class":"B.com FY", "precentage":78.50}
>>> print (D1['class'])
B.com FY
>>> print (D1.get('class'))
B.com FY
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "Items in tuple are indexed. Slice operator allows item of certain index to be accessed"
},
{
"code": null,
"e": 1215,
"s": 1149,
"text": ">>> T1=(12, \"Ravi\", \"B.Com FY\", 78.50)\n>>> print (T1[2])\nB.Com FY"
},
{
"code": null,
"e": 1392,
"s": 1215,
"text": "Items in dictionary are not indexed. Value associated with a certain key is obtained by putting in square bracket. The get() method of dictionary also returns associated value."
},
{
"code": null,
"e": 1523,
"s": 1392,
"text": ">>> D1={\"Rollno\":12, \"class\":\"B.com FY\", \"precentage\":78.50}\n>>> print (D1['class'])\nB.com FY\n>>> print (D1.get('class'))\nB.com FY"
}
] |
How to check if a JavaScript function is defined?
|
To check if a JavaScript function is defined or not, checks it with “undefined”.
You can try to run the following example to check for a function is defined or not in JavaScript −
<!DOCTYPE html>
<html>
<body>
<script>
function display() {
alert("Hello World!");
}
if ( typeof(display) === 'undefined') {
document.write('undefined');
} else {
document.write("Function is defined");
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "To check if a JavaScript function is defined or not, checks it with “undefined”."
},
{
"code": null,
"e": 1242,
"s": 1143,
"text": "You can try to run the following example to check for a function is defined or not in JavaScript −"
},
{
"code": null,
"e": 1572,
"s": 1242,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n function display() {\n alert(\"Hello World!\");\n }\n if ( typeof(display) === 'undefined') {\n document.write('undefined');\n } else {\n document.write(\"Function is defined\");\n }\n </script>\n </body>\n</html>"
}
] |
How to restart MsSQL server on Linux | Start MsSQL | Stop MsSQL Linux
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Here we will see how to restart MsSQL server on Linux machine.
MsSQL is a very commonly used database server, at times due to the many reasons you may need to stop/start/restart the server and even look for the status whether it is running or not?
Let’s see how to accomplish these tasks on a Linux machine.
We can get the status of MsSQL server using systemctl command. systemctl command is used to examine and control the state of “systemd” system and service manager.
$systemctl status mssql-server
systemctl status mssql-server
● mssql-server.service - Microsoft SQL Server Database Engine
Loaded: loaded (/usr/lib/systemd/system/mssql-server.service; enabled; vendor preset: disabled)
Active: active (running) since Tue 2020-03-31 12:55:05 BST; 1 weeks 0 days ago
Docs: https://docs.microsoft.com/en-us/sql/linux
Main PID: 212021 (sqlservr)
CGroup: /system.slice/mssql-server.service
├─212021 /opt/mssql/bin/sqlservr
└─212043 /opt/mssql/bin/sqlservr
As you can on the above output, the Microsoft SQL Server is running on my Linux machine. Let’s restart the running MsSQL server now.
To stop/start the MsSQL server you need sudo access. Let’s run the below systemctl command with sudo to stop the MsSQL server.
#Stop mssql server
$sudo systemctl stop mssql-server
#Start mssql server
$sudo systemctl Start mssql-server
You won’t see any success messages by running the above commands, that means your server has started successfully, you can confirm the status by using systemctl status mssql-server command as we have seen earlier.
Instead of stop and start, we can even restart the server directly using restart command like below.
# Restart mssql server
$sudo systemctl restart mssql-server
Happy Learning 🙂
Error response from daemon: Cannot kill container: XXX: Container XXX is not running
JQuery Stop Animations Example Tutorial
How to install Maven on Ubuntu 14.x
How to install Apache Kafka on Ubuntu 18.04
How to Install Kubernetes on Ubuntu 18.04
Linux vi commands list
How to set JAVA_HOME on Linux
Spring Boot Redis Cache Example – Redis Server
How to find Linux RHEL version ? OS and Kernel Version ?
How to install Java 11 on Ubuntu 18.04
Install Apache Solr on Windows 10
Ubuntu – How to set default Java version on Ubuntu
MicroServices Spring Boot Eureka Server Example
Setup/Install Redis Server on Windows 10
Spring Boot How to change the Tomcat to Jetty Server
Error response from daemon: Cannot kill container: XXX: Container XXX is not running
JQuery Stop Animations Example Tutorial
How to install Maven on Ubuntu 14.x
How to install Apache Kafka on Ubuntu 18.04
How to Install Kubernetes on Ubuntu 18.04
Linux vi commands list
How to set JAVA_HOME on Linux
Spring Boot Redis Cache Example – Redis Server
How to find Linux RHEL version ? OS and Kernel Version ?
How to install Java 11 on Ubuntu 18.04
Install Apache Solr on Windows 10
Ubuntu – How to set default Java version on Ubuntu
MicroServices Spring Boot Eureka Server Example
Setup/Install Redis Server on Windows 10
Spring Boot How to change the Tomcat to Jetty Server
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 461,
"s": 398,
"text": "Here we will see how to restart MsSQL server on Linux machine."
},
{
"code": null,
"e": 646,
"s": 461,
"text": "MsSQL is a very commonly used database server, at times due to the many reasons you may need to stop/start/restart the server and even look for the status whether it is running or not?"
},
{
"code": null,
"e": 706,
"s": 646,
"text": "Let’s see how to accomplish these tasks on a Linux machine."
},
{
"code": null,
"e": 869,
"s": 706,
"text": "We can get the status of MsSQL server using systemctl command. systemctl command is used to examine and control the state of “systemd” system and service manager."
},
{
"code": null,
"e": 1391,
"s": 869,
"text": "$systemctl status mssql-server\n\nsystemctl status mssql-server\n● mssql-server.service - Microsoft SQL Server Database Engine\n Loaded: loaded (/usr/lib/systemd/system/mssql-server.service; enabled; vendor preset: disabled)\n Active: active (running) since Tue 2020-03-31 12:55:05 BST; 1 weeks 0 days ago\n Docs: https://docs.microsoft.com/en-us/sql/linux\n Main PID: 212021 (sqlservr)\n CGroup: /system.slice/mssql-server.service\n ├─212021 /opt/mssql/bin/sqlservr\n └─212043 /opt/mssql/bin/sqlservr"
},
{
"code": null,
"e": 1524,
"s": 1391,
"text": "As you can on the above output, the Microsoft SQL Server is running on my Linux machine. Let’s restart the running MsSQL server now."
},
{
"code": null,
"e": 1651,
"s": 1524,
"text": "To stop/start the MsSQL server you need sudo access. Let’s run the below systemctl command with sudo to stop the MsSQL server."
},
{
"code": null,
"e": 1704,
"s": 1651,
"text": "#Stop mssql server\n$sudo systemctl stop mssql-server"
},
{
"code": null,
"e": 1759,
"s": 1704,
"text": "#Start mssql server\n$sudo systemctl Start mssql-server"
},
{
"code": null,
"e": 1973,
"s": 1759,
"text": "You won’t see any success messages by running the above commands, that means your server has started successfully, you can confirm the status by using systemctl status mssql-server command as we have seen earlier."
},
{
"code": null,
"e": 2074,
"s": 1973,
"text": "Instead of stop and start, we can even restart the server directly using restart command like below."
},
{
"code": null,
"e": 2135,
"s": 2074,
"text": "# Restart mssql server\n$sudo systemctl restart mssql-server\n"
},
{
"code": null,
"e": 2152,
"s": 2135,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2824,
"s": 2152,
"text": "\nError response from daemon: Cannot kill container: XXX: Container XXX is not running\nJQuery Stop Animations Example Tutorial\nHow to install Maven on Ubuntu 14.x\nHow to install Apache Kafka on Ubuntu 18.04\nHow to Install Kubernetes on Ubuntu 18.04\nLinux vi commands list\nHow to set JAVA_HOME on Linux\nSpring Boot Redis Cache Example – Redis Server\nHow to find Linux RHEL version ? OS and Kernel Version ?\nHow to install Java 11 on Ubuntu 18.04\nInstall Apache Solr on Windows 10\nUbuntu – How to set default Java version on Ubuntu\nMicroServices Spring Boot Eureka Server Example\nSetup/Install Redis Server on Windows 10\nSpring Boot How to change the Tomcat to Jetty Server\n"
},
{
"code": null,
"e": 2909,
"s": 2824,
"text": "Error response from daemon: Cannot kill container: XXX: Container XXX is not running"
},
{
"code": null,
"e": 2949,
"s": 2909,
"text": "JQuery Stop Animations Example Tutorial"
},
{
"code": null,
"e": 2985,
"s": 2949,
"text": "How to install Maven on Ubuntu 14.x"
},
{
"code": null,
"e": 3029,
"s": 2985,
"text": "How to install Apache Kafka on Ubuntu 18.04"
},
{
"code": null,
"e": 3071,
"s": 3029,
"text": "How to Install Kubernetes on Ubuntu 18.04"
},
{
"code": null,
"e": 3094,
"s": 3071,
"text": "Linux vi commands list"
},
{
"code": null,
"e": 3124,
"s": 3094,
"text": "How to set JAVA_HOME on Linux"
},
{
"code": null,
"e": 3171,
"s": 3124,
"text": "Spring Boot Redis Cache Example – Redis Server"
},
{
"code": null,
"e": 3228,
"s": 3171,
"text": "How to find Linux RHEL version ? OS and Kernel Version ?"
},
{
"code": null,
"e": 3267,
"s": 3228,
"text": "How to install Java 11 on Ubuntu 18.04"
},
{
"code": null,
"e": 3301,
"s": 3267,
"text": "Install Apache Solr on Windows 10"
},
{
"code": null,
"e": 3352,
"s": 3301,
"text": "Ubuntu – How to set default Java version on Ubuntu"
},
{
"code": null,
"e": 3400,
"s": 3352,
"text": "MicroServices Spring Boot Eureka Server Example"
},
{
"code": null,
"e": 3441,
"s": 3400,
"text": "Setup/Install Redis Server on Windows 10"
}
] |
Tryit Editor v3.7
|
Tryit: Style the first letter of a paragraph and let it float left
|
[] |
Directi Interview | Set 7 (Programming Questions) - GeeksforGeeks
|
01 Feb, 2022
An article containing recent Directi programming round questions in my campus placements and also those in my friends’ colleges.
1) You are given a string S. Each character of S is either ‘a’, or ‘b’. You wish to reverse exactly one sub-string of S such that the new string is lexicographically smaller than all the other strings that you can get by reversing exactly one sub-string. For example, given ‘abab’, you may choose to reverse the substring ‘ab’ that starts from index 2 (0-based). This gives you the string ‘abba’. But, if you choose the reverse the substring ‘ba’ starting from index 1, you will get ‘aabb’. There is no way of getting a smaller string, hence reversing the substring in the range [1, 2] is optimal.
Input First line contains a number T, the number of test cases. Each test case contains a single string S. The characters of the string will be from the set { a, b }.
Output For each test case, print two numbers separated by comma; for example “x,y” (without the quotes and without any additional whitespace). “x,y” describe the starting index (0-based) and ending index respectively of the substring that must be reversed in order to achieve the smallest lexicographical string. If there are multiple possible answers, print the one with the smallest ‘x’. If there are still multiple answers possible, print the one with the smallest ‘y’. Constraints 1 <= T <= 100 1 <= length of S <= 1000 Sample Input 5 abab abba bbaa aaaa babaabba Sample Output 1,2 1,3 0,3 0,0 0,4
2) Given two strings I and F, where I is the initial state and F is the final state. Each state will contain ‘a’,’b’ and only one empty slot represented by ‘_’. Your task is to move from the initial state to the final state with the minimum number of operation. Allowed operations are 1. You can swap empty character with any adjacent character. (For example ‘aba_ab’ can be converted into ‘ab_aab’ or ‘abaa_b’). 2. You can swap empty character with next to the adjacent character only if the adjacent character is different from next to the adjacent character. (For example ‘aba_ab’ can be converted into ‘a_abab’ or ‘ababa_’, but ‘ab_aab’ cannot be converted to ‘abaa_b’, because ‘a’ cannot jump over ‘a’). Input The first line contains single integer T – the number of test cases (less than 25). T-test cases follow. Each test case contains two string I and F in two different lines, where I is the initial state and F is the final state. I and F may be equal. Their length will always be equal. Their length will be at least 2. Their length will never be more than 20.
Output For each test case output a single line containing the minimum number of steps required to reach the final state from the initial state. You can assume it is always possible to reach the final state from the initial state. You can assume that no answer is more than 30. Example Input: 2 a_b ab_ aba_a _baaa
Output: 1 2
3) A probabilistic preorder traversal is generated for a binary search tree from the following pseudo-code
function preorder(u) {
if u is null then return
print u.label
r = either 0 or 1 with 50% probability
if r == 0
preorder(u.left_child)
preorder(u.right_child)
if r == 1
preorder(u.right_child)
preorder(u.left_child)
}
Given the preorder traversals of a binary search tree, you can always uniquely construct the binary search tree. Since, the inorder traversal of a binary search tree is, of course, the sorted list of labels. Given one of the probabilistic preorder traversals of some binary search tree, print the number of different probabilistic preorder traversals that the above algorithm might generate. See the explanation section for clarity.
Input The first line in the input is equal to N, the number of test cases. Then follows the description of N test cases. The first line in each test case is the integer N, the number of nodes in the binary search tree. On the next line, there are N integers – a probabilistic preorder traversal of the binary search tree. All the labels of the nodes in a test case will be distinct. The value of each label in a test case will be between 1 and N, inclusive. You may assume that the input will be a valid probabilistic preorder traversal of some binary search tree.
Output
For each test case, print a single number on a line by itself. This number should be the number of different probabilistic preorder traversals that exist for the binary search tee – including the one given in the test case. You may assume that the answer will always be less than or equal to 1,000,000,000. In fact, it is easy to see that the answer can never be more than 2^30 (read to-the-power). Constraints 1 < T <= 10000 1 <= N <= 30
Sample Input 3 3 2 1 3 3 1 2 3 5 2 4 3 5 1
Sample Output 2 1 4
4) You are given a large array of 10,000,000 bits. Each bit is initially 0. You perform several operations of the type “Flip all the bits between start_index and end_index, inclusive”. Given a sequence of several such operations, perform all the operations on the array. Finally, split the array into sets of 4 bits – first four, next four, then next four and so on. Each set can represent a hexadecimal integer. There will be exactly 2,500,000 hexadecimal integers. Calculate the frequency of each of the hexadecimal integers from ‘0’ to ‘f’ among the 2,500,000 integers, and print it. See Input / Output and explanation of Sample Input / Output for clarity. Input The first line of input contains an integer T (1 ? T ? 10), the number of test cases. Then follows the description of T test cases. You should assume that the array has exactly 10,000,000 bits and that the bits are all unset at the start of each test case. The first line of each test case contains an integer N (1 ? N ? 10,000), the number of operations performed. The next N lines contain two integers separated by a space, the start_index and end_index for the respective operation. Note that the flip operation is performed from start_index to end_index, inclusive. Also, the array is 1-indexed – meaning, the smallest index is 1 and the largest index is 10,000,000. Output For each test case, output 16 integers on a single line, separated by single space characters. The first integer should represent the number of times 0 occurs among the 2,500,000 hexadecimal integers created according to the problem statement. The second integer should represent the number of times 1 occurs among the 2,500,000 hexadecimal integers created according to the problem statement, and so on. Constraints 1 <= start_index <= end_index start_index <= end_index <= 10,000,000 Sample Input 2 2 1 4 9999997 10000000 2 3 6 5 8
Sample Output 2499998 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2499998 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0
5) You are given two strings, say A and B, of the same length, say N. You can swap A[i] and B[i] for all i between 1 and N, inclusive. You cannot swap two characters within A or within B. Also, you can only swap a character in A with the character at the same index in B, and with no other character. You can perform this operation zero or more times. You wish to modify the strings through the operations in such a way that the number of unique characters in the strings is small. In fact, if n(A) is the number of unique characters in A and n(B) is the number of unique characters in B; you wish to perform the operations such that max(n(A),n(B)) is as small as possible. Print the value of max(n(A),n(B)) after all the operations.
Input The first line of input contains T, the number of test cases. Then follows the description of T test cases. Each test case contains the number N on the first line. The next two lines of the test case contain two N letter strings, A and B respectively. The letters are lowercase english letters. Output Print a single line for each test case. Print the value of max(n(A),n(B)) after all the operations are performed such that the value is as small as possible. Constraints 1 <= T <= 100 1 <= length(A) <= 16 length(B) = length(A)
Sample Input 3 7 directi itcerid 5 ababa babab 5 abaaa baabb
Sample Output 4 1 2
6) Let’s define a string as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type, where x is the same letter. Tags can be nested into each other i.e., one opening and closing tag pair can be located inside another pair.
Let’s define the notion of a XML-text:
1) An empty string is a XML-text 2) If S is a XML-text, then ” S ” (quotes and spaces are for clarity) also is a XML-text, where a is any small Latin letter 3) If S1, S2 are XML-texts, then “S1 S2” (quotes and spaces are for clarity) also is a XML-text
You are given a string. You have to verify if the given string is a valid xml or not. Input First line contain T number of test cases For each test case: Only one line containing xml tagged string S. Output Print in one line a string TRUE if s is a valid xml FALSE if it is not. Constraints 0 < T <= 10 0 < length of S <= 10^5 Example Input: 2
Output: TRUE FALSE
7) In this problem we consider two stairways, A and B, which are parallel to each other. Both stairways, A and B, have N steps each where A[i], B[i] represent i-th step of A and B respectively. Each step has some amount of penalty associated and if you use that step you will be penalized by the same amount. After taking a few steps you will accumulate penalty of all of the steps you visited. You have a maximum jump length of K i.e., from A[i] you can jump forward to A[i+1] or A[i+2] ... or A[i+K] without using any steps in between. You can also jump across the stairways with an extra penalty P for changing stairways. For example from A[i] you can jump to B[i+1] or B[i+2] ... or B[i+K] with an additional penalty P along with the penalty of the step you visit. You can also jump from stairway B to stairway A and that too incurs an additional penalty P along with the penalty of the step you visit. Observe that from each step you can jump forward only. Your final penalty will be the penalty of all the steps you visited plus P times the number of times you crossed the stairways. You can start from A[1] or B[1] and should reach A[N] or B[N] minimizing the penalty accumulated on the way. Find the minimum penalty you will accumulate. Input The first line in the input is equal to T, the number of test cases. Then follows the description of T test cases. The first line in each test case has three integers N, the number of steps in both stairways, K, maximum jump length, P, the penalty for crossing the stairs. On the second line of each test case, there are N integers where ith integer represents the penalty of step A[i]. On the third line of each test, there are N integers where ith integer represents penalty of step B[i]. Output For each test case, output a single line containing the minimum penalty you can accumulate on your path starting from { A[1] or B[1] } and ending on { A[N] or B[N] }. Constraints 1 <= T <= 10
1 <= N <= 1000
0 <= P <= 1000
1 <= K <= N
0 <= A[i], B[i] <= 1000 Example Input: 6 4 1 0 1 2 3 4 1 2 3 4 4 1 0 1 2 3 4 4 3 2 1 4 2 0 1 2 3 4 4 3 2 1 4 1 10 1 2 3 4 4 3 2 1 4 2 10 1 2 3 4 4 3 2 1 5 1 50 0 0 102 104 0 101 103 0 0 105
Output: 10 6 4 10 7 100
8) In this problem we consider a rooted tree Tr with root r (not necessarily a binary tree). A dfs – depth first search – traversal of the tree Tr starting from root r, visits the nodes of Tr in a particular order. Let us call that order as dfs ordering. Observe that during a dfs traversal, from each node we have choices between which child to traverse first. These different choices lead to different dfs ordering. You have to find different ways a dfs can visit the nodes i.e., number of the different ordering of nodes possible by a dfs on Tr starting from root r.
Consider an example Tr with 3 nodes labeled 1, 2, 3 with 1 as root and with 2 and 3 as children of 1.
A dfs on this Tr can visit nodes in ordering (1, 2, 3) or (1, 3, 2). Hence there are 2 ways of dfs ordering.
See sample test cases for more examples Input The first line in the input is equal to T, the number of test cases. Then follows the description of T test cases. The first line in each test case is the integer N, the number of nodes in the tree Tr. Each node is labeled with a distinct integer between 1 and N inclusive. On the next line, there are N integers where ith integer represents parent label of node labeled i in rooted tree Tr. The value of each label in a test case will be between 1 and N, inclusive. The parent node of node labeled i will have label less than i. Node with label 1 is the root node r. The parent node of the root node will be given as 0 in test cases. Output For each test case, output a single line containing the number of different orderings possible by dfs on Tree Tr. Since this number can be huge output the value modulo 1,000,000,007.
Constraints 1 <= T <= 100 1 <= N <= 1000 0 <= A[i] < i
Example
Input: 6 2 0 1 3 0 1 1 4 0 1 1 1 3 0 1 2 4 0 1 1 2 5 0 1 1 2 2
Output: 1 2 6 1 2 4
9) Katrina is a super geek. She likes to optimize things. Suppose she is at position (0,0) of a two-dimensional grid containing ‘m’ rows and ‘n’ columns. She wants to reach the bottom right point of this grid traveling through as the minimum number of cells as possible. Each cell of the grid contains a positive integer, the positive integer defines the number of cells Katrina can jump either in the right or the downward direction when she reaches that cell. She cannot move left or up. You need to find the optimal path for Katrina so that starting from the top left position in the grid she reaches the bottom right position in the minimum number of hops. Input You are provided a template in which you have to implement one function minHops. The declaration of minHops looks like
C / C++ int minHops(int matrix[64][64], int m, int n)
Java statuc int minHops(int[][] matrix, int m, int n)
Output The function should return the minimum number of cells that should be touched to reach from top left corner of the grid to the bottom right corner (including touching both top left and the bottom right cells). Return 0 in case no path exists. Example Suppose the grid looks like this
2 4 2 5 3 8 1 1 1
Starting at A(0,0) contains ‘2’ so you can either go to (0,2) or (2,0). So following two paths exist to reach (2,2) from (0,0) (0,0) => (0,2) => (2,2) (0,0) => (2,0) => (2,1) => (2,2)
Hence the output for this test case should be 3
Example 2
5 3 8 2 6 4 2 1
There is no path from (0,0) to (1,3), so the output for this case should be 0
Example 3
2 3 2 1 4 3 2 5 8 2 1 1 2 2 1
Various paths in this case are (0,0) => (0,2) => (2,2) => (2,4) (0,0) => (2,0) => (2,1) => (2,2) => (2,4)
So output, in this case, should be 4
10) Consider NewYork city which has grid-like structure of houses. You are provided the city map in the form of a matrix. Each cell represents a building. From each building, you can go to the adjacent four buildings in four directions: east, west, north, south. Spiderman wants to rescue a victim which is on some building. You will be provided with the location of the victim and spiderman is situated at (1,1) building. But, there is a condition that spiderman can not jump between buildings if the difference in their heights is greater than some particular value. Find a way for spiderman to reach the victim by crossing the minimum number of buildings.
Input The input contains multiple test cases. First Line is an integer T, representing the number of test cases to follow.
The first line of each test case has 4 numbers – M, N, X, Y, D. Here MxN is the dimension of the city grid. (X, Y) is the location of the victim.
This is followed by M lines. Each line consists of N space-separated positive integers corresponding to building heights. D is the maximum difference between heights of buildings that spiderman can cross. Output One line for each test case containing a single integer, denoting the minimum number of buildings spiderman needs to cross. Return -1 if it’s not possible. Constraints Should contain all the constraints on the input data that you may have. Format it like: 1 <= T, M, N, X, Y <= 100 1 <= D <= 100000 Each building height will be less than 100000
Example Input: 3 3 3 3 3 2 1 2 3 6 9 4 7 8 5 3 3 3 3 1 1 8 3 9 5 6 7 2 4 3 3 3 3 1 1 6 7 2 5 8 3 4 9
Output: 3 -1 7
11) You are given a tree of N nodes. Each of the nodes will be numbered from 0 to N-1 and each node i is associated with a value vi. Assume the tree is rooted at node 0. A node y is said to be descendant of node x if x occurs in the path from node 0 to node y. A subtree rooted at node x is defined as a set of all nodes which are descendants of x (including x). A subtree is called univalued if the values of all the nodes in the subtree are equal. Given the tree and values associated with nodes in the tree, you are required to find the number of univalued subtrees in the tree. Input The first line contains an integer N which is the number of nodes in the tree. The next N lines contain N integers representing the values associated with each node i.e ith line contains the value associated with node i-1. The next N-1 lines give the information of edges in the tree. Each line contains two space-separated integers x and y denoting an edge between node x and node y. Output You have to print the number of univalued subtrees that are contained in the given tree. Constraints N<=30000 Example Input: 5 0 0 1 1 1 0 1 0 2 2 3 2 4 Output: 4
12) Directi organizes FNCS (Friday Night Chill Session) every once in a while (lots of FUN!). Directians comes and enjoy various events and then go out when they get tired and come back again when they are refreshed. For convenience, in/out of any person is recorded. At the end of the day, The organizer wonders what the maximum number of persons was during the event. So he asks for your help. He gives you the entry and exit time of each person like this:
Person Entry_time Exit_time
#1 6 10
#2 1 7
#3 1 4
#4 8 10
#5 6 10
The identity of the person does not matter. #1 and #4 may be the same person. In this case, the maximum number of persons present during the event at any time is 3. Your task is to read the entries and compute the max number of persons present during the course of the event. Input The input contains multiple test cases. First Line is an integer T, representing the number of test cases to follow. The first line of each test case is a number N, number of entry-exit records. This is followed by N lines. Each line consists of two space-separated integers corresponding to entry time and exit time of a person. Output One line for each test case containing a single integer, denoting the maximum number of persons present at the party at any time. Constraints 1 <= T <= 100 1 <= N <= 100 1 <= ENTRY_TIME < EXIT_TIME <= 10000000 The entry and exit time of the persons are guaranteed to be distinct
Example Input: 1 6 7 8 4 9 6 9 8 17 2 14 2 10
Output: 5
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
All Practice Problems for Directi !
Directi
Interview Experiences
Sorting
Directi
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
Amazon Interview Experience for SDE-1
Oracle Interview Experience | Set 69 (Application Engineer)
|
[
{
"code": null,
"e": 24837,
"s": 24809,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 24967,
"s": 24837,
"text": "An article containing recent Directi programming round questions in my campus placements and also those in my friends’ colleges. "
},
{
"code": null,
"e": 25566,
"s": 24967,
"text": "1) You are given a string S. Each character of S is either ‘a’, or ‘b’. You wish to reverse exactly one sub-string of S such that the new string is lexicographically smaller than all the other strings that you can get by reversing exactly one sub-string. For example, given ‘abab’, you may choose to reverse the substring ‘ab’ that starts from index 2 (0-based). This gives you the string ‘abba’. But, if you choose the reverse the substring ‘ba’ starting from index 1, you will get ‘aabb’. There is no way of getting a smaller string, hence reversing the substring in the range [1, 2] is optimal. "
},
{
"code": null,
"e": 25734,
"s": 25566,
"text": "Input First line contains a number T, the number of test cases. Each test case contains a single string S. The characters of the string will be from the set { a, b }. "
},
{
"code": null,
"e": 26337,
"s": 25734,
"text": "Output For each test case, print two numbers separated by comma; for example “x,y” (without the quotes and without any additional whitespace). “x,y” describe the starting index (0-based) and ending index respectively of the substring that must be reversed in order to achieve the smallest lexicographical string. If there are multiple possible answers, print the one with the smallest ‘x’. If there are still multiple answers possible, print the one with the smallest ‘y’. Constraints 1 <= T <= 100 1 <= length of S <= 1000 Sample Input 5 abab abba bbaa aaaa babaabba Sample Output 1,2 1,3 0,3 0,0 0,4 "
},
{
"code": null,
"e": 27411,
"s": 26337,
"text": "2) Given two strings I and F, where I is the initial state and F is the final state. Each state will contain ‘a’,’b’ and only one empty slot represented by ‘_’. Your task is to move from the initial state to the final state with the minimum number of operation. Allowed operations are 1. You can swap empty character with any adjacent character. (For example ‘aba_ab’ can be converted into ‘ab_aab’ or ‘abaa_b’). 2. You can swap empty character with next to the adjacent character only if the adjacent character is different from next to the adjacent character. (For example ‘aba_ab’ can be converted into ‘a_abab’ or ‘ababa_’, but ‘ab_aab’ cannot be converted to ‘abaa_b’, because ‘a’ cannot jump over ‘a’). Input The first line contains single integer T – the number of test cases (less than 25). T-test cases follow. Each test case contains two string I and F in two different lines, where I is the initial state and F is the final state. I and F may be equal. Their length will always be equal. Their length will be at least 2. Their length will never be more than 20. "
},
{
"code": null,
"e": 27726,
"s": 27411,
"text": "Output For each test case output a single line containing the minimum number of steps required to reach the final state from the initial state. You can assume it is always possible to reach the final state from the initial state. You can assume that no answer is more than 30. Example Input: 2 a_b ab_ aba_a _baaa "
},
{
"code": null,
"e": 27739,
"s": 27726,
"text": "Output: 1 2 "
},
{
"code": null,
"e": 27848,
"s": 27739,
"text": "3) A probabilistic preorder traversal is generated for a binary search tree from the following pseudo-code "
},
{
"code": null,
"e": 28117,
"s": 27848,
"text": "function preorder(u) {\n if u is null then return\n print u.label\n r = either 0 or 1 with 50% probability\n if r == 0\n preorder(u.left_child)\n preorder(u.right_child)\n if r == 1\n preorder(u.right_child)\n preorder(u.left_child)\n}"
},
{
"code": null,
"e": 28551,
"s": 28117,
"text": "Given the preorder traversals of a binary search tree, you can always uniquely construct the binary search tree. Since, the inorder traversal of a binary search tree is, of course, the sorted list of labels. Given one of the probabilistic preorder traversals of some binary search tree, print the number of different probabilistic preorder traversals that the above algorithm might generate. See the explanation section for clarity. "
},
{
"code": null,
"e": 29117,
"s": 28551,
"text": "Input The first line in the input is equal to N, the number of test cases. Then follows the description of N test cases. The first line in each test case is the integer N, the number of nodes in the binary search tree. On the next line, there are N integers – a probabilistic preorder traversal of the binary search tree. All the labels of the nodes in a test case will be distinct. The value of each label in a test case will be between 1 and N, inclusive. You may assume that the input will be a valid probabilistic preorder traversal of some binary search tree. "
},
{
"code": null,
"e": 29125,
"s": 29117,
"text": "Output "
},
{
"code": null,
"e": 29565,
"s": 29125,
"text": "For each test case, print a single number on a line by itself. This number should be the number of different probabilistic preorder traversals that exist for the binary search tee – including the one given in the test case. You may assume that the answer will always be less than or equal to 1,000,000,000. In fact, it is easy to see that the answer can never be more than 2^30 (read to-the-power). Constraints 1 < T <= 10000 1 <= N <= 30 "
},
{
"code": null,
"e": 29609,
"s": 29565,
"text": "Sample Input 3 3 2 1 3 3 1 2 3 5 2 4 3 5 1 "
},
{
"code": null,
"e": 29630,
"s": 29609,
"text": "Sample Output 2 1 4 "
},
{
"code": null,
"e": 31509,
"s": 29630,
"text": "4) You are given a large array of 10,000,000 bits. Each bit is initially 0. You perform several operations of the type “Flip all the bits between start_index and end_index, inclusive”. Given a sequence of several such operations, perform all the operations on the array. Finally, split the array into sets of 4 bits – first four, next four, then next four and so on. Each set can represent a hexadecimal integer. There will be exactly 2,500,000 hexadecimal integers. Calculate the frequency of each of the hexadecimal integers from ‘0’ to ‘f’ among the 2,500,000 integers, and print it. See Input / Output and explanation of Sample Input / Output for clarity. Input The first line of input contains an integer T (1 ? T ? 10), the number of test cases. Then follows the description of T test cases. You should assume that the array has exactly 10,000,000 bits and that the bits are all unset at the start of each test case. The first line of each test case contains an integer N (1 ? N ? 10,000), the number of operations performed. The next N lines contain two integers separated by a space, the start_index and end_index for the respective operation. Note that the flip operation is performed from start_index to end_index, inclusive. Also, the array is 1-indexed – meaning, the smallest index is 1 and the largest index is 10,000,000. Output For each test case, output 16 integers on a single line, separated by single space characters. The first integer should represent the number of times 0 occurs among the 2,500,000 hexadecimal integers created according to the problem statement. The second integer should represent the number of times 1 occurs among the 2,500,000 hexadecimal integers created according to the problem statement, and so on. Constraints 1 <= start_index <= end_index start_index <= end_index <= 10,000,000 Sample Input 2 2 1 4 9999997 10000000 2 3 6 5 8 "
},
{
"code": null,
"e": 31600,
"s": 31509,
"text": "Sample Output 2499998 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2499998 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 "
},
{
"code": null,
"e": 32335,
"s": 31600,
"text": "5) You are given two strings, say A and B, of the same length, say N. You can swap A[i] and B[i] for all i between 1 and N, inclusive. You cannot swap two characters within A or within B. Also, you can only swap a character in A with the character at the same index in B, and with no other character. You can perform this operation zero or more times. You wish to modify the strings through the operations in such a way that the number of unique characters in the strings is small. In fact, if n(A) is the number of unique characters in A and n(B) is the number of unique characters in B; you wish to perform the operations such that max(n(A),n(B)) is as small as possible. Print the value of max(n(A),n(B)) after all the operations. "
},
{
"code": null,
"e": 32871,
"s": 32335,
"text": "Input The first line of input contains T, the number of test cases. Then follows the description of T test cases. Each test case contains the number N on the first line. The next two lines of the test case contain two N letter strings, A and B respectively. The letters are lowercase english letters. Output Print a single line for each test case. Print the value of max(n(A),n(B)) after all the operations are performed such that the value is as small as possible. Constraints 1 <= T <= 100 1 <= length(A) <= 16 length(B) = length(A) "
},
{
"code": null,
"e": 32933,
"s": 32871,
"text": "Sample Input 3 7 directi itcerid 5 ababa babab 5 abaaa baabb "
},
{
"code": null,
"e": 32954,
"s": 32933,
"text": "Sample Output 4 1 2 "
},
{
"code": null,
"e": 33240,
"s": 32954,
"text": "6) Let’s define a string as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type, where x is the same letter. Tags can be nested into each other i.e., one opening and closing tag pair can be located inside another pair. "
},
{
"code": null,
"e": 33280,
"s": 33240,
"text": "Let’s define the notion of a XML-text: "
},
{
"code": null,
"e": 33534,
"s": 33280,
"text": "1) An empty string is a XML-text 2) If S is a XML-text, then ” S ” (quotes and spaces are for clarity) also is a XML-text, where a is any small Latin letter 3) If S1, S2 are XML-texts, then “S1 S2” (quotes and spaces are for clarity) also is a XML-text "
},
{
"code": null,
"e": 33879,
"s": 33534,
"text": "You are given a string. You have to verify if the given string is a valid xml or not. Input First line contain T number of test cases For each test case: Only one line containing xml tagged string S. Output Print in one line a string TRUE if s is a valid xml FALSE if it is not. Constraints 0 < T <= 10 0 < length of S <= 10^5 Example Input: 2 "
},
{
"code": null,
"e": 33899,
"s": 33879,
"text": "Output: TRUE FALSE "
},
{
"code": null,
"e": 35841,
"s": 33899,
"text": "7) In this problem we consider two stairways, A and B, which are parallel to each other. Both stairways, A and B, have N steps each where A[i], B[i] represent i-th step of A and B respectively. Each step has some amount of penalty associated and if you use that step you will be penalized by the same amount. After taking a few steps you will accumulate penalty of all of the steps you visited. You have a maximum jump length of K i.e., from A[i] you can jump forward to A[i+1] or A[i+2] ... or A[i+K] without using any steps in between. You can also jump across the stairways with an extra penalty P for changing stairways. For example from A[i] you can jump to B[i+1] or B[i+2] ... or B[i+K] with an additional penalty P along with the penalty of the step you visit. You can also jump from stairway B to stairway A and that too incurs an additional penalty P along with the penalty of the step you visit. Observe that from each step you can jump forward only. Your final penalty will be the penalty of all the steps you visited plus P times the number of times you crossed the stairways. You can start from A[1] or B[1] and should reach A[N] or B[N] minimizing the penalty accumulated on the way. Find the minimum penalty you will accumulate. Input The first line in the input is equal to T, the number of test cases. Then follows the description of T test cases. The first line in each test case has three integers N, the number of steps in both stairways, K, maximum jump length, P, the penalty for crossing the stairs. On the second line of each test case, there are N integers where ith integer represents the penalty of step A[i]. On the third line of each test, there are N integers where ith integer represents penalty of step B[i]. Output For each test case, output a single line containing the minimum penalty you can accumulate on your path starting from { A[1] or B[1] } and ending on { A[N] or B[N] }. Constraints 1 <= T <= 10 "
},
{
"code": null,
"e": 35857,
"s": 35841,
"text": "1 <= N <= 1000 "
},
{
"code": null,
"e": 35873,
"s": 35857,
"text": "0 <= P <= 1000 "
},
{
"code": null,
"e": 35886,
"s": 35873,
"text": "1 <= K <= N "
},
{
"code": null,
"e": 36077,
"s": 35886,
"text": "0 <= A[i], B[i] <= 1000 Example Input: 6 4 1 0 1 2 3 4 1 2 3 4 4 1 0 1 2 3 4 4 3 2 1 4 2 0 1 2 3 4 4 3 2 1 4 1 10 1 2 3 4 4 3 2 1 4 2 10 1 2 3 4 4 3 2 1 5 1 50 0 0 102 104 0 101 103 0 0 105 "
},
{
"code": null,
"e": 36102,
"s": 36077,
"text": "Output: 10 6 4 10 7 100 "
},
{
"code": null,
"e": 36673,
"s": 36102,
"text": "8) In this problem we consider a rooted tree Tr with root r (not necessarily a binary tree). A dfs – depth first search – traversal of the tree Tr starting from root r, visits the nodes of Tr in a particular order. Let us call that order as dfs ordering. Observe that during a dfs traversal, from each node we have choices between which child to traverse first. These different choices lead to different dfs ordering. You have to find different ways a dfs can visit the nodes i.e., number of the different ordering of nodes possible by a dfs on Tr starting from root r. "
},
{
"code": null,
"e": 36776,
"s": 36673,
"text": "Consider an example Tr with 3 nodes labeled 1, 2, 3 with 1 as root and with 2 and 3 as children of 1. "
},
{
"code": null,
"e": 36886,
"s": 36776,
"text": "A dfs on this Tr can visit nodes in ordering (1, 2, 3) or (1, 3, 2). Hence there are 2 ways of dfs ordering. "
},
{
"code": null,
"e": 37758,
"s": 36886,
"text": "See sample test cases for more examples Input The first line in the input is equal to T, the number of test cases. Then follows the description of T test cases. The first line in each test case is the integer N, the number of nodes in the tree Tr. Each node is labeled with a distinct integer between 1 and N inclusive. On the next line, there are N integers where ith integer represents parent label of node labeled i in rooted tree Tr. The value of each label in a test case will be between 1 and N, inclusive. The parent node of node labeled i will have label less than i. Node with label 1 is the root node r. The parent node of the root node will be given as 0 in test cases. Output For each test case, output a single line containing the number of different orderings possible by dfs on Tree Tr. Since this number can be huge output the value modulo 1,000,000,007. "
},
{
"code": null,
"e": 37815,
"s": 37758,
"text": "Constraints 1 <= T <= 100 1 <= N <= 1000 0 <= A[i] < i "
},
{
"code": null,
"e": 37824,
"s": 37815,
"text": "Example "
},
{
"code": null,
"e": 37888,
"s": 37824,
"text": "Input: 6 2 0 1 3 0 1 1 4 0 1 1 1 3 0 1 2 4 0 1 1 2 5 0 1 1 2 2 "
},
{
"code": null,
"e": 37909,
"s": 37888,
"text": "Output: 1 2 6 1 2 4 "
},
{
"code": null,
"e": 38696,
"s": 37909,
"text": "9) Katrina is a super geek. She likes to optimize things. Suppose she is at position (0,0) of a two-dimensional grid containing ‘m’ rows and ‘n’ columns. She wants to reach the bottom right point of this grid traveling through as the minimum number of cells as possible. Each cell of the grid contains a positive integer, the positive integer defines the number of cells Katrina can jump either in the right or the downward direction when she reaches that cell. She cannot move left or up. You need to find the optimal path for Katrina so that starting from the top left position in the grid she reaches the bottom right position in the minimum number of hops. Input You are provided a template in which you have to implement one function minHops. The declaration of minHops looks like "
},
{
"code": null,
"e": 38751,
"s": 38696,
"text": "C / C++ int minHops(int matrix[64][64], int m, int n) "
},
{
"code": null,
"e": 38806,
"s": 38751,
"text": "Java statuc int minHops(int[][] matrix, int m, int n) "
},
{
"code": null,
"e": 39098,
"s": 38806,
"text": "Output The function should return the minimum number of cells that should be touched to reach from top left corner of the grid to the bottom right corner (including touching both top left and the bottom right cells). Return 0 in case no path exists. Example Suppose the grid looks like this "
},
{
"code": null,
"e": 39117,
"s": 39098,
"text": "2 4 2 5 3 8 1 1 1 "
},
{
"code": null,
"e": 39302,
"s": 39117,
"text": "Starting at A(0,0) contains ‘2’ so you can either go to (0,2) or (2,0). So following two paths exist to reach (2,2) from (0,0) (0,0) => (0,2) => (2,2) (0,0) => (2,0) => (2,1) => (2,2) "
},
{
"code": null,
"e": 39351,
"s": 39302,
"text": "Hence the output for this test case should be 3 "
},
{
"code": null,
"e": 39362,
"s": 39351,
"text": "Example 2 "
},
{
"code": null,
"e": 39379,
"s": 39362,
"text": "5 3 8 2 6 4 2 1 "
},
{
"code": null,
"e": 39458,
"s": 39379,
"text": "There is no path from (0,0) to (1,3), so the output for this case should be 0 "
},
{
"code": null,
"e": 39469,
"s": 39458,
"text": "Example 3 "
},
{
"code": null,
"e": 39500,
"s": 39469,
"text": "2 3 2 1 4 3 2 5 8 2 1 1 2 2 1 "
},
{
"code": null,
"e": 39607,
"s": 39500,
"text": "Various paths in this case are (0,0) => (0,2) => (2,2) => (2,4) (0,0) => (2,0) => (2,1) => (2,2) => (2,4) "
},
{
"code": null,
"e": 39645,
"s": 39607,
"text": "So output, in this case, should be 4 "
},
{
"code": null,
"e": 40305,
"s": 39645,
"text": "10) Consider NewYork city which has grid-like structure of houses. You are provided the city map in the form of a matrix. Each cell represents a building. From each building, you can go to the adjacent four buildings in four directions: east, west, north, south. Spiderman wants to rescue a victim which is on some building. You will be provided with the location of the victim and spiderman is situated at (1,1) building. But, there is a condition that spiderman can not jump between buildings if the difference in their heights is greater than some particular value. Find a way for spiderman to reach the victim by crossing the minimum number of buildings. "
},
{
"code": null,
"e": 40429,
"s": 40305,
"text": "Input The input contains multiple test cases. First Line is an integer T, representing the number of test cases to follow. "
},
{
"code": null,
"e": 40576,
"s": 40429,
"text": "The first line of each test case has 4 numbers – M, N, X, Y, D. Here MxN is the dimension of the city grid. (X, Y) is the location of the victim. "
},
{
"code": null,
"e": 41134,
"s": 40576,
"text": "This is followed by M lines. Each line consists of N space-separated positive integers corresponding to building heights. D is the maximum difference between heights of buildings that spiderman can cross. Output One line for each test case containing a single integer, denoting the minimum number of buildings spiderman needs to cross. Return -1 if it’s not possible. Constraints Should contain all the constraints on the input data that you may have. Format it like: 1 <= T, M, N, X, Y <= 100 1 <= D <= 100000 Each building height will be less than 100000 "
},
{
"code": null,
"e": 41236,
"s": 41134,
"text": "Example Input: 3 3 3 3 3 2 1 2 3 6 9 4 7 8 5 3 3 3 3 1 1 8 3 9 5 6 7 2 4 3 3 3 3 1 1 6 7 2 5 8 3 4 9 "
},
{
"code": null,
"e": 41252,
"s": 41236,
"text": "Output: 3 -1 7 "
},
{
"code": null,
"e": 42396,
"s": 41252,
"text": "11) You are given a tree of N nodes. Each of the nodes will be numbered from 0 to N-1 and each node i is associated with a value vi. Assume the tree is rooted at node 0. A node y is said to be descendant of node x if x occurs in the path from node 0 to node y. A subtree rooted at node x is defined as a set of all nodes which are descendants of x (including x). A subtree is called univalued if the values of all the nodes in the subtree are equal. Given the tree and values associated with nodes in the tree, you are required to find the number of univalued subtrees in the tree. Input The first line contains an integer N which is the number of nodes in the tree. The next N lines contain N integers representing the values associated with each node i.e ith line contains the value associated with node i-1. The next N-1 lines give the information of edges in the tree. Each line contains two space-separated integers x and y denoting an edge between node x and node y. Output You have to print the number of univalued subtrees that are contained in the given tree. Constraints N<=30000 Example Input: 5 0 0 1 1 1 0 1 0 2 2 3 2 4 Output: 4 "
},
{
"code": null,
"e": 42860,
"s": 42399,
"text": "12) Directi organizes FNCS (Friday Night Chill Session) every once in a while (lots of FUN!). Directians comes and enjoy various events and then go out when they get tired and come back again when they are refreshed. For convenience, in/out of any person is recorded. At the end of the day, The organizer wonders what the maximum number of persons was during the event. So he asks for your help. He gives you the entry and exit time of each person like this: "
},
{
"code": null,
"e": 43005,
"s": 42860,
"text": "Person Entry_time Exit_time\n#1 6 10\n#2 1 7\n#3 1 4 \n#4 8 10\n#5 6 10"
},
{
"code": null,
"e": 43904,
"s": 43005,
"text": "The identity of the person does not matter. #1 and #4 may be the same person. In this case, the maximum number of persons present during the event at any time is 3. Your task is to read the entries and compute the max number of persons present during the course of the event. Input The input contains multiple test cases. First Line is an integer T, representing the number of test cases to follow. The first line of each test case is a number N, number of entry-exit records. This is followed by N lines. Each line consists of two space-separated integers corresponding to entry time and exit time of a person. Output One line for each test case containing a single integer, denoting the maximum number of persons present at the party at any time. Constraints 1 <= T <= 100 1 <= N <= 100 1 <= ENTRY_TIME < EXIT_TIME <= 10000000 The entry and exit time of the persons are guaranteed to be distinct "
},
{
"code": null,
"e": 43951,
"s": 43904,
"text": "Example Input: 1 6 7 8 4 9 6 9 8 17 2 14 2 10 "
},
{
"code": null,
"e": 43962,
"s": 43951,
"text": "Output: 5 "
},
{
"code": null,
"e": 44188,
"s": 43965,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 44227,
"s": 44190,
"text": "All Practice Problems for Directi ! "
},
{
"code": null,
"e": 44239,
"s": 44231,
"text": "Directi"
},
{
"code": null,
"e": 44261,
"s": 44239,
"text": "Interview Experiences"
},
{
"code": null,
"e": 44269,
"s": 44261,
"text": "Sorting"
},
{
"code": null,
"e": 44277,
"s": 44269,
"text": "Directi"
},
{
"code": null,
"e": 44285,
"s": 44277,
"text": "Sorting"
},
{
"code": null,
"e": 44383,
"s": 44285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44392,
"s": 44383,
"text": "Comments"
},
{
"code": null,
"e": 44405,
"s": 44392,
"text": "Old Comments"
},
{
"code": null,
"e": 44464,
"s": 44405,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 44514,
"s": 44464,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 44586,
"s": 44514,
"text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022"
},
{
"code": null,
"e": 44624,
"s": 44586,
"text": "Amazon Interview Experience for SDE-1"
}
] |
Calculate difference between columns of R DataFrame - GeeksforGeeks
|
26 Jan, 2022
Generally, the difference between two columns can be calculated from a dataframe that contains some numeric data. In this article, we will discuss how the difference between columns can be calculated in the R programming language.
Approach
Create a dataframe and the columns should be of numeric or integer data type so that we can find the difference between them.
Extract required data from columns using the $ operator into separate variables. For example, we have two columns then extract individual columns into separate variables.
Then perform the minus operation for the difference between those columns.
Finally, print the result.
Example 1 :
R
# creating a dataframedf=data.frame(num=c(1,2,3,4),num1=c(5,4,3,2)) # Extracting column 1a=df$num # Extracting column 2b=df$num1 # printing dataframeprint(df) # printing difference among# two columnsprint(b-a)
Output :
Example 2 :
R
# creating a dataframe with some# numeric datadf=data.frame(num=c(1.9,2.9,3.4,5.6,9.8), num1=c(6.3,7.7,8.0,9.3,10.9))print(df) # extracting column 1 into a# variable called aa=df$num # extracting column 2 into a# variable called bb=df$num1 # printing the difference between# two columnsprint(b-a)
Output :
Example 3 :
R
# creating a dataframe with# some numeric datadf=data.frame(num=c(1,2,3,4,5), num1=c(6,7,8,9,10)) # extracting column 1 into a# variable called aa=df$num # extracting column 2 into a# variable called bb=df$num1 # printing the dataframeprint(df) # printing the difference# between two columnsprint(b-a)
Output :
surinderdawra388
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
|
[
{
"code": null,
"e": 24654,
"s": 24626,
"text": "\n26 Jan, 2022"
},
{
"code": null,
"e": 24885,
"s": 24654,
"text": "Generally, the difference between two columns can be calculated from a dataframe that contains some numeric data. In this article, we will discuss how the difference between columns can be calculated in the R programming language."
},
{
"code": null,
"e": 24894,
"s": 24885,
"text": "Approach"
},
{
"code": null,
"e": 25020,
"s": 24894,
"text": "Create a dataframe and the columns should be of numeric or integer data type so that we can find the difference between them."
},
{
"code": null,
"e": 25191,
"s": 25020,
"text": "Extract required data from columns using the $ operator into separate variables. For example, we have two columns then extract individual columns into separate variables."
},
{
"code": null,
"e": 25266,
"s": 25191,
"text": "Then perform the minus operation for the difference between those columns."
},
{
"code": null,
"e": 25293,
"s": 25266,
"text": "Finally, print the result."
},
{
"code": null,
"e": 25306,
"s": 25293,
"text": "Example 1 : "
},
{
"code": null,
"e": 25308,
"s": 25306,
"text": "R"
},
{
"code": "# creating a dataframedf=data.frame(num=c(1,2,3,4),num1=c(5,4,3,2)) # Extracting column 1a=df$num # Extracting column 2b=df$num1 # printing dataframeprint(df) # printing difference among# two columnsprint(b-a)",
"e": 25519,
"s": 25308,
"text": null
},
{
"code": null,
"e": 25528,
"s": 25519,
"text": "Output :"
},
{
"code": null,
"e": 25540,
"s": 25528,
"text": "Example 2 :"
},
{
"code": null,
"e": 25542,
"s": 25540,
"text": "R"
},
{
"code": "# creating a dataframe with some# numeric datadf=data.frame(num=c(1.9,2.9,3.4,5.6,9.8), num1=c(6.3,7.7,8.0,9.3,10.9))print(df) # extracting column 1 into a# variable called aa=df$num # extracting column 2 into a# variable called bb=df$num1 # printing the difference between# two columnsprint(b-a)",
"e": 25852,
"s": 25542,
"text": null
},
{
"code": null,
"e": 25861,
"s": 25852,
"text": "Output :"
},
{
"code": null,
"e": 25874,
"s": 25861,
"text": "Example 3 : "
},
{
"code": null,
"e": 25876,
"s": 25874,
"text": "R"
},
{
"code": "# creating a dataframe with# some numeric datadf=data.frame(num=c(1,2,3,4,5), num1=c(6,7,8,9,10)) # extracting column 1 into a# variable called aa=df$num # extracting column 2 into a# variable called bb=df$num1 # printing the dataframeprint(df) # printing the difference# between two columnsprint(b-a)",
"e": 26191,
"s": 25876,
"text": null
},
{
"code": null,
"e": 26200,
"s": 26191,
"text": "Output :"
},
{
"code": null,
"e": 26217,
"s": 26200,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26224,
"s": 26217,
"text": "Picked"
},
{
"code": null,
"e": 26245,
"s": 26224,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 26257,
"s": 26245,
"text": "R-DataFrame"
},
{
"code": null,
"e": 26268,
"s": 26257,
"text": "R Language"
},
{
"code": null,
"e": 26279,
"s": 26268,
"text": "R Programs"
},
{
"code": null,
"e": 26377,
"s": 26279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26386,
"s": 26377,
"text": "Comments"
},
{
"code": null,
"e": 26399,
"s": 26386,
"text": "Old Comments"
},
{
"code": null,
"e": 26457,
"s": 26399,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 26489,
"s": 26457,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26541,
"s": 26489,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26593,
"s": 26541,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26637,
"s": 26593,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26695,
"s": 26637,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 26739,
"s": 26695,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26788,
"s": 26739,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 26846,
"s": 26788,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
Advanced Regression with Python | Towards Data Science
|
In a series of weekly articles, I will cover some important statistics topics with a twist.
The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more.
At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week.
Articles published so far:
Bernoulli and Binomial Random Variables with Python
From Binomial to Geometric and Poisson Random Variables with Python
Sampling Distribution of a Sample Proportion with Python
Confidence Intervals with Python
Significance Tests with Python
Two-sample Inference for the Difference Between Groups with Python
Inference for Categorical Data
Advanced Regression
Analysis of Variance — ANOVA
As usual, the code is available on my GitHub.
Imagine that you want to predict the salary of a Data Scientist based on the number of years he has been coding. To build this relationship, we can sample 20 random people from the population of Data Scientists and plot the relationship (notice that the salary unit is 10,000€). At the same time, we can calculate the line of best fit.
import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom scipy.stats import t, chi2salaries = [[4, 5.5, 3.5, 6, 7, 9, 3.4, 5.3, 4.3, 5.3, 6, 6.2, 6.5, 7, 7.1, 4.3, 5.2, 5, 5.7, 3.2]]yearsCoding = [[2, 5, 1, 4, 5, 10, 2, 2, 4, 3, 4, 6, 5, 6, 7, 4, 3, 4, 4, 3]]n = 20plt.scatter(yearsCoding[0], salaries[0])plt.xlabel('Years Coding')plt.ylabel('Salary');
The line of best fit can be calculated by minimizing the squared distance between the data points and the line. The equation for the regression line is the following:
where b is the slope, and a is the intercept of the regression line. Notice that by calculating this line for our data, we calculate the line of best fit for a single sample of 20 Data Scientists. We could calculate a different line of best fit for a different sample that we took from our population. This happens because we are estimating parameters for a population. If you could get the salaries and number of years coding for all the Data Scientists in the world to build your model, you would be estimating the true population parameters. In that case, we replace a and b with α and β:
Since we are using samples to estimate the population parameters, we can make inferences based on those samples. With that in mind, we know that b will not be exactly equal to β, but can we say that there is a positive linear relationship or a non-zero linear relationship between salaries and years of coding? As a matter of fact, we can do it by defining a confidence interval around this statistic. This way, we will have a good sense of where the true parameter might actually be. In previous articles, we saw how to compute such interval: we subtract/add the critical value t* multiplied by the standard error of b.
In the same way, we could define a hypothesis test for the slope parameter. One states that there is no relationship between the variables as a null hypothesis and, as the alternative, that there is a relationship between the variables (you could also be more specific and define the alternative hypothesis to be only positive or negative).
As in any other inference procedure, we must respect the conditions to ensure valid results. In this case, for the slope of linear regression, we must ensure that:
The data must be randomly generated;
The individual observations should be independent (or approximately independent — remember the 10% rule);
The relationship between the variables must be linear;
For any given x in the population, the distribution of y must be normal;
The variance should be constant for any given x.
We already defined our equation for the regression line; now, we need to define our cost function and a method to update our parameters. For our cost function, we will be using the Mean Squared Error:
To update our parameters, we will be using gradient descent. I will not cover the method in-depth; I only want to give some intuition. The first step is to compute the gradient of the cost function with respect to each parameter:
Then we update the parameters accordingly:
where α represents the learning rate.
def fit_lr(X, y, num_iter=1000, lr=0.01): n_samples = X.shape[0] slope = 0 intercept = 0 for _ in range(num_iter): y_predicted = np.dot(X, slope) + intercept ds = (1/n_samples) * np.dot(X.T, (y_predicted - y)) di = (1/n_samples) * np.sum(y_predicted - y) slope -= lr * ds intercept -= lr * di return (slope, intercept)slope, intercept = fit_lr(np.array(yearsCoding[0]), np.array(salaries[0]))plt.scatter(yearsCoding[0], salaries[0])plt.xlabel('Years Coding')plt.ylabel('Salary')plt.plot(yearsCoding[0],slope*np.array(yearsCoding[0]) + intercept, color='r');
print('Slope=' + str(slope))print('Intercept=' + str(intercept))Slope=0.7096702503648314Intercept=2.4147010493601404
What would be the salary of a Data Scientist that codes for 15 years?
slope * 15 + intercept13.059754804832611
It would be around 130,000€.
We can treat the slope ^b as a normally distributed random variable with a mean of b and a variance equal to σ2 divided by the sum of squares of X.
As we do not know the population variance, we use the sampling variance to calculate the Standard Error (SE):
We can describe the SE as the standard deviation of the sampling distribution of the slope of the regression line.
SS_xx = np.sum((np.array(yearsCoding[0]) - np.mean(np.array(yearsCoding[0])))**2)SS_xx79.20000000000002SE_b = (np.sqrt(np.sum((np.array(salaries[0])-(np.array(yearsCoding[0])*slope+intercept))**2)/(n-2))) / np.sqrt(SS_xx)SE_b0.08687984291368046
We can finally calculate the 95% confidence interval for the slope of our linear regression.
print('95% Confidence interval=[' + str(np.round(slope - t.ppf(0.975, df=n-2)*SE_b,2)) + ',' + str(np.round(slope + t.ppf(0.975, df=n-2)*SE_b,2)) + ']')95% Confidence interval=[0.53,0.89]
Recall that a 95% confidence interval means that the true slope is contained in our confidence intervals 95% of the time.
We can use this interval to test the following hypothesis at the α= 0.05 level of significance:
What can we conclude? Assuming that H_0 is true, we face the situation where β=0 does not overlap with the 95% interval, which happens with less than 5% probability. Thus, we reject H_0 and accept the suggested H_1. It states that there is some relationship (non-zero) between the number of years coding and the salary of a Data Scientist.
Now, suppose that the relationship between the salary of a Data Scientist and the number of years of coding is not linear. In this case, we see that it is closer to an exponential relationship. What happens if we try to fit a line to these data?
salaries = [[3.5, 7.5, 2.5, 7, 9, 40, 3.4, 4.3, 5.3, 5.3, 4, 12.2, 8.5, 10, 18.1, 4.3, 5.2, 5, 5.7, 5.2]]yearsCoding = [[2, 5, 1 , 4, 5, 10, 2 , 2 , 4, 3 , 4, 6 , 5 , 6 , 7 , 4 , 3 , 4, 4 , 3 ]]n = 20plt.scatter(yearsCoding[0], salaries[0])plt.xlabel('Years Coding')plt.ylabel('Salary');
slope, intercept = fit_lr(np.array(yearsCoding[0]), np.array(salaries[0]))plt.scatter(yearsCoding[0], salaries[0])plt.xlabel('Years Coding')plt.ylabel('Salary')plt.plot(yearsCoding[0],slope*np.array(yearsCoding[0]) + intercept, color='r');
print('Slope=' + str(slope))print('Intercept=' + str(intercept))Slope=3.35501894004377Intercept=-5.5729005963397205
We see that the line that we have fitted does not explain the data at all. We even get a negative salary for someone that just started coding, and we would heavily underestimate the salary of someone that codes for 10 years. We have two options here. The first is to fit an exponential line to the data. The problem with this approach is that we lose the tools we have been developing to fit and analyze a linear relationship between two variables. On the other hand, we can transform our data before fitting the regression line.
plt.scatter(yearsCoding[0], np.log(salaries[0]))plt.xlabel('Years Coding')plt.ylabel('ln(Salary)');
slope, intercept = fit_lr(np.array(yearsCoding[0]), np.log(np.array(salaries[0])))plt.scatter(yearsCoding[0], np.log(salaries[0]))plt.xlabel('Years Coding')plt.ylabel('ln(Salary)')plt.plot(yearsCoding[0],slope*np.array(yearsCoding[0]) + intercept, color='r');
print('Slope=' + str(slope))print('Intercept=' + str(intercept))Slope=0.3173211894646696Intercept=0.5195321580809141
With the transformation, we see that the line of best fit actually explains the relationship between the variable years of coding and the transformed variable salary. But notice that the relationship between the original variables is not linear but exponential.
What would be the salary of a Data Scientist that codes for 15 years in this scenario?
np.exp(slope * 15+intercept)196.24227641696947
It would be almost 2M€! Compare it with the result from the linear dataset that we used before.
This article covered how to solve a linear regression problem and then use our line of best fit to make inferences about our parameters. In this case, we focus on the slope parameter, using confidence intervals and hypothesis testing to evaluate the type of association between two variables of interest. Finally, we introduced the concept of transforming variables to deal with the fact that the data can have nonlinear patterns.
You will get the solutions in next week’s article.
Márcia collected data on the battery life and price of a random sample of Portable Computers. Based on the data presented below, what is the test statistic for the null hypothesis that the population slope is 0?Rui obtained a random sample of colleagues at work and noticed a positive linear relationship between their ages and the number of kilometers they said they walked yesterday. A 95% confidence interval for the slope of the regression line was (15.4, 155.2). Rui wants to use this interval to test H_0: β=0 vs. H_1: β ≠ 0 at the 5% significance level. Assume that all conditions for inference have been met. What should Rui conclude?
Márcia collected data on the battery life and price of a random sample of Portable Computers. Based on the data presented below, what is the test statistic for the null hypothesis that the population slope is 0?
Rui obtained a random sample of colleagues at work and noticed a positive linear relationship between their ages and the number of kilometers they said they walked yesterday. A 95% confidence interval for the slope of the regression line was (15.4, 155.2). Rui wants to use this interval to test H_0: β=0 vs. H_1: β ≠ 0 at the 5% significance level. Assume that all conditions for inference have been met. What should Rui conclude?
According to a distributor of surfboards, 66% of the boards are common, 25% are uncommon, and 9% are rare. José wondered if the rarity levels of the boards he and his friends owned followed this distribution, so he took a random sample of 500 boards and recorded their rarity levels. The results are presented in the table below. Carry out a goodness-of-fit test to determine if the distribution of rarity levels of surfboards José and his friends own disagrees with the claimed percentages.
According to a distributor of surfboards, 66% of the boards are common, 25% are uncommon, and 9% are rare. José wondered if the rarity levels of the boards he and his friends owned followed this distribution, so he took a random sample of 500 boards and recorded their rarity levels. The results are presented in the table below. Carry out a goodness-of-fit test to determine if the distribution of rarity levels of surfboards José and his friends own disagrees with the claimed percentages.
table = [['Cards', 345, 125, 30]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['Rarity level', 'Common', 'Uncommon', 'Rare']df = df.set_index('Rarity level')df
arr = df.to_numpy()arr = np.concatenate((arr, (np.sum(arr)*np.asarray([0.66, 0.25, 0.09])).reshape(1,-1)))chi_sq_statistic = np.sum((arr[0]-arr[1])**2/arr[1])chi_sq_statistic5.681818181818182print('P-value = ' + str(np.round(1-chi2.cdf(chi_sq_statistic, df =2), 4)))P-value = 0.0584if 1-chi2.cdf(chi_sq_statistic, df =2) < alpha: print('Reject H_0')else: print('Fail to reject H_0')Fail to reject H_0
|
[
{
"code": null,
"e": 264,
"s": 172,
"text": "In a series of weekly articles, I will cover some important statistics topics with a twist."
},
{
"code": null,
"e": 564,
"s": 264,
"text": "The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more."
},
{
"code": null,
"e": 706,
"s": 564,
"text": "At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week."
},
{
"code": null,
"e": 733,
"s": 706,
"text": "Articles published so far:"
},
{
"code": null,
"e": 785,
"s": 733,
"text": "Bernoulli and Binomial Random Variables with Python"
},
{
"code": null,
"e": 853,
"s": 785,
"text": "From Binomial to Geometric and Poisson Random Variables with Python"
},
{
"code": null,
"e": 910,
"s": 853,
"text": "Sampling Distribution of a Sample Proportion with Python"
},
{
"code": null,
"e": 943,
"s": 910,
"text": "Confidence Intervals with Python"
},
{
"code": null,
"e": 974,
"s": 943,
"text": "Significance Tests with Python"
},
{
"code": null,
"e": 1041,
"s": 974,
"text": "Two-sample Inference for the Difference Between Groups with Python"
},
{
"code": null,
"e": 1072,
"s": 1041,
"text": "Inference for Categorical Data"
},
{
"code": null,
"e": 1092,
"s": 1072,
"text": "Advanced Regression"
},
{
"code": null,
"e": 1121,
"s": 1092,
"text": "Analysis of Variance — ANOVA"
},
{
"code": null,
"e": 1167,
"s": 1121,
"text": "As usual, the code is available on my GitHub."
},
{
"code": null,
"e": 1503,
"s": 1167,
"text": "Imagine that you want to predict the salary of a Data Scientist based on the number of years he has been coding. To build this relationship, we can sample 20 random people from the population of Data Scientists and plot the relationship (notice that the salary unit is 10,000€). At the same time, we can calculate the line of best fit."
},
{
"code": null,
"e": 1872,
"s": 1503,
"text": "import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom scipy.stats import t, chi2salaries = [[4, 5.5, 3.5, 6, 7, 9, 3.4, 5.3, 4.3, 5.3, 6, 6.2, 6.5, 7, 7.1, 4.3, 5.2, 5, 5.7, 3.2]]yearsCoding = [[2, 5, 1, 4, 5, 10, 2, 2, 4, 3, 4, 6, 5, 6, 7, 4, 3, 4, 4, 3]]n = 20plt.scatter(yearsCoding[0], salaries[0])plt.xlabel('Years Coding')plt.ylabel('Salary');"
},
{
"code": null,
"e": 2039,
"s": 1872,
"text": "The line of best fit can be calculated by minimizing the squared distance between the data points and the line. The equation for the regression line is the following:"
},
{
"code": null,
"e": 2631,
"s": 2039,
"text": "where b is the slope, and a is the intercept of the regression line. Notice that by calculating this line for our data, we calculate the line of best fit for a single sample of 20 Data Scientists. We could calculate a different line of best fit for a different sample that we took from our population. This happens because we are estimating parameters for a population. If you could get the salaries and number of years coding for all the Data Scientists in the world to build your model, you would be estimating the true population parameters. In that case, we replace a and b with α and β:"
},
{
"code": null,
"e": 3252,
"s": 2631,
"text": "Since we are using samples to estimate the population parameters, we can make inferences based on those samples. With that in mind, we know that b will not be exactly equal to β, but can we say that there is a positive linear relationship or a non-zero linear relationship between salaries and years of coding? As a matter of fact, we can do it by defining a confidence interval around this statistic. This way, we will have a good sense of where the true parameter might actually be. In previous articles, we saw how to compute such interval: we subtract/add the critical value t* multiplied by the standard error of b."
},
{
"code": null,
"e": 3593,
"s": 3252,
"text": "In the same way, we could define a hypothesis test for the slope parameter. One states that there is no relationship between the variables as a null hypothesis and, as the alternative, that there is a relationship between the variables (you could also be more specific and define the alternative hypothesis to be only positive or negative)."
},
{
"code": null,
"e": 3757,
"s": 3593,
"text": "As in any other inference procedure, we must respect the conditions to ensure valid results. In this case, for the slope of linear regression, we must ensure that:"
},
{
"code": null,
"e": 3794,
"s": 3757,
"text": "The data must be randomly generated;"
},
{
"code": null,
"e": 3900,
"s": 3794,
"text": "The individual observations should be independent (or approximately independent — remember the 10% rule);"
},
{
"code": null,
"e": 3955,
"s": 3900,
"text": "The relationship between the variables must be linear;"
},
{
"code": null,
"e": 4028,
"s": 3955,
"text": "For any given x in the population, the distribution of y must be normal;"
},
{
"code": null,
"e": 4077,
"s": 4028,
"text": "The variance should be constant for any given x."
},
{
"code": null,
"e": 4278,
"s": 4077,
"text": "We already defined our equation for the regression line; now, we need to define our cost function and a method to update our parameters. For our cost function, we will be using the Mean Squared Error:"
},
{
"code": null,
"e": 4508,
"s": 4278,
"text": "To update our parameters, we will be using gradient descent. I will not cover the method in-depth; I only want to give some intuition. The first step is to compute the gradient of the cost function with respect to each parameter:"
},
{
"code": null,
"e": 4551,
"s": 4508,
"text": "Then we update the parameters accordingly:"
},
{
"code": null,
"e": 4589,
"s": 4551,
"text": "where α represents the learning rate."
},
{
"code": null,
"e": 5205,
"s": 4589,
"text": "def fit_lr(X, y, num_iter=1000, lr=0.01): n_samples = X.shape[0] slope = 0 intercept = 0 for _ in range(num_iter): y_predicted = np.dot(X, slope) + intercept ds = (1/n_samples) * np.dot(X.T, (y_predicted - y)) di = (1/n_samples) * np.sum(y_predicted - y) slope -= lr * ds intercept -= lr * di return (slope, intercept)slope, intercept = fit_lr(np.array(yearsCoding[0]), np.array(salaries[0]))plt.scatter(yearsCoding[0], salaries[0])plt.xlabel('Years Coding')plt.ylabel('Salary')plt.plot(yearsCoding[0],slope*np.array(yearsCoding[0]) + intercept, color='r');"
},
{
"code": null,
"e": 5322,
"s": 5205,
"text": "print('Slope=' + str(slope))print('Intercept=' + str(intercept))Slope=0.7096702503648314Intercept=2.4147010493601404"
},
{
"code": null,
"e": 5392,
"s": 5322,
"text": "What would be the salary of a Data Scientist that codes for 15 years?"
},
{
"code": null,
"e": 5433,
"s": 5392,
"text": "slope * 15 + intercept13.059754804832611"
},
{
"code": null,
"e": 5462,
"s": 5433,
"text": "It would be around 130,000€."
},
{
"code": null,
"e": 5610,
"s": 5462,
"text": "We can treat the slope ^b as a normally distributed random variable with a mean of b and a variance equal to σ2 divided by the sum of squares of X."
},
{
"code": null,
"e": 5720,
"s": 5610,
"text": "As we do not know the population variance, we use the sampling variance to calculate the Standard Error (SE):"
},
{
"code": null,
"e": 5835,
"s": 5720,
"text": "We can describe the SE as the standard deviation of the sampling distribution of the slope of the regression line."
},
{
"code": null,
"e": 6080,
"s": 5835,
"text": "SS_xx = np.sum((np.array(yearsCoding[0]) - np.mean(np.array(yearsCoding[0])))**2)SS_xx79.20000000000002SE_b = (np.sqrt(np.sum((np.array(salaries[0])-(np.array(yearsCoding[0])*slope+intercept))**2)/(n-2))) / np.sqrt(SS_xx)SE_b0.08687984291368046"
},
{
"code": null,
"e": 6173,
"s": 6080,
"text": "We can finally calculate the 95% confidence interval for the slope of our linear regression."
},
{
"code": null,
"e": 6361,
"s": 6173,
"text": "print('95% Confidence interval=[' + str(np.round(slope - t.ppf(0.975, df=n-2)*SE_b,2)) + ',' + str(np.round(slope + t.ppf(0.975, df=n-2)*SE_b,2)) + ']')95% Confidence interval=[0.53,0.89]"
},
{
"code": null,
"e": 6483,
"s": 6361,
"text": "Recall that a 95% confidence interval means that the true slope is contained in our confidence intervals 95% of the time."
},
{
"code": null,
"e": 6579,
"s": 6483,
"text": "We can use this interval to test the following hypothesis at the α= 0.05 level of significance:"
},
{
"code": null,
"e": 6919,
"s": 6579,
"text": "What can we conclude? Assuming that H_0 is true, we face the situation where β=0 does not overlap with the 95% interval, which happens with less than 5% probability. Thus, we reject H_0 and accept the suggested H_1. It states that there is some relationship (non-zero) between the number of years coding and the salary of a Data Scientist."
},
{
"code": null,
"e": 7165,
"s": 6919,
"text": "Now, suppose that the relationship between the salary of a Data Scientist and the number of years of coding is not linear. In this case, we see that it is closer to an exponential relationship. What happens if we try to fit a line to these data?"
},
{
"code": null,
"e": 7473,
"s": 7165,
"text": "salaries = [[3.5, 7.5, 2.5, 7, 9, 40, 3.4, 4.3, 5.3, 5.3, 4, 12.2, 8.5, 10, 18.1, 4.3, 5.2, 5, 5.7, 5.2]]yearsCoding = [[2, 5, 1 , 4, 5, 10, 2 , 2 , 4, 3 , 4, 6 , 5 , 6 , 7 , 4 , 3 , 4, 4 , 3 ]]n = 20plt.scatter(yearsCoding[0], salaries[0])plt.xlabel('Years Coding')plt.ylabel('Salary');"
},
{
"code": null,
"e": 7713,
"s": 7473,
"text": "slope, intercept = fit_lr(np.array(yearsCoding[0]), np.array(salaries[0]))plt.scatter(yearsCoding[0], salaries[0])plt.xlabel('Years Coding')plt.ylabel('Salary')plt.plot(yearsCoding[0],slope*np.array(yearsCoding[0]) + intercept, color='r');"
},
{
"code": null,
"e": 7829,
"s": 7713,
"text": "print('Slope=' + str(slope))print('Intercept=' + str(intercept))Slope=3.35501894004377Intercept=-5.5729005963397205"
},
{
"code": null,
"e": 8359,
"s": 7829,
"text": "We see that the line that we have fitted does not explain the data at all. We even get a negative salary for someone that just started coding, and we would heavily underestimate the salary of someone that codes for 10 years. We have two options here. The first is to fit an exponential line to the data. The problem with this approach is that we lose the tools we have been developing to fit and analyze a linear relationship between two variables. On the other hand, we can transform our data before fitting the regression line."
},
{
"code": null,
"e": 8459,
"s": 8359,
"text": "plt.scatter(yearsCoding[0], np.log(salaries[0]))plt.xlabel('Years Coding')plt.ylabel('ln(Salary)');"
},
{
"code": null,
"e": 8719,
"s": 8459,
"text": "slope, intercept = fit_lr(np.array(yearsCoding[0]), np.log(np.array(salaries[0])))plt.scatter(yearsCoding[0], np.log(salaries[0]))plt.xlabel('Years Coding')plt.ylabel('ln(Salary)')plt.plot(yearsCoding[0],slope*np.array(yearsCoding[0]) + intercept, color='r');"
},
{
"code": null,
"e": 8836,
"s": 8719,
"text": "print('Slope=' + str(slope))print('Intercept=' + str(intercept))Slope=0.3173211894646696Intercept=0.5195321580809141"
},
{
"code": null,
"e": 9098,
"s": 8836,
"text": "With the transformation, we see that the line of best fit actually explains the relationship between the variable years of coding and the transformed variable salary. But notice that the relationship between the original variables is not linear but exponential."
},
{
"code": null,
"e": 9185,
"s": 9098,
"text": "What would be the salary of a Data Scientist that codes for 15 years in this scenario?"
},
{
"code": null,
"e": 9232,
"s": 9185,
"text": "np.exp(slope * 15+intercept)196.24227641696947"
},
{
"code": null,
"e": 9328,
"s": 9232,
"text": "It would be almost 2M€! Compare it with the result from the linear dataset that we used before."
},
{
"code": null,
"e": 9759,
"s": 9328,
"text": "This article covered how to solve a linear regression problem and then use our line of best fit to make inferences about our parameters. In this case, we focus on the slope parameter, using confidence intervals and hypothesis testing to evaluate the type of association between two variables of interest. Finally, we introduced the concept of transforming variables to deal with the fact that the data can have nonlinear patterns."
},
{
"code": null,
"e": 9810,
"s": 9759,
"text": "You will get the solutions in next week’s article."
},
{
"code": null,
"e": 10455,
"s": 9810,
"text": "Márcia collected data on the battery life and price of a random sample of Portable Computers. Based on the data presented below, what is the test statistic for the null hypothesis that the population slope is 0?Rui obtained a random sample of colleagues at work and noticed a positive linear relationship between their ages and the number of kilometers they said they walked yesterday. A 95% confidence interval for the slope of the regression line was (15.4, 155.2). Rui wants to use this interval to test H_0: β=0 vs. H_1: β ≠ 0 at the 5% significance level. Assume that all conditions for inference have been met. What should Rui conclude?"
},
{
"code": null,
"e": 10668,
"s": 10455,
"text": "Márcia collected data on the battery life and price of a random sample of Portable Computers. Based on the data presented below, what is the test statistic for the null hypothesis that the population slope is 0?"
},
{
"code": null,
"e": 11101,
"s": 10668,
"text": "Rui obtained a random sample of colleagues at work and noticed a positive linear relationship between their ages and the number of kilometers they said they walked yesterday. A 95% confidence interval for the slope of the regression line was (15.4, 155.2). Rui wants to use this interval to test H_0: β=0 vs. H_1: β ≠ 0 at the 5% significance level. Assume that all conditions for inference have been met. What should Rui conclude?"
},
{
"code": null,
"e": 11595,
"s": 11101,
"text": "According to a distributor of surfboards, 66% of the boards are common, 25% are uncommon, and 9% are rare. José wondered if the rarity levels of the boards he and his friends owned followed this distribution, so he took a random sample of 500 boards and recorded their rarity levels. The results are presented in the table below. Carry out a goodness-of-fit test to determine if the distribution of rarity levels of surfboards José and his friends own disagrees with the claimed percentages."
},
{
"code": null,
"e": 12089,
"s": 11595,
"text": "According to a distributor of surfboards, 66% of the boards are common, 25% are uncommon, and 9% are rare. José wondered if the rarity levels of the boards he and his friends owned followed this distribution, so he took a random sample of 500 boards and recorded their rarity levels. The results are presented in the table below. Carry out a goodness-of-fit test to determine if the distribution of rarity levels of surfboards José and his friends own disagrees with the claimed percentages."
},
{
"code": null,
"e": 12253,
"s": 12089,
"text": "table = [['Cards', 345, 125, 30]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['Rarity level', 'Common', 'Uncommon', 'Rare']df = df.set_index('Rarity level')df"
}
] |
Check if value exists in a comma separated list in MySQL?
|
To check if value exists in a comma separated list, you can use FIND_IN_SET() function.
The syntax is as follows
SELECT *FROM yourTablename WHERE FIND_IN_SET(‘yourValue’,yourColumnName) > 0;
Let us first create a table. The query to create a table is as follows
mysql> create table existInCommaSeparatedList
- > (
- > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
- > Name varchar(200)
- > );
Query OK, 0 rows affected (0.68 sec)
Now you can insert some records in the table using insert command.
The query is as follows
mysql> insert into existInCommaSeparatedList(Name) values('John,Carol,Sam,Larry,Bob,David');
Query OK, 1 row affected (0.35 sec)
mysql> insert into existInCommaSeparatedList(Name) values('Maxwell,Chris,James');
Query OK, 1 row affected (0.14 sec)
mysql> insert into existInCommaSeparatedList(Name) values('Robert,Ramit');
Query OK, 1 row affected (0.34 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from existInCommaSeparatedList;
The following is the output
+----+--------------------------------+
| Id | Name |
+----+--------------------------------+
| 1 | John,Carol,Sam,Larry,Bob,David |
| 2 | Maxwell,Chris,James |
| 3 | Robert,Ramit |
+----+--------------------------------+
3 rows in set (0.00 sec)
Here is the query to check if value exists in a comma separated list. We are checking for the field with comma separated text “Robert”
mysql> SELECT *FROM existInCommaSeparatedList WHERE FIND_IN_SET('Robert',Name) > 0;
The following is the output
+----+--------------+
| Id | Name |
+----+--------------+
| 3 | Robert,Ramit |
+----+--------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "To check if value exists in a comma separated list, you can use FIND_IN_SET() function."
},
{
"code": null,
"e": 1175,
"s": 1150,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1253,
"s": 1175,
"text": "SELECT *FROM yourTablename WHERE FIND_IN_SET(‘yourValue’,yourColumnName) > 0;"
},
{
"code": null,
"e": 1324,
"s": 1253,
"text": "Let us first create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1502,
"s": 1324,
"text": "mysql> create table existInCommaSeparatedList\n - > (\n - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > Name varchar(200)\n - > );\nQuery OK, 0 rows affected (0.68 sec)"
},
{
"code": null,
"e": 1569,
"s": 1502,
"text": "Now you can insert some records in the table using insert command."
},
{
"code": null,
"e": 1593,
"s": 1569,
"text": "The query is as follows"
},
{
"code": null,
"e": 1951,
"s": 1593,
"text": "mysql> insert into existInCommaSeparatedList(Name) values('John,Carol,Sam,Larry,Bob,David');\nQuery OK, 1 row affected (0.35 sec)\nmysql> insert into existInCommaSeparatedList(Name) values('Maxwell,Chris,James');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into existInCommaSeparatedList(Name) values('Robert,Ramit');\nQuery OK, 1 row affected (0.34 sec)"
},
{
"code": null,
"e": 2010,
"s": 1951,
"text": "Display all records from the table using select statement."
},
{
"code": null,
"e": 2034,
"s": 2010,
"text": "The query is as follows"
},
{
"code": null,
"e": 2081,
"s": 2034,
"text": "mysql> select *from existInCommaSeparatedList;"
},
{
"code": null,
"e": 2109,
"s": 2081,
"text": "The following is the output"
},
{
"code": null,
"e": 2414,
"s": 2109,
"text": "+----+--------------------------------+\n| Id | Name |\n+----+--------------------------------+\n| 1 | John,Carol,Sam,Larry,Bob,David |\n| 2 | Maxwell,Chris,James |\n| 3 | Robert,Ramit |\n+----+--------------------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2549,
"s": 2414,
"text": "Here is the query to check if value exists in a comma separated list. We are checking for the field with comma separated text “Robert”"
},
{
"code": null,
"e": 2633,
"s": 2549,
"text": "mysql> SELECT *FROM existInCommaSeparatedList WHERE FIND_IN_SET('Robert',Name) > 0;"
},
{
"code": null,
"e": 2661,
"s": 2633,
"text": "The following is the output"
},
{
"code": null,
"e": 2795,
"s": 2661,
"text": "+----+--------------+\n| Id | Name |\n+----+--------------+\n| 3 | Robert,Ramit |\n+----+--------------+\n1 row in set (0.00 sec)"
}
] |
Erlang - Numbers
|
In Erlang there are 2 types of numeric literals which are integers and floats. Following are some examples which show how integers and floats can be used in Erlang.
Integer − An example of how the number data type can be used as an integer is shown in the following program. This program shows the addition of 2 Integers.
-module(helloworld).
-export([start/0]).
start() ->
io:fwrite("~w",[1+1]).
The output of the above program will be as follows −
2
Float − An example of how the number data type can be used as a float is shown in the following program. This program shows the addition of 2 Integers.
-module(helloworld).
-export([start/0]).
start() ->
io:fwrite("~w",[1.1+1.2]).
The output of the above program will be as follows −
2.3
When using the fwrite method to output values to the console, there are formatting parameters available which can be used to output numbers as float or exponential numbers. Let’s look at how we can achieve this.
-module(helloworld).
-export([start/0]).
start() ->
io:fwrite("~f~n",[1.1+1.2]),
io:fwrite("~e~n",[1.1+1.2]).
The output of the above program will be as follows −
2.300000
2.30000e+0
The following key things need to be noted about the above program −
When the ~f option is specified it means that the argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6.
When the ~f option is specified it means that the argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6.
When the ~e option is specified it means that the argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6.
When the ~e option is specified it means that the argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6.
The following mathematical functions are available in Erlang for numbers. Note that all the mathematical functions for Erlang are present in the math library. So all of the below examples will use the import statement to import all the methods in the math library.
sin
This method returns the sine of the specified value.
cos
This method returns the cosine of the specified value.
tan
This method returns the tangent of the specified value.
asin
The method returns the arcsine of the specified value.
acos
The method returns the arccosine of the specified value.
atan
The method returns the arctangent of the specified value.
The method returns the exponential of the specified value.
log
The method returns the logarithmic of the specified value.
abs
The method returns the absolute value of the specified number.
float
The method converts a number to a float value.
Is_float
The method checks if a number is a float value.
Is_Integer
The method checks if a number is a Integer value.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2466,
"s": 2301,
"text": "In Erlang there are 2 types of numeric literals which are integers and floats. Following are some examples which show how integers and floats can be used in Erlang."
},
{
"code": null,
"e": 2623,
"s": 2466,
"text": "Integer − An example of how the number data type can be used as an integer is shown in the following program. This program shows the addition of 2 Integers."
},
{
"code": null,
"e": 2705,
"s": 2623,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n io:fwrite(\"~w\",[1+1])."
},
{
"code": null,
"e": 2758,
"s": 2705,
"text": "The output of the above program will be as follows −"
},
{
"code": null,
"e": 2761,
"s": 2758,
"text": "2\n"
},
{
"code": null,
"e": 2913,
"s": 2761,
"text": "Float − An example of how the number data type can be used as a float is shown in the following program. This program shows the addition of 2 Integers."
},
{
"code": null,
"e": 2999,
"s": 2913,
"text": "-module(helloworld).\n-export([start/0]). \n\nstart() -> \n io:fwrite(\"~w\",[1.1+1.2]).\n"
},
{
"code": null,
"e": 3052,
"s": 2999,
"text": "The output of the above program will be as follows −"
},
{
"code": null,
"e": 3057,
"s": 3052,
"text": "2.3\n"
},
{
"code": null,
"e": 3269,
"s": 3057,
"text": "When using the fwrite method to output values to the console, there are formatting parameters available which can be used to output numbers as float or exponential numbers. Let’s look at how we can achieve this."
},
{
"code": null,
"e": 3390,
"s": 3269,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n io:fwrite(\"~f~n\",[1.1+1.2]), \n io:fwrite(\"~e~n\",[1.1+1.2])."
},
{
"code": null,
"e": 3443,
"s": 3390,
"text": "The output of the above program will be as follows −"
},
{
"code": null,
"e": 3464,
"s": 3443,
"text": "2.300000\n2.30000e+0\n"
},
{
"code": null,
"e": 3532,
"s": 3464,
"text": "The following key things need to be noted about the above program −"
},
{
"code": null,
"e": 3731,
"s": 3532,
"text": "When the ~f option is specified it means that the argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6."
},
{
"code": null,
"e": 3930,
"s": 3731,
"text": "When the ~f option is specified it means that the argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6."
},
{
"code": null,
"e": 4117,
"s": 3930,
"text": "When the ~e option is specified it means that the argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6."
},
{
"code": null,
"e": 4304,
"s": 4117,
"text": "When the ~e option is specified it means that the argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6."
},
{
"code": null,
"e": 4569,
"s": 4304,
"text": "The following mathematical functions are available in Erlang for numbers. Note that all the mathematical functions for Erlang are present in the math library. So all of the below examples will use the import statement to import all the methods in the math library."
},
{
"code": null,
"e": 4573,
"s": 4569,
"text": "sin"
},
{
"code": null,
"e": 4626,
"s": 4573,
"text": "This method returns the sine of the specified value."
},
{
"code": null,
"e": 4630,
"s": 4626,
"text": "cos"
},
{
"code": null,
"e": 4685,
"s": 4630,
"text": "This method returns the cosine of the specified value."
},
{
"code": null,
"e": 4689,
"s": 4685,
"text": "tan"
},
{
"code": null,
"e": 4745,
"s": 4689,
"text": "This method returns the tangent of the specified value."
},
{
"code": null,
"e": 4750,
"s": 4745,
"text": "asin"
},
{
"code": null,
"e": 4805,
"s": 4750,
"text": "The method returns the arcsine of the specified value."
},
{
"code": null,
"e": 4810,
"s": 4805,
"text": "acos"
},
{
"code": null,
"e": 4867,
"s": 4810,
"text": "The method returns the arccosine of the specified value."
},
{
"code": null,
"e": 4872,
"s": 4867,
"text": "atan"
},
{
"code": null,
"e": 4930,
"s": 4872,
"text": "The method returns the arctangent of the specified value."
},
{
"code": null,
"e": 4989,
"s": 4930,
"text": "The method returns the exponential of the specified value."
},
{
"code": null,
"e": 4993,
"s": 4989,
"text": "log"
},
{
"code": null,
"e": 5052,
"s": 4993,
"text": "The method returns the logarithmic of the specified value."
},
{
"code": null,
"e": 5056,
"s": 5052,
"text": "abs"
},
{
"code": null,
"e": 5119,
"s": 5056,
"text": "The method returns the absolute value of the specified number."
},
{
"code": null,
"e": 5125,
"s": 5119,
"text": "float"
},
{
"code": null,
"e": 5172,
"s": 5125,
"text": "The method converts a number to a float value."
},
{
"code": null,
"e": 5181,
"s": 5172,
"text": "Is_float"
},
{
"code": null,
"e": 5229,
"s": 5181,
"text": "The method checks if a number is a float value."
},
{
"code": null,
"e": 5240,
"s": 5229,
"text": "Is_Integer"
},
{
"code": null,
"e": 5290,
"s": 5240,
"text": "The method checks if a number is a Integer value."
},
{
"code": null,
"e": 5297,
"s": 5290,
"text": " Print"
},
{
"code": null,
"e": 5308,
"s": 5297,
"text": " Add Notes"
}
] |
__init__ in Python - GeeksforGeeks
|
26 Nov, 2019
Prerequisites – Python Class, Objects, Self
Whenever object oriented programming is done in Python, we mostly come across __init__ method which we usually don’t fully understand. This article explains the main concept of __init__ but before understanding the __init__ some prerequisites are required.
The __init__ method is similar to constructors in C++ and Java. Constructors are used to initialize the object’s state. The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.
Example:
# A Sample class with init method class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) p = Person('Nikhil') p.say_hi()
Output:
Hello, my name is Nikhil
In the above example, a person name Nikhil is created. While creating a person, “Nikhil” is passed as an argument, this argument will be passed to the __init__ method to initialize the object. The keyword self represents the instance of a class and binds the attributes with the given arguments. Similarly, many objects of Person class can be created by passing different names as arguments.
Example:
# A Sample class with init method class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) # Creating different objects p1 = Person('Nikhil') p2 = Person('Abhinav')p3 = Person('Anshul') p1.say_hi() p2.say_hi()p3.say_hi()
Output:
Hello, my name is Nikhil
Hello, my name is Abhinav
Hello, my name is Anshul
Inheritance is the capability of one class to derive or inherit the properties from some other class. Let’s consider the below example to see how __init__ works in inheritance.
# Python program to# demonstrate init with# inheritance class A(object): def __init__(self, something): print("A init called") self.something = something class B(A): def __init__(self, something): # Calling init of parent class A.__init__(self, something) print("B init called") self.something = something obj = B("Something")
Output:
A init called
B init called
So, the parent class constructor is called first. But in Python, it is not compulsory that parent class constructor will always be called first. The order in which the __init__ method is called for a parent or a child class can be modified. This can simply be done by calling the parent class constructor after the body of child class constructor.
Example:
# Python program to# demonstrate init with# inheritance class A(object): def __init__(self, something): print("A init called") self.something = something class B(A): def __init__(self, something): print("B init called") self.something = something # Calling init of parent class A.__init__(self, something) obj = B("Something")
Output:
B init called
A init called
Note: To know more about inheritance click here.
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25319,
"s": 25291,
"text": "\n26 Nov, 2019"
},
{
"code": null,
"e": 25363,
"s": 25319,
"text": "Prerequisites – Python Class, Objects, Self"
},
{
"code": null,
"e": 25620,
"s": 25363,
"text": "Whenever object oriented programming is done in Python, we mostly come across __init__ method which we usually don’t fully understand. This article explains the main concept of __init__ but before understanding the __init__ some prerequisites are required."
},
{
"code": null,
"e": 26136,
"s": 25620,
"text": "The __init__ method is similar to constructors in C++ and Java. Constructors are used to initialize the object’s state. The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object."
},
{
"code": null,
"e": 26145,
"s": 26136,
"text": "Example:"
},
{
"code": "# A Sample class with init method class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) p = Person('Nikhil') p.say_hi() ",
"e": 26432,
"s": 26145,
"text": null
},
{
"code": null,
"e": 26440,
"s": 26432,
"text": "Output:"
},
{
"code": null,
"e": 26466,
"s": 26440,
"text": "Hello, my name is Nikhil\n"
},
{
"code": null,
"e": 26858,
"s": 26466,
"text": "In the above example, a person name Nikhil is created. While creating a person, “Nikhil” is passed as an argument, this argument will be passed to the __init__ method to initialize the object. The keyword self represents the instance of a class and binds the attributes with the given arguments. Similarly, many objects of Person class can be created by passing different names as arguments."
},
{
"code": null,
"e": 26867,
"s": 26858,
"text": "Example:"
},
{
"code": "# A Sample class with init method class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) # Creating different objects p1 = Person('Nikhil') p2 = Person('Abhinav')p3 = Person('Anshul') p1.say_hi() p2.say_hi()p3.say_hi()",
"e": 27252,
"s": 26867,
"text": null
},
{
"code": null,
"e": 27260,
"s": 27252,
"text": "Output:"
},
{
"code": null,
"e": 27337,
"s": 27260,
"text": "Hello, my name is Nikhil\nHello, my name is Abhinav\nHello, my name is Anshul\n"
},
{
"code": null,
"e": 27514,
"s": 27337,
"text": "Inheritance is the capability of one class to derive or inherit the properties from some other class. Let’s consider the below example to see how __init__ works in inheritance."
},
{
"code": "# Python program to# demonstrate init with# inheritance class A(object): def __init__(self, something): print(\"A init called\") self.something = something class B(A): def __init__(self, something): # Calling init of parent class A.__init__(self, something) print(\"B init called\") self.something = something obj = B(\"Something\")",
"e": 27910,
"s": 27514,
"text": null
},
{
"code": null,
"e": 27918,
"s": 27910,
"text": "Output:"
},
{
"code": null,
"e": 27947,
"s": 27918,
"text": "A init called\nB init called\n"
},
{
"code": null,
"e": 28295,
"s": 27947,
"text": "So, the parent class constructor is called first. But in Python, it is not compulsory that parent class constructor will always be called first. The order in which the __init__ method is called for a parent or a child class can be modified. This can simply be done by calling the parent class constructor after the body of child class constructor."
},
{
"code": null,
"e": 28304,
"s": 28295,
"text": "Example:"
},
{
"code": "# Python program to# demonstrate init with# inheritance class A(object): def __init__(self, something): print(\"A init called\") self.something = something class B(A): def __init__(self, something): print(\"B init called\") self.something = something # Calling init of parent class A.__init__(self, something) obj = B(\"Something\")",
"e": 28700,
"s": 28304,
"text": null
},
{
"code": null,
"e": 28708,
"s": 28700,
"text": "Output:"
},
{
"code": null,
"e": 28737,
"s": 28708,
"text": "B init called\nA init called\n"
},
{
"code": null,
"e": 28786,
"s": 28737,
"text": "Note: To know more about inheritance click here."
},
{
"code": null,
"e": 28797,
"s": 28786,
"text": "Python-OOP"
},
{
"code": null,
"e": 28804,
"s": 28797,
"text": "Python"
},
{
"code": null,
"e": 28902,
"s": 28804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28920,
"s": 28902,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28955,
"s": 28920,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28987,
"s": 28955,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29009,
"s": 28987,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29051,
"s": 29009,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29081,
"s": 29051,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29107,
"s": 29081,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29136,
"s": 29107,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29180,
"s": 29136,
"text": "Reading and Writing to text files in Python"
}
] |
Matplotlib.pyplot.streamplot() in Python - GeeksforGeeks
|
21 Oct, 2021
Stream plot is basically a type of 2D plot used majorly by physicists to show fluid flow and 2D field gradients .The basic function to create a stream plot in Matplotlib is:
ax.streamplot(x_grid, y_grid, x_vec, y_vec, density=spacing)
Here x_grid and y_grid are arrays of the x and y points.The x_vec and y_vec represent the stream velocity of each point present on the grid.The attribute #density=spacing# specify that how much close the streamlines are to be drawn together.
Let’s start by creating a simple stream plot that contains streamlines on a 10 by 10 grid.All the streamlines are parallel and pointing towards the right.The code below creates the stream plot containing horizontal parallel lines pointing to the right:
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating datasetx = np.arange(0, 10)y = np.arange(0, 10) # Creating gridsX, Y = np.meshgrid(x, y) # x-component to the rightu = np.ones((10, 10)) # y-component zerov = np.zeros((10, 10)) fig = plt.figure(figsize = (12, 7)) # Plotting stream plotplt.streamplot(X, Y, u, v, density = 0.5) # show plotplt.show()
Output:
Here, x and y are 1D arrays on an evenly spaced grid, u and v are 2D arrays of velocities of x and y where the number of rows should match with the length of y while the number of columns should match with x, density is a float value which controls the closeness of the stream lines.
With the help of streamplot() function we can create and customize a plot showing field lines based on defined 2D vector field. Many attributes are available in streamplot() function for the modification of the plots.
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating data setw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) # Creating plotfig = plt.figure(figsize = (12, 7))plt.streamplot(X, Y, U, V, density = 1) # show plotplt.show()
Output:
Some of the customization of the above graph are listed below:Varying the density of streamlines –
Python3
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(24, 20))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Varying the density along a# streamlineax = fig.add_subplot(gs[0, 0])ax.streamplot(X, Y, U, V, density =[0.4, 0.8]) ax.set_title('Varying the density along a streamline') # show plotplt.tight_layout()plt.show()
Output:
Varying the color along a streamline –
Python3
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(24, 20))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Varying color along a streamlineax = fig.add_subplot(gs[0, 1])strm = ax.streamplot(X, Y, U, V, color = U, linewidth = 2, cmap ='autumn')fig.colorbar(strm.lines)ax.set_title('Varying the color along a streamline.') # show plotplt.tight_layout()plt.show()
Output:
Varying the line width along a streamline –
Python3
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(24, 20))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Varying line width along a streamlineax = fig.add_subplot(gs[1, 0])lw = 5 * speed / speed.max()ax.streamplot(X, Y, U, V, density = 0.6, color ='k', linewidth = lw) ax.set_title('Varying line width along a streamline') # show plotplt.tight_layout()plt.show()
Output:
Controlling the starting points of streamlines –
Python3
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(24, 20))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Controlling the starting points# of the streamlinesseek_points = np.array([[-2, -1, 0, 1, 2, -1], [-2, -1, 0, 1, 2, 2]]) ax = fig.add_subplot(gs[1, 1])strm = ax.streamplot(X, Y, U, V, color = U, linewidth = 2, cmap ='autumn', start_points = seek_points.T) fig.colorbar(strm.lines)ax.set_title('Controlling the starting\points of the streamlines') # Displaying the starting points# with blue symbols.ax.plot(seek_points[0], seek_points[1], 'bo')ax.set(xlim =(-w, w), ylim =(-w, w)) # show plotplt.tight_layout()plt.show()
Output:
Streamlines skipping masked regions and NaN values –
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(20, 16))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Create a maskmask = np.zeros(U.shape, dtype = bool)mask[40:60, 40:60] = TrueU[:20, :20] = np.nanU = np.ma.array(U, mask = mask) ax = fig.add_subplot(gs[2:, :])ax.streamplot(X, Y, U, V, color ='r')ax.set_title('Streamplot with Masking') ax.imshow(~mask, extent =(-w, w, -w, w), alpha = 0.5, interpolation ='nearest', cmap ='gray', aspect ='auto')ax.set_aspect('equal') # show plotplt.tight_layout()plt.show()
Output:
Example: Stream plot to demonstrate the electric field due to two point charges.The electric field at any point on a surface depends upon the position and distance between the two charges:
Python3
import sysimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Circle # Function to determine electric fielddef E(q, r0, x, y): den = np.hypot(x-r0[0], y-r0[1])**3 return q * (x - r0[0]) / den, q * (y - r0[1]) / den # Grid of x, y pointsnx, ny = 64, 64x = np.linspace(-2, 2, nx)y = np.linspace(-2, 2, ny)X, Y = np.meshgrid(x, y) # Create a multipole with nq charges of# alternating sign, equally spaced# on the unit circle. # Increase the power with increase in chargenq = 2**1charges = []for i in range(nq): q = i % 2 * 2 - 1 charges.append((q, (np.cos(2 * np.pi * i / nq), np.sin(2 * np.pi * i / nq)))) # Electric field vector, E =(Ex, Ey)# as separate componentsEx, Ey = np.zeros((ny, nx)), np.zeros((ny, nx)) for charge in charges: ex, ey = E(*charge, x = X, y = Y) Ex += ex Ey += ey fig = plt.figure(figsize =(18, 8))ax = fig.add_subplot(111) # Plotting the streamlines with# proper color and arrowcolor = 2 * np.log(np.hypot(Ex, Ey))ax.streamplot(x, y, Ex, Ey, color = color, linewidth = 1, cmap = plt.cm.inferno, density = 2, arrowstyle ='->', arrowsize = 1.5) # Add filled circles for the charges# themselvescharge_colors = {True: '#AA0000', False: '#0000AA'} for q, pos in charges: ax.add_artist(Circle(pos, 0.05, color = charge_colors[q>0])) ax.set_xlabel('X-axis')ax.set_ylabel('X-axis')ax.set_xlim(-2, 2)ax.set_ylim(-2, 2)ax.set_aspect('equal') plt.show()
Output:
saurabh1990aror
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25429,
"s": 25401,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 25605,
"s": 25429,
"text": "Stream plot is basically a type of 2D plot used majorly by physicists to show fluid flow and 2D field gradients .The basic function to create a stream plot in Matplotlib is: "
},
{
"code": null,
"e": 25666,
"s": 25605,
"text": "ax.streamplot(x_grid, y_grid, x_vec, y_vec, density=spacing)"
},
{
"code": null,
"e": 25909,
"s": 25666,
"text": "Here x_grid and y_grid are arrays of the x and y points.The x_vec and y_vec represent the stream velocity of each point present on the grid.The attribute #density=spacing# specify that how much close the streamlines are to be drawn together. "
},
{
"code": null,
"e": 26164,
"s": 25909,
"text": "Let’s start by creating a simple stream plot that contains streamlines on a 10 by 10 grid.All the streamlines are parallel and pointing towards the right.The code below creates the stream plot containing horizontal parallel lines pointing to the right: "
},
{
"code": null,
"e": 26172,
"s": 26164,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating datasetx = np.arange(0, 10)y = np.arange(0, 10) # Creating gridsX, Y = np.meshgrid(x, y) # x-component to the rightu = np.ones((10, 10)) # y-component zerov = np.zeros((10, 10)) fig = plt.figure(figsize = (12, 7)) # Plotting stream plotplt.streamplot(X, Y, u, v, density = 0.5) # show plotplt.show()",
"e": 26551,
"s": 26172,
"text": null
},
{
"code": null,
"e": 26561,
"s": 26551,
"text": "Output: "
},
{
"code": null,
"e": 26846,
"s": 26561,
"text": "Here, x and y are 1D arrays on an evenly spaced grid, u and v are 2D arrays of velocities of x and y where the number of rows should match with the length of y while the number of columns should match with x, density is a float value which controls the closeness of the stream lines. "
},
{
"code": null,
"e": 27065,
"s": 26846,
"text": "With the help of streamplot() function we can create and customize a plot showing field lines based on defined 2D vector field. Many attributes are available in streamplot() function for the modification of the plots. "
},
{
"code": null,
"e": 27073,
"s": 27065,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating data setw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) # Creating plotfig = plt.figure(figsize = (12, 7))plt.streamplot(X, Y, U, V, density = 1) # show plotplt.show()",
"e": 27376,
"s": 27073,
"text": null
},
{
"code": null,
"e": 27386,
"s": 27376,
"text": "Output: "
},
{
"code": null,
"e": 27486,
"s": 27386,
"text": "Some of the customization of the above graph are listed below:Varying the density of streamlines – "
},
{
"code": null,
"e": 27494,
"s": 27486,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(24, 20))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Varying the density along a# streamlineax = fig.add_subplot(gs[0, 0])ax.streamplot(X, Y, U, V, density =[0.4, 0.8]) ax.set_title('Varying the density along a streamline') # show plotplt.tight_layout()plt.show()",
"e": 28058,
"s": 27494,
"text": null
},
{
"code": null,
"e": 28068,
"s": 28058,
"text": "Output: "
},
{
"code": null,
"e": 28108,
"s": 28068,
"text": "Varying the color along a streamline – "
},
{
"code": null,
"e": 28116,
"s": 28108,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(24, 20))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Varying color along a streamlineax = fig.add_subplot(gs[0, 1])strm = ax.streamplot(X, Y, U, V, color = U, linewidth = 2, cmap ='autumn')fig.colorbar(strm.lines)ax.set_title('Varying the color along a streamline.') # show plotplt.tight_layout()plt.show() ",
"e": 28733,
"s": 28116,
"text": null
},
{
"code": null,
"e": 28743,
"s": 28733,
"text": "Output: "
},
{
"code": null,
"e": 28788,
"s": 28743,
"text": "Varying the line width along a streamline – "
},
{
"code": null,
"e": 28796,
"s": 28788,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(24, 20))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Varying line width along a streamlineax = fig.add_subplot(gs[1, 0])lw = 5 * speed / speed.max()ax.streamplot(X, Y, U, V, density = 0.6, color ='k', linewidth = lw) ax.set_title('Varying line width along a streamline') # show plotplt.tight_layout()plt.show()",
"e": 29407,
"s": 28796,
"text": null
},
{
"code": null,
"e": 29417,
"s": 29407,
"text": "Output: "
},
{
"code": null,
"e": 29467,
"s": 29417,
"text": "Controlling the starting points of streamlines – "
},
{
"code": null,
"e": 29475,
"s": 29467,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(24, 20))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Controlling the starting points# of the streamlinesseek_points = np.array([[-2, -1, 0, 1, 2, -1], [-2, -1, 0, 1, 2, 2]]) ax = fig.add_subplot(gs[1, 1])strm = ax.streamplot(X, Y, U, V, color = U, linewidth = 2, cmap ='autumn', start_points = seek_points.T) fig.colorbar(strm.lines)ax.set_title('Controlling the starting\\points of the streamlines') # Displaying the starting points# with blue symbols.ax.plot(seek_points[0], seek_points[1], 'bo')ax.set(xlim =(-w, w), ylim =(-w, w)) # show plotplt.tight_layout()plt.show()",
"e": 30420,
"s": 29475,
"text": null
},
{
"code": null,
"e": 30430,
"s": 30420,
"text": "Output: "
},
{
"code": null,
"e": 30484,
"s": 30430,
"text": "Streamlines skipping masked regions and NaN values – "
},
{
"code": null,
"e": 30492,
"s": 30484,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec # Creating datasetw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(20, 16))gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Create a maskmask = np.zeros(U.shape, dtype = bool)mask[40:60, 40:60] = TrueU[:20, :20] = np.nanU = np.ma.array(U, mask = mask) ax = fig.add_subplot(gs[2:, :])ax.streamplot(X, Y, U, V, color ='r')ax.set_title('Streamplot with Masking') ax.imshow(~mask, extent =(-w, w, -w, w), alpha = 0.5, interpolation ='nearest', cmap ='gray', aspect ='auto')ax.set_aspect('equal') # show plotplt.tight_layout()plt.show()",
"e": 31245,
"s": 30492,
"text": null
},
{
"code": null,
"e": 31255,
"s": 31245,
"text": "Output: "
},
{
"code": null,
"e": 31445,
"s": 31255,
"text": "Example: Stream plot to demonstrate the electric field due to two point charges.The electric field at any point on a surface depends upon the position and distance between the two charges: "
},
{
"code": null,
"e": 31453,
"s": 31445,
"text": "Python3"
},
{
"code": "import sysimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Circle # Function to determine electric fielddef E(q, r0, x, y): den = np.hypot(x-r0[0], y-r0[1])**3 return q * (x - r0[0]) / den, q * (y - r0[1]) / den # Grid of x, y pointsnx, ny = 64, 64x = np.linspace(-2, 2, nx)y = np.linspace(-2, 2, ny)X, Y = np.meshgrid(x, y) # Create a multipole with nq charges of# alternating sign, equally spaced# on the unit circle. # Increase the power with increase in chargenq = 2**1charges = []for i in range(nq): q = i % 2 * 2 - 1 charges.append((q, (np.cos(2 * np.pi * i / nq), np.sin(2 * np.pi * i / nq)))) # Electric field vector, E =(Ex, Ey)# as separate componentsEx, Ey = np.zeros((ny, nx)), np.zeros((ny, nx)) for charge in charges: ex, ey = E(*charge, x = X, y = Y) Ex += ex Ey += ey fig = plt.figure(figsize =(18, 8))ax = fig.add_subplot(111) # Plotting the streamlines with# proper color and arrowcolor = 2 * np.log(np.hypot(Ex, Ey))ax.streamplot(x, y, Ex, Ey, color = color, linewidth = 1, cmap = plt.cm.inferno, density = 2, arrowstyle ='->', arrowsize = 1.5) # Add filled circles for the charges# themselvescharge_colors = {True: '#AA0000', False: '#0000AA'} for q, pos in charges: ax.add_artist(Circle(pos, 0.05, color = charge_colors[q>0])) ax.set_xlabel('X-axis')ax.set_ylabel('X-axis')ax.set_xlim(-2, 2)ax.set_ylim(-2, 2)ax.set_aspect('equal') plt.show()",
"e": 32974,
"s": 31453,
"text": null
},
{
"code": null,
"e": 32984,
"s": 32974,
"text": "Output: "
},
{
"code": null,
"e": 33002,
"s": 32986,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 33020,
"s": 33002,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 33027,
"s": 33020,
"text": "Python"
},
{
"code": null,
"e": 33125,
"s": 33027,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33160,
"s": 33125,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 33192,
"s": 33160,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 33214,
"s": 33192,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 33256,
"s": 33214,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 33286,
"s": 33256,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 33312,
"s": 33286,
"text": "Python String | replace()"
},
{
"code": null,
"e": 33341,
"s": 33312,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 33385,
"s": 33341,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 33422,
"s": 33385,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Replace every element of the array by sum of all other elements - GeeksforGeeks
|
17 May, 2021
Given an array of size N, the task is to find the encrypted array. The encrypted array is obtained by replacing each element of the original array with the sum of the remaining array elements i.e.
For every i, arr[i] = sumOfArrayElements – arr[i]
Examples:
Input: arr[] = {5, 1, 3, 2, 4}
Output: 10 14 12 13 11
Original array {5, 1, 3, 2, 4}
Encrypted array is obtained as:
= {1+3+2+4, 5+3+2+4, 5+1+2+4, 5+1+3+4, 5+1+3+2}
= {10, 14, 12, 13, 11}
Each element of original array is replaced by the
sum of the remaining array elements.
Input: arr[] = {6, 8, 32, 12, 14, 10, 25 }
Output: 101 99 75 95 93 97 82
This problem is similar to Find original array from encrypted array (An array of sums of other elements).Approach:
Find the sum of all elements of the array.Traverse the array and replace arr[i] with the sum-arr[i].
Find the sum of all elements of the array.
Traverse the array and replace arr[i] with the sum-arr[i].
C++
Java
Python 3
C#
PHP
Javascript
// C++ implementation to find encrypted array// from the original array#include <bits/stdc++.h>using namespace std; // Finds and prints the elements of the encrypted// arrayvoid findEncryptedArray(int arr[], int n){ // total sum of elements // of original array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // calculating and displaying // elements of encrypted array for (int i = 0; i < n; i++) cout << (sum - arr[i]) << " ";} // Driver programint main(){ int arr[] = { 5, 1, 3, 2, 4 }; int N = sizeof(arr) / sizeof(arr[0]); findEncryptedArray(arr, N); return 0;}
// Java implementation to find encrypted// array from the original array class GFG { // Finds and prints the elements // of the encrypted array static void findEncryptedArray(int arr[], int n) { // total sum of elements // of original array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // calculating and displaying // elements of encrypted array for (int i = 0; i < n; i++) System.out.print(sum - arr[i] + " "); } // Driver program public static void main(String[] args) { int arr[] = { 5, 1, 3, 2, 4 }; int N = arr.length; findEncryptedArray(arr, N); }}
# Python 3 implementation# to find encrypted array# from the original array # Finds and prints the elements# of the encrypted arraydef findEncryptedArray(arr, n) : sum = 0 # total sum of elements # of original array for i in range(n) : sum += arr[i] # calculating and displaying # elements of encrypted array for i in range(n) : print(sum - arr[i], end = " ") # Driver Codeif __name__ == "__main__" : arr = [ 5, 1, 3, 2, 4] N = len(arr) # function calling findEncryptedArray(arr, N) # This code is contributed by ANKITRAI1
// C# implementation to find// encrypted array from the// original arrayusing System; class GFG{// Finds and prints the elements// of the encrypted arraystatic void findEncryptedArray(int []arr, int n){ // total sum of elements // of original array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // calculating and displaying // elements of encrypted array for (int i = 0; i < n; i++) Console.Write(sum - arr[i] + " ");} // Driver Codepublic static void Main(){ int []arr = { 5, 1, 3, 2, 4 }; int N = arr.Length; findEncryptedArray(arr, N);}} // This code is contributed// by inder_verma.
<?php// PHP implementation to// find encrypted array// from the original array // Finds and prints the// elements of the encrypted// arrayfunction findEncryptedArray(&$arr, $n){ // total sum of elements // of original array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // calculating and displaying // elements of encrypted array for ($i = 0; $i < $n; $i++) echo ($sum - $arr[$i]) . " ";} // Driver Code$arr = array(5, 1, 3, 2, 4 );$N = sizeof($arr);findEncryptedArray($arr, $N); // This code is contributed// by ChitraNayal?>
<script> // JavaScript implementation to find encrypted// array from the original array // Finds and prints the elements // of the encrypted array function findEncryptedArray(arr,n) { // total sum of elements // of original array let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // calculating and displaying // elements of encrypted array for (let i = 0; i < n; i++) document.write(sum - arr[i] + " "); } // Driver program let arr=[5, 1, 3, 2, 4 ]; let N = arr.length; findEncryptedArray(arr, N); // This code is contributed by rag2127 </script>
10 14 12 13 11
Time complexity: O(n)
inderDuMCA
ankthon
ukasp
rag2127
prefix-sum
suffix-sum
Arrays
prefix-sum
Arrays
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
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 26829,
"s": 26801,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 27027,
"s": 26829,
"text": "Given an array of size N, the task is to find the encrypted array. The encrypted array is obtained by replacing each element of the original array with the sum of the remaining array elements i.e. "
},
{
"code": null,
"e": 27077,
"s": 27027,
"text": "For every i, arr[i] = sumOfArrayElements – arr[i]"
},
{
"code": null,
"e": 27089,
"s": 27077,
"text": "Examples: "
},
{
"code": null,
"e": 27444,
"s": 27089,
"text": "Input: arr[] = {5, 1, 3, 2, 4} \nOutput: 10 14 12 13 11\nOriginal array {5, 1, 3, 2, 4}\nEncrypted array is obtained as:\n= {1+3+2+4, 5+3+2+4, 5+1+2+4, 5+1+3+4, 5+1+3+2}\n= {10, 14, 12, 13, 11}\nEach element of original array is replaced by the \nsum of the remaining array elements. \n\nInput: arr[] = {6, 8, 32, 12, 14, 10, 25 }\nOutput: 101 99 75 95 93 97 82 "
},
{
"code": null,
"e": 27563,
"s": 27446,
"text": "This problem is similar to Find original array from encrypted array (An array of sums of other elements).Approach: "
},
{
"code": null,
"e": 27664,
"s": 27563,
"text": "Find the sum of all elements of the array.Traverse the array and replace arr[i] with the sum-arr[i]."
},
{
"code": null,
"e": 27707,
"s": 27664,
"text": "Find the sum of all elements of the array."
},
{
"code": null,
"e": 27766,
"s": 27707,
"text": "Traverse the array and replace arr[i] with the sum-arr[i]."
},
{
"code": null,
"e": 27772,
"s": 27768,
"text": "C++"
},
{
"code": null,
"e": 27777,
"s": 27772,
"text": "Java"
},
{
"code": null,
"e": 27786,
"s": 27777,
"text": "Python 3"
},
{
"code": null,
"e": 27789,
"s": 27786,
"text": "C#"
},
{
"code": null,
"e": 27793,
"s": 27789,
"text": "PHP"
},
{
"code": null,
"e": 27804,
"s": 27793,
"text": "Javascript"
},
{
"code": "// C++ implementation to find encrypted array// from the original array#include <bits/stdc++.h>using namespace std; // Finds and prints the elements of the encrypted// arrayvoid findEncryptedArray(int arr[], int n){ // total sum of elements // of original array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // calculating and displaying // elements of encrypted array for (int i = 0; i < n; i++) cout << (sum - arr[i]) << \" \";} // Driver programint main(){ int arr[] = { 5, 1, 3, 2, 4 }; int N = sizeof(arr) / sizeof(arr[0]); findEncryptedArray(arr, N); return 0;}",
"e": 28428,
"s": 27804,
"text": null
},
{
"code": "// Java implementation to find encrypted// array from the original array class GFG { // Finds and prints the elements // of the encrypted array static void findEncryptedArray(int arr[], int n) { // total sum of elements // of original array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // calculating and displaying // elements of encrypted array for (int i = 0; i < n; i++) System.out.print(sum - arr[i] + \" \"); } // Driver program public static void main(String[] args) { int arr[] = { 5, 1, 3, 2, 4 }; int N = arr.length; findEncryptedArray(arr, N); }}",
"e": 29117,
"s": 28428,
"text": null
},
{
"code": "# Python 3 implementation# to find encrypted array# from the original array # Finds and prints the elements# of the encrypted arraydef findEncryptedArray(arr, n) : sum = 0 # total sum of elements # of original array for i in range(n) : sum += arr[i] # calculating and displaying # elements of encrypted array for i in range(n) : print(sum - arr[i], end = \" \") # Driver Codeif __name__ == \"__main__\" : arr = [ 5, 1, 3, 2, 4] N = len(arr) # function calling findEncryptedArray(arr, N) # This code is contributed by ANKITRAI1",
"e": 29703,
"s": 29117,
"text": null
},
{
"code": "// C# implementation to find// encrypted array from the// original arrayusing System; class GFG{// Finds and prints the elements// of the encrypted arraystatic void findEncryptedArray(int []arr, int n){ // total sum of elements // of original array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // calculating and displaying // elements of encrypted array for (int i = 0; i < n; i++) Console.Write(sum - arr[i] + \" \");} // Driver Codepublic static void Main(){ int []arr = { 5, 1, 3, 2, 4 }; int N = arr.Length; findEncryptedArray(arr, N);}} // This code is contributed// by inder_verma.",
"e": 30376,
"s": 29703,
"text": null
},
{
"code": "<?php// PHP implementation to// find encrypted array// from the original array // Finds and prints the// elements of the encrypted// arrayfunction findEncryptedArray(&$arr, $n){ // total sum of elements // of original array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // calculating and displaying // elements of encrypted array for ($i = 0; $i < $n; $i++) echo ($sum - $arr[$i]) . \" \";} // Driver Code$arr = array(5, 1, 3, 2, 4 );$N = sizeof($arr);findEncryptedArray($arr, $N); // This code is contributed// by ChitraNayal?>",
"e": 30950,
"s": 30376,
"text": null
},
{
"code": "<script> // JavaScript implementation to find encrypted// array from the original array // Finds and prints the elements // of the encrypted array function findEncryptedArray(arr,n) { // total sum of elements // of original array let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // calculating and displaying // elements of encrypted array for (let i = 0; i < n; i++) document.write(sum - arr[i] + \" \"); } // Driver program let arr=[5, 1, 3, 2, 4 ]; let N = arr.length; findEncryptedArray(arr, N); // This code is contributed by rag2127 </script>",
"e": 31622,
"s": 30950,
"text": null
},
{
"code": null,
"e": 31637,
"s": 31622,
"text": "10 14 12 13 11"
},
{
"code": null,
"e": 31662,
"s": 31639,
"text": "Time complexity: O(n) "
},
{
"code": null,
"e": 31673,
"s": 31662,
"text": "inderDuMCA"
},
{
"code": null,
"e": 31681,
"s": 31673,
"text": "ankthon"
},
{
"code": null,
"e": 31687,
"s": 31681,
"text": "ukasp"
},
{
"code": null,
"e": 31695,
"s": 31687,
"text": "rag2127"
},
{
"code": null,
"e": 31706,
"s": 31695,
"text": "prefix-sum"
},
{
"code": null,
"e": 31717,
"s": 31706,
"text": "suffix-sum"
},
{
"code": null,
"e": 31724,
"s": 31717,
"text": "Arrays"
},
{
"code": null,
"e": 31735,
"s": 31724,
"text": "prefix-sum"
},
{
"code": null,
"e": 31742,
"s": 31735,
"text": "Arrays"
},
{
"code": null,
"e": 31840,
"s": 31742,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31908,
"s": 31840,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31952,
"s": 31908,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32000,
"s": 31952,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32023,
"s": 32000,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32055,
"s": 32023,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32069,
"s": 32055,
"text": "Linear Search"
},
{
"code": null,
"e": 32090,
"s": 32069,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 32175,
"s": 32090,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 32220,
"s": 32175,
"text": "Python | Using 2D arrays/lists the right way"
}
] |
Method Class | getReturnType() Method in Java - GeeksforGeeks
|
12 Nov, 2021
Prerequisite : Java.lang.Class class in Java | Set 1, Java.lang.Class class in Java | Set 2The java.lang.reflectMethod Class help in getting information of a single method on a class or interface. This class also provides access to the methods of classes and invoke them at runtime. The getReturnType() method of Method class Every Method has a return type whether it is void, int, double, string or any other datatype. The getReturnType() method of Method class returns a Class object that represent the return type, declared in method at time of creating the method.Syntax:
public Class<?> getReturnType()
Parameters: The method does not take any parameters.Return Value: The method returns a Class object that represent the formal return type of the method object.Below programs illustrate the getReturnType() method of Method class :Program 1: Below program prints Return Type for some specific methods of a class provided as input in main method of program.
Java
/** Program Demonstrate how to apply getReturnType() method* of Method Class.*/import java.lang.reflect.Method; public class GFG { // Main method public static void main(String[] args) { try { // Create class object Class classobj = demoForReturnParam.class; // Get Method Object Method[] methods = classobj.getMethods(); // Iterate through methods for (Method method : methods) { // We are only taking method defined in the demo class // We are not taking other methods of the object class if (method.getName().equals("setValue") || method.getName().equals("getValue") || method.getName().equals("setManyValues")) { // apply getReturnType() method Class returnParam = method.getReturnType(); // print return Type class object of method Object System.out.println("\nMethod Name : " + method.getName()); System.out.println("Return Type Details: " + returnParam.getName()); } } } catch (Exception e) { e.printStackTrace(); } }} // A simple classclass demoForReturnParam { // Method returning int value public int setValue() { System.out.println("setValue"); return 24; } // Method returning string value public String getValue() { System.out.println("getValue"); return "getValue"; } // Method returning nothing public void setManyValues(int value1, String value3) { System.out.println("setManyValues"); }}
Method Name : setManyValues
Return Type Details: void
Method Name : getValue
Return Type Details: java.lang.String
Method Name : setValue
Return Type Details: int
Program 2: Below program prints Return Type for all the methods of a class provided in main method of program.
Java
/** Program Demonstrate how to apply getReturnType() method* of Method Class.*/import java.lang.reflect.Method; public class GFG { // Main method public static void main(String[] args) { try { // Create class object Class classobj = GFG.class; // Get Method Object Method[] methods = classobj.getMethods(); // Iterate through methods for (Method method : methods) { // Apply getReturnType() method Class returnParam = method.getReturnType(); // Print return Type class object of method Object System.out.println("\nMethod Name : " + method.getName()); System.out.println("Return Type Details: " + returnParam.getName()); } } catch (Exception e) { e.printStackTrace(); } } // Method returning int value public int method1() { System.out.println("method1"); return 24; } // Method returning string value public String method2() { System.out.println("method2"); return "method3"; } // Method returning nothing public void method3(int value1, String value3) { System.out.println("method3"); }}
Method Name : method3
Return Type Details: void
Method Name : method2
Return Type Details: java.lang.String
Method Name : method1
Return Type Details: int
Method Name : main
Return Type Details: void
Method Name : wait
Return Type Details: void
Method Name : wait
Return Type Details: void
Method Name : wait
Return Type Details: void
Method Name : equals
Return Type Details: boolean
Method Name : toString
Return Type Details: java.lang.String
Method Name : hashCode
Return Type Details: int
Method Name : getClass
Return Type Details: java.lang.Class
Method Name : notify
Return Type Details: void
Method Name : notifyAll
Return Type Details: void
Explanation: Output of this program also showing results for method objects other than methods defined in class object like wait, equals, toString, hashCode, getClass, notify, notifyAll. These methods are inherited from super class name Object of java.lang lang package by class object.Reference: Oracle Doc for getReturnType()
kashishsoda
Java-Functions
Java-lang package
java-lang-reflect-package
Java-Method Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Interfaces in Java
Stream In Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Queue Interface In Java
|
[
{
"code": null,
"e": 25535,
"s": 25507,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 26113,
"s": 25535,
"text": "Prerequisite : Java.lang.Class class in Java | Set 1, Java.lang.Class class in Java | Set 2The java.lang.reflectMethod Class help in getting information of a single method on a class or interface. This class also provides access to the methods of classes and invoke them at runtime. The getReturnType() method of Method class Every Method has a return type whether it is void, int, double, string or any other datatype. The getReturnType() method of Method class returns a Class object that represent the return type, declared in method at time of creating the method.Syntax: "
},
{
"code": null,
"e": 26145,
"s": 26113,
"text": "public Class<?> getReturnType()"
},
{
"code": null,
"e": 26502,
"s": 26145,
"text": "Parameters: The method does not take any parameters.Return Value: The method returns a Class object that represent the formal return type of the method object.Below programs illustrate the getReturnType() method of Method class :Program 1: Below program prints Return Type for some specific methods of a class provided as input in main method of program. "
},
{
"code": null,
"e": 26507,
"s": 26502,
"text": "Java"
},
{
"code": "/** Program Demonstrate how to apply getReturnType() method* of Method Class.*/import java.lang.reflect.Method; public class GFG { // Main method public static void main(String[] args) { try { // Create class object Class classobj = demoForReturnParam.class; // Get Method Object Method[] methods = classobj.getMethods(); // Iterate through methods for (Method method : methods) { // We are only taking method defined in the demo class // We are not taking other methods of the object class if (method.getName().equals(\"setValue\") || method.getName().equals(\"getValue\") || method.getName().equals(\"setManyValues\")) { // apply getReturnType() method Class returnParam = method.getReturnType(); // print return Type class object of method Object System.out.println(\"\\nMethod Name : \" + method.getName()); System.out.println(\"Return Type Details: \" + returnParam.getName()); } } } catch (Exception e) { e.printStackTrace(); } }} // A simple classclass demoForReturnParam { // Method returning int value public int setValue() { System.out.println(\"setValue\"); return 24; } // Method returning string value public String getValue() { System.out.println(\"getValue\"); return \"getValue\"; } // Method returning nothing public void setManyValues(int value1, String value3) { System.out.println(\"setManyValues\"); }}",
"e": 28251,
"s": 26507,
"text": null
},
{
"code": null,
"e": 28416,
"s": 28251,
"text": "Method Name : setManyValues\nReturn Type Details: void\n\nMethod Name : getValue\nReturn Type Details: java.lang.String\n\nMethod Name : setValue\nReturn Type Details: int"
},
{
"code": null,
"e": 28531,
"s": 28418,
"text": "Program 2: Below program prints Return Type for all the methods of a class provided in main method of program. "
},
{
"code": null,
"e": 28536,
"s": 28531,
"text": "Java"
},
{
"code": "/** Program Demonstrate how to apply getReturnType() method* of Method Class.*/import java.lang.reflect.Method; public class GFG { // Main method public static void main(String[] args) { try { // Create class object Class classobj = GFG.class; // Get Method Object Method[] methods = classobj.getMethods(); // Iterate through methods for (Method method : methods) { // Apply getReturnType() method Class returnParam = method.getReturnType(); // Print return Type class object of method Object System.out.println(\"\\nMethod Name : \" + method.getName()); System.out.println(\"Return Type Details: \" + returnParam.getName()); } } catch (Exception e) { e.printStackTrace(); } } // Method returning int value public int method1() { System.out.println(\"method1\"); return 24; } // Method returning string value public String method2() { System.out.println(\"method2\"); return \"method3\"; } // Method returning nothing public void method3(int value1, String value3) { System.out.println(\"method3\"); }}",
"e": 29842,
"s": 28536,
"text": null
},
{
"code": null,
"e": 30505,
"s": 29842,
"text": "Method Name : method3\nReturn Type Details: void\n\nMethod Name : method2\nReturn Type Details: java.lang.String\n\nMethod Name : method1\nReturn Type Details: int\n\nMethod Name : main\nReturn Type Details: void\n\nMethod Name : wait\nReturn Type Details: void\n\nMethod Name : wait\nReturn Type Details: void\n\nMethod Name : wait\nReturn Type Details: void\n\nMethod Name : equals\nReturn Type Details: boolean\n\nMethod Name : toString\nReturn Type Details: java.lang.String\n\nMethod Name : hashCode\nReturn Type Details: int\n\nMethod Name : getClass\nReturn Type Details: java.lang.Class\n\nMethod Name : notify\nReturn Type Details: void\n\nMethod Name : notifyAll\nReturn Type Details: void"
},
{
"code": null,
"e": 30836,
"s": 30507,
"text": "Explanation: Output of this program also showing results for method objects other than methods defined in class object like wait, equals, toString, hashCode, getClass, notify, notifyAll. These methods are inherited from super class name Object of java.lang lang package by class object.Reference: Oracle Doc for getReturnType() "
},
{
"code": null,
"e": 30848,
"s": 30836,
"text": "kashishsoda"
},
{
"code": null,
"e": 30863,
"s": 30848,
"text": "Java-Functions"
},
{
"code": null,
"e": 30881,
"s": 30863,
"text": "Java-lang package"
},
{
"code": null,
"e": 30907,
"s": 30881,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 30925,
"s": 30907,
"text": "Java-Method Class"
},
{
"code": null,
"e": 30930,
"s": 30925,
"text": "Java"
},
{
"code": null,
"e": 30935,
"s": 30930,
"text": "Java"
},
{
"code": null,
"e": 31033,
"s": 30935,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31063,
"s": 31033,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31082,
"s": 31063,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31097,
"s": 31082,
"text": "Stream In Java"
},
{
"code": null,
"e": 31115,
"s": 31097,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31147,
"s": 31115,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31167,
"s": 31147,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31199,
"s": 31167,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31223,
"s": 31199,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 31235,
"s": 31223,
"text": "Set in Java"
}
] |
How to validate if input in input field is a valid credit card number using express-validator ? - GeeksforGeeks
|
08 Apr, 2022
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only valid credit card numbers are allowed i.e. there not allowed any other string or number which not follow the rule to be a valid credit card. We can also validate these input fields to only accept a valid credit card number using express-validator middleware.
Condition to be a valid credit card number:
Credit card number must follow the Luhn’s algorithm as shown below:
The Luhn Formula:
Drop the last digit from the number. The last digit is what we want to check against.
Reverse the numbers.
Multiply the digits in odd positions (1, 3, 5, etc.) by 2 and subtract 9 to all any result higher than 9.
Add all the numbers together.
The check digit (the last number of the card) is the amount that you would need to add to get a multiple of 10 (Modulo 10).
Example: Original Number: 4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 5 Drop the last digit: 4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 Reverse the digits: 5 8 9 9 8 6 8 5 7 3 7 6 5 5 4 Multiple odd place digits by 2: 10 8 18 9 16 6 16 5 14 3 14 6 10 5 8 Subtract 9 to numbers over 9: 1 8 9 9 7 6 7 5 5 3 5 6 1 5 8 Add all numbers: 1 8 9 9 7 6 7 5 5 3 5 6 1 5 8 = 85 Mod 10: 85 modulo 10 = 5 (last digit of card)
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on validation isCreditCard() with ‘ . ‘
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate an input field to only allow a valid credit card number.
javascript
const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateCardNumber } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/cardinfo', [validateCardNumber], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {cname, cno, edate} = req.body // New record await repo.create({ 'card name':cname, 'card number':cno, 'expiry date':edate.toString() }) res.send('<strong>Card information is saved ' + 'to the database successfully</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch (err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding: 'utf8' })) } // Create new record async create(attrs) { // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile(this.filename, JSON.stringify(records, null, 2)) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')
Filename – form.js: This file contains logic to show form to submit the card information.
javascript
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/cardinfo' method='POST'> <div> <div> <label class='label' id='cname'> Card Name </label> </div> <input class='input' type='text' name='cname' placeholder='Vinit singh' for='cname'> </div> <div> <div> <label class='label' id='cno'> Card Number </label> </div> <input class='input' type='text' name='cno' placeholder='Card Number' for='cno'> <p class="help is-danger"> ${getError(errors, 'cno')} </p> </div> <div> <div> <label class='label' id='edate'> Expiry Date </label> </div> <input class='input' type='date' name='edate' placeholder='23/9/2026' for='cdate'> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}
Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to only allow a valid credit card number).
javascript
const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateCardNumber : check('cno') // To delete leading and trailing space .trim() // Validate height to accept // only decimal number .isCreditCard() // Custom message .withMessage('Must be a valid credit card number') }
Filename – package.json
package.json file
Database:
Database
Output:
Attempt to submit the form with invalid card number(not following luhn formula)
Attempt to submit the form with invalid card number(not following luhn formula and also no credit card started with number 9)
Response when attempt to submit the form with invalid card number
Attempt to submit the form with valid card number(following luhn formula)
Response when attempt to submit the form with valid card number
Database after successful submission of form:
Database after successful submission of form
Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content.
anikakapoor
rkbhola5
Express.js
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Export Module
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 26777,
"s": 26267,
"text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only valid credit card numbers are allowed i.e. there not allowed any other string or number which not follow the rule to be a valid credit card. We can also validate these input fields to only accept a valid credit card number using express-validator middleware."
},
{
"code": null,
"e": 26821,
"s": 26777,
"text": "Condition to be a valid credit card number:"
},
{
"code": null,
"e": 26889,
"s": 26821,
"text": "Credit card number must follow the Luhn’s algorithm as shown below:"
},
{
"code": null,
"e": 26907,
"s": 26889,
"text": "The Luhn Formula:"
},
{
"code": null,
"e": 26993,
"s": 26907,
"text": "Drop the last digit from the number. The last digit is what we want to check against."
},
{
"code": null,
"e": 27014,
"s": 26993,
"text": "Reverse the numbers."
},
{
"code": null,
"e": 27120,
"s": 27014,
"text": "Multiply the digits in odd positions (1, 3, 5, etc.) by 2 and subtract 9 to all any result higher than 9."
},
{
"code": null,
"e": 27150,
"s": 27120,
"text": "Add all the numbers together."
},
{
"code": null,
"e": 27274,
"s": 27150,
"text": "The check digit (the last number of the card) is the amount that you would need to add to get a multiple of 10 (Modulo 10)."
},
{
"code": null,
"e": 27661,
"s": 27274,
"text": "Example: Original Number: 4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 5 Drop the last digit: 4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 Reverse the digits: 5 8 9 9 8 6 8 5 7 3 7 6 5 5 4 Multiple odd place digits by 2: 10 8 18 9 16 6 16 5 14 3 14 6 10 5 8 Subtract 9 to numbers over 9: 1 8 9 9 7 6 7 5 5 3 5 6 1 5 8 Add all numbers: 1 8 9 9 7 6 7 5 5 3 5 6 1 5 8 = 85 Mod 10: 85 modulo 10 = 5 (last digit of card) "
},
{
"code": null,
"e": 27699,
"s": 27661,
"text": "Command to install express-validator:"
},
{
"code": null,
"e": 27729,
"s": 27699,
"text": "npm install express-validator"
},
{
"code": null,
"e": 27784,
"s": 27729,
"text": "Steps to use express-validator to implement the logic:"
},
{
"code": null,
"e": 27822,
"s": 27784,
"text": "Install express-validator middleware."
},
{
"code": null,
"e": 27883,
"s": 27822,
"text": "Create a validator.js file to code all the validation logic."
},
{
"code": null,
"e": 27995,
"s": 27883,
"text": "Validate input by validateInputField: check(input field name) and chain on validation isCreditCard() with ‘ . ‘"
},
{
"code": null,
"e": 28097,
"s": 27995,
"text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations."
},
{
"code": null,
"e": 28190,
"s": 28097,
"text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors."
},
{
"code": null,
"e": 28263,
"s": 28190,
"text": "If error occurs redirect to the same page passing the error information."
},
{
"code": null,
"e": 28339,
"s": 28263,
"text": "If error list is empty, give access to the user for the subsequent request."
},
{
"code": null,
"e": 28505,
"s": 28339,
"text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."
},
{
"code": null,
"e": 28612,
"s": 28505,
"text": "Example: This example illustrates how to validate an input field to only allow a valid credit card number."
},
{
"code": null,
"e": 28623,
"s": 28612,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateCardNumber } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/cardinfo', [validateCardNumber], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {cname, cno, edate} = req.body // New record await repo.create({ 'card name':cname, 'card number':cno, 'expiry date':edate.toString() }) res.send('<strong>Card information is saved ' + 'to the database successfully</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 29722,
"s": 28623,
"text": null
},
{
"code": null,
"e": 29830,
"s": 29722,
"text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it."
},
{
"code": null,
"e": 29841,
"s": 29830,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch (err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding: 'utf8' })) } // Create new record async create(attrs) { // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile(this.filename, JSON.stringify(records, null, 2)) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 31094,
"s": 29841,
"text": null
},
{
"code": null,
"e": 31184,
"s": 31094,
"text": "Filename – form.js: This file contains logic to show form to submit the card information."
},
{
"code": null,
"e": 31195,
"s": 31184,
"text": "javascript"
},
{
"code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/cardinfo' method='POST'> <div> <div> <label class='label' id='cname'> Card Name </label> </div> <input class='input' type='text' name='cname' placeholder='Vinit singh' for='cname'> </div> <div> <div> <label class='label' id='cno'> Card Number </label> </div> <input class='input' type='text' name='cno' placeholder='Card Number' for='cno'> <p class=\"help is-danger\"> ${getError(errors, 'cno')} </p> </div> <div> <div> <label class='label' id='edate'> Expiry Date </label> </div> <input class='input' type='date' name='edate' placeholder='23/9/2026' for='cdate'> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}",
"e": 32843,
"s": 31195,
"text": null
},
{
"code": null,
"e": 32986,
"s": 32843,
"text": "Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to only allow a valid credit card number)."
},
{
"code": null,
"e": 32997,
"s": 32986,
"text": "javascript"
},
{
"code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateCardNumber : check('cno') // To delete leading and trailing space .trim() // Validate height to accept // only decimal number .isCreditCard() // Custom message .withMessage('Must be a valid credit card number') }",
"e": 33346,
"s": 32997,
"text": null
},
{
"code": null,
"e": 33370,
"s": 33346,
"text": "Filename – package.json"
},
{
"code": null,
"e": 33388,
"s": 33370,
"text": "package.json file"
},
{
"code": null,
"e": 33398,
"s": 33388,
"text": "Database:"
},
{
"code": null,
"e": 33407,
"s": 33398,
"text": "Database"
},
{
"code": null,
"e": 33415,
"s": 33407,
"text": "Output:"
},
{
"code": null,
"e": 33495,
"s": 33415,
"text": "Attempt to submit the form with invalid card number(not following luhn formula)"
},
{
"code": null,
"e": 33621,
"s": 33495,
"text": "Attempt to submit the form with invalid card number(not following luhn formula and also no credit card started with number 9)"
},
{
"code": null,
"e": 33687,
"s": 33621,
"text": "Response when attempt to submit the form with invalid card number"
},
{
"code": null,
"e": 33761,
"s": 33687,
"text": "Attempt to submit the form with valid card number(following luhn formula)"
},
{
"code": null,
"e": 33825,
"s": 33761,
"text": "Response when attempt to submit the form with valid card number"
},
{
"code": null,
"e": 33871,
"s": 33825,
"text": "Database after successful submission of form:"
},
{
"code": null,
"e": 33916,
"s": 33871,
"text": "Database after successful submission of form"
},
{
"code": null,
"e": 34012,
"s": 33916,
"text": "Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content."
},
{
"code": null,
"e": 34024,
"s": 34012,
"text": "anikakapoor"
},
{
"code": null,
"e": 34033,
"s": 34024,
"text": "rkbhola5"
},
{
"code": null,
"e": 34044,
"s": 34033,
"text": "Express.js"
},
{
"code": null,
"e": 34057,
"s": 34044,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 34065,
"s": 34057,
"text": "Node.js"
},
{
"code": null,
"e": 34082,
"s": 34065,
"text": "Web Technologies"
},
{
"code": null,
"e": 34180,
"s": 34082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34202,
"s": 34180,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 34241,
"s": 34202,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 34311,
"s": 34241,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 34336,
"s": 34311,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 34363,
"s": 34336,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 34403,
"s": 34363,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34448,
"s": 34403,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34491,
"s": 34448,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 34553,
"s": 34491,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Java | Class and Object | Question 5 - GeeksforGeeks
|
28 Jun, 2021
Predict the output of the following program.
class First{ void display() { System.out.println("Inside First"); }} class Second extends First{ void display() { System.out.println("Inside Second"); }} class Test{ public static void main(String[] args) { First obj1 = new First(); Second obj2 = new Second(); First ref; ref = obj1; ref.display(); ref = obj2; ref.display(); }}
(A) Compilation error(B)
Inside First
Inside Second
(C)
Inside First
Inside First
(D) Runtime errorAnswer: (B)Explanation: ‘ref’ is a reference variable which obtains the reference of object of class First and calls its function display().Then ‘ref’ refers to object of class Second and calls its function display().Quiz of this Question
Class and Object
Java-Class and Object
Java Quiz
Java-Class and Object
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Java | Arrays | Question 1
Java | Functions | Question 1
Java | Exception Handling | Question 6
Java | Abstract Class and Interface | Question 2
Java | Exception Handling | Question 4
Java | Exception Handling | Question 3
Java | Packages | Question 2
Java | Operators | Question 1
Java | Exception Handling | Question 8
Java | Exception Handling | Question 7
|
[
{
"code": null,
"e": 23999,
"s": 23971,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24044,
"s": 23999,
"text": "Predict the output of the following program."
},
{
"code": " class First{ void display() { System.out.println(\"Inside First\"); }} class Second extends First{ void display() { System.out.println(\"Inside Second\"); }} class Test{ public static void main(String[] args) { First obj1 = new First(); Second obj2 = new Second(); First ref; ref = obj1; ref.display(); ref = obj2; ref.display(); }}",
"e": 24482,
"s": 24044,
"text": null
},
{
"code": null,
"e": 24507,
"s": 24482,
"text": "(A) Compilation error(B)"
},
{
"code": null,
"e": 24534,
"s": 24507,
"text": "Inside First\nInside Second"
},
{
"code": null,
"e": 24538,
"s": 24534,
"text": "(C)"
},
{
"code": null,
"e": 24564,
"s": 24538,
"text": "Inside First\nInside First"
},
{
"code": null,
"e": 24820,
"s": 24564,
"text": "(D) Runtime errorAnswer: (B)Explanation: ‘ref’ is a reference variable which obtains the reference of object of class First and calls its function display().Then ‘ref’ refers to object of class Second and calls its function display().Quiz of this Question"
},
{
"code": null,
"e": 24837,
"s": 24820,
"text": "Class and Object"
},
{
"code": null,
"e": 24859,
"s": 24837,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 24869,
"s": 24859,
"text": "Java Quiz"
},
{
"code": null,
"e": 24891,
"s": 24869,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 24989,
"s": 24891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24998,
"s": 24989,
"text": "Comments"
},
{
"code": null,
"e": 25011,
"s": 24998,
"text": "Old Comments"
},
{
"code": null,
"e": 25038,
"s": 25011,
"text": "Java | Arrays | Question 1"
},
{
"code": null,
"e": 25068,
"s": 25038,
"text": "Java | Functions | Question 1"
},
{
"code": null,
"e": 25107,
"s": 25068,
"text": "Java | Exception Handling | Question 6"
},
{
"code": null,
"e": 25156,
"s": 25107,
"text": "Java | Abstract Class and Interface | Question 2"
},
{
"code": null,
"e": 25195,
"s": 25156,
"text": "Java | Exception Handling | Question 4"
},
{
"code": null,
"e": 25234,
"s": 25195,
"text": "Java | Exception Handling | Question 3"
},
{
"code": null,
"e": 25263,
"s": 25234,
"text": "Java | Packages | Question 2"
},
{
"code": null,
"e": 25293,
"s": 25263,
"text": "Java | Operators | Question 1"
},
{
"code": null,
"e": 25332,
"s": 25293,
"text": "Java | Exception Handling | Question 8"
}
] |
PHP & MySQL - Sorting Data Example
|
PHP uses mysqli query() or mysql_query() function to get sorted records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli->query($sql,$resultmode)
$sql
Required - SQL query to get sorted records from a table.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to get sorted records from a table −
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Sorting MySQL Table records</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');
$sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl order by tutorial_title asc";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
$row["tutorial_id"],
$row["tutorial_title"],
$row["tutorial_author"],
$row["submission_date"]);
}
} else {
printf('No record found.<br />');
}
mysqli_free_result($result);
$mysqli->close();
?>
</body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021
Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2308,
"s": 2132,
"text": "PHP uses mysqli query() or mysql_query() function to get sorted records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 2342,
"s": 2308,
"text": "$mysqli->query($sql,$resultmode)\n"
},
{
"code": null,
"e": 2347,
"s": 2342,
"text": "$sql"
},
{
"code": null,
"e": 2404,
"s": 2347,
"text": "Required - SQL query to get sorted records from a table."
},
{
"code": null,
"e": 2416,
"s": 2404,
"text": "$resultmode"
},
{
"code": null,
"e": 2564,
"s": 2416,
"text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used."
},
{
"code": null,
"e": 2627,
"s": 2564,
"text": "Try the following example to get sorted records from a table −"
},
{
"code": null,
"e": 2687,
"s": 2627,
"text": "Copy and paste the following example as mysql_example.php −"
},
{
"code": null,
"e": 3898,
"s": 2687,
"text": "<html>\n <head>\n <title>Sorting MySQL Table records</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli->connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli->connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n \n $sql = \"SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl order by tutorial_title asc\";\n $result = $mysqli->query($sql);\n \n if ($result->num_rows > 0) {\n while($row = $result->fetch_assoc()) {\n printf(\"Id: %s, Title: %s, Author: %s, Date: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_title\"], \n $row[\"tutorial_author\"],\n $row[\"submission_date\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli->close();\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 3980,
"s": 3898,
"text": "Access the mysql_example.php deployed on apache web server and verify the output."
},
{
"code": null,
"e": 4231,
"s": 3980,
"text": "Connected successfully.\nId: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021\nId: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021\nId: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021\nId: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021\n"
},
{
"code": null,
"e": 4264,
"s": 4231,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4280,
"s": 4264,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4313,
"s": 4280,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4324,
"s": 4313,
"text": " Syed Raza"
},
{
"code": null,
"e": 4359,
"s": 4324,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4376,
"s": 4359,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4409,
"s": 4376,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4424,
"s": 4409,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 4459,
"s": 4424,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 4471,
"s": 4459,
"text": " Azaz Patel"
},
{
"code": null,
"e": 4506,
"s": 4471,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4534,
"s": 4506,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4541,
"s": 4534,
"text": " Print"
},
{
"code": null,
"e": 4552,
"s": 4541,
"text": " Add Notes"
}
] |
Tryit Editor v3.6 - Show Node.js Command Prompt
|
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
//Parse the address:
var q = url.parse(adr, true);
/*The parse method returns an object containing url properties*/
console.log(q.host);
console.log(q.pathname);
console.log(q.search);
/*The query property returns an object with all the querystring parameters as properties:*/
|
[
{
"code": null,
"e": 26,
"s": 0,
"text": "var url = require('url');"
},
{
"code": null,
"e": 98,
"s": 26,
"text": "var adr = 'http://localhost:8080/default.htm?year=2017&month=february';"
},
{
"code": null,
"e": 119,
"s": 98,
"text": "//Parse the address:"
},
{
"code": null,
"e": 149,
"s": 119,
"text": "var q = url.parse(adr, true);"
},
{
"code": null,
"e": 151,
"s": 149,
"text": ""
},
{
"code": null,
"e": 216,
"s": 151,
"text": "/*The parse method returns an object containing url properties*/"
},
{
"code": null,
"e": 237,
"s": 216,
"text": "console.log(q.host);"
},
{
"code": null,
"e": 262,
"s": 237,
"text": "console.log(q.pathname);"
},
{
"code": null,
"e": 285,
"s": 262,
"text": "console.log(q.search);"
},
{
"code": null,
"e": 287,
"s": 285,
"text": ""
}
] |
Arjun – Hidden HTTP Parameter Discovery Suite in Kali Linux - GeeksforGeeks
|
30 Jun, 2021
When a security researcher tries to hack a web application to test the security of a web application, sometimes it becomes a challenging task due to the sheer amount of moving parts they possess. The web applications use HTTP requests and parameters for GET and POST methods. But sometimes developers of web applications conceal these details from the user due to internal security reasons for the web applications. However, Arjun is a tool that can help security researchers in such situations. This tool helps security researchers to discover hidden HTTP parameters in web applications. HTTP parameters are also called query strings, which you see in the URL bar. The following is an example of an HTTP parameter.
http://site.com/name?id=1
Arjun is an Indian bug bounty tool. The Arjun tool is famous for finding query parameters for URL endpoints on the links of websites and web apps. This tool is a lightweight tool and can find parameters in 10 seconds by just making 20-40 requests to the target domain. This tool has an in-built default dictionary of 10,985 parameter names, which makes it more powerful to find query parameters in URL. This tool provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain), which can be a website or an IP address. The interactive console provides a number of helpful features, such as command completion and contextual help.
Step 1: Open your kali Linux operating system and use the following command to install the tool. After installing the tool, you have to move into the directory of the tool using the second command. To list out the contents of the directory, use the third command that is given below.
git clone https://github.com/s0md3v/Arjun.git
cd Arjun
ls -l
Step 2: The tool has been downloaded successfully. Now use the following command to install the tool.
python3 setup.py install
Step 3: The tool has been installed successfully. Now use the following command to run the tool.
arjun -h
The help menu of the tool is opened. The tool is running successfully. Now let’s see some examples which will show usages of the tool.
Example 1: Use the arjun tool to find the endpoints of a URL.
arjun -u http://testphp.vulnweb.com/listproducts.php
The tool giving all the information above can be useful for a security researcher.
Example 2: Use the arjun tool to find the endpoints of a URL with the -u flag.
arjun -u http://testphp.vulnweb.com/listproducts.php -o new.json
And to search for JSON parameters, use the –json option or new.json option with -o flag
Example 3: Use the arjun tool to find the endpoints of a URL with -u flag with the heuristic scanner.
arjun -u http://google.com
The -u flag is the simple way to run the tool. You have to apply the -u URL to the tool with the valid URL.
Example 4: Use the arjun tool to find endpoints of a URL with -u flag and thread drag.
arjun -u http://google.com -t 5
Kali-Linux
linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25122,
"s": 24406,
"text": "When a security researcher tries to hack a web application to test the security of a web application, sometimes it becomes a challenging task due to the sheer amount of moving parts they possess. The web applications use HTTP requests and parameters for GET and POST methods. But sometimes developers of web applications conceal these details from the user due to internal security reasons for the web applications. However, Arjun is a tool that can help security researchers in such situations. This tool helps security researchers to discover hidden HTTP parameters in web applications. HTTP parameters are also called query strings, which you see in the URL bar. The following is an example of an HTTP parameter."
},
{
"code": null,
"e": 25148,
"s": 25122,
"text": "http://site.com/name?id=1"
},
{
"code": null,
"e": 25846,
"s": 25148,
"text": "Arjun is an Indian bug bounty tool. The Arjun tool is famous for finding query parameters for URL endpoints on the links of websites and web apps. This tool is a lightweight tool and can find parameters in 10 seconds by just making 20-40 requests to the target domain. This tool has an in-built default dictionary of 10,985 parameter names, which makes it more powerful to find query parameters in URL. This tool provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain), which can be a website or an IP address. The interactive console provides a number of helpful features, such as command completion and contextual help."
},
{
"code": null,
"e": 26130,
"s": 25846,
"text": "Step 1: Open your kali Linux operating system and use the following command to install the tool. After installing the tool, you have to move into the directory of the tool using the second command. To list out the contents of the directory, use the third command that is given below."
},
{
"code": null,
"e": 26191,
"s": 26130,
"text": "git clone https://github.com/s0md3v/Arjun.git\ncd Arjun\nls -l"
},
{
"code": null,
"e": 26293,
"s": 26191,
"text": "Step 2: The tool has been downloaded successfully. Now use the following command to install the tool."
},
{
"code": null,
"e": 26318,
"s": 26293,
"text": "python3 setup.py install"
},
{
"code": null,
"e": 26415,
"s": 26318,
"text": "Step 3: The tool has been installed successfully. Now use the following command to run the tool."
},
{
"code": null,
"e": 26424,
"s": 26415,
"text": "arjun -h"
},
{
"code": null,
"e": 26559,
"s": 26424,
"text": "The help menu of the tool is opened. The tool is running successfully. Now let’s see some examples which will show usages of the tool."
},
{
"code": null,
"e": 26621,
"s": 26559,
"text": "Example 1: Use the arjun tool to find the endpoints of a URL."
},
{
"code": null,
"e": 26674,
"s": 26621,
"text": "arjun -u http://testphp.vulnweb.com/listproducts.php"
},
{
"code": null,
"e": 26757,
"s": 26674,
"text": "The tool giving all the information above can be useful for a security researcher."
},
{
"code": null,
"e": 26836,
"s": 26757,
"text": "Example 2: Use the arjun tool to find the endpoints of a URL with the -u flag."
},
{
"code": null,
"e": 26901,
"s": 26836,
"text": "arjun -u http://testphp.vulnweb.com/listproducts.php -o new.json"
},
{
"code": null,
"e": 26989,
"s": 26901,
"text": "And to search for JSON parameters, use the –json option or new.json option with -o flag"
},
{
"code": null,
"e": 27091,
"s": 26989,
"text": "Example 3: Use the arjun tool to find the endpoints of a URL with -u flag with the heuristic scanner."
},
{
"code": null,
"e": 27118,
"s": 27091,
"text": "arjun -u http://google.com"
},
{
"code": null,
"e": 27226,
"s": 27118,
"text": "The -u flag is the simple way to run the tool. You have to apply the -u URL to the tool with the valid URL."
},
{
"code": null,
"e": 27313,
"s": 27226,
"text": "Example 4: Use the arjun tool to find endpoints of a URL with -u flag and thread drag."
},
{
"code": null,
"e": 27345,
"s": 27313,
"text": "arjun -u http://google.com -t 5"
},
{
"code": null,
"e": 27356,
"s": 27345,
"text": "Kali-Linux"
},
{
"code": null,
"e": 27362,
"s": 27356,
"text": "linux"
},
{
"code": null,
"e": 27374,
"s": 27362,
"text": "Linux-Tools"
},
{
"code": null,
"e": 27385,
"s": 27374,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27483,
"s": 27385,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27520,
"s": 27483,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27555,
"s": 27520,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27581,
"s": 27555,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27615,
"s": 27581,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27644,
"s": 27615,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27681,
"s": 27644,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27707,
"s": 27681,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27747,
"s": 27707,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 27782,
"s": 27747,
"text": "Basic Operators in Shell Scripting"
}
] |
Design an online book reader system - GeeksforGeeks
|
29 Jul, 2021
Design an online book reader system (Object-Oriented Design).
Asked In: Amazon, Microsoft, and many more interviews
Solution: Let’s assume we want to design a basic online reading system that provides the following functionality:
• Searching the database of books and reading a book.• User membership creation and extension.• Only one active user at a time and only one active book by this user
The class OnlineReaderSystem represents the body of our program. We could implementthe class such that it stores information about all the books deals with user management and refreshes the display, but that would make this class rather hefty. Instead, we’ve chosen to tear off these components into Library, UserManager, and Display classes.
The classes:
1. User2. Book3. Library4. UserManager5. Display6. OnlineReaderSystem
Full code is given below :
Java
C#
import java.util.HashMap; /** This class represents the system*/ class OnlineReaderSystem { private Library library; private UserManager userManager; private Display display; private Book activeBook; private User activeUser; public OnlineReaderSystem() { userManager = new UserManager(); library = new Library(); display = new Display(); } public Library getLibrary() { return library; } public UserManager getUserManager() { return userManager; } public Display getDisplay() { return display; } public Book getActiveBook() { return activeBook; } public void setActiveBook(Book book) { activeBook = book; display.displayBook(book); } public User getActiveUser() { return activeUser; } public void setActiveUser(User user) { activeUser = user; display.displayUser(user); }} /** We then implement separate classes to handle the user* manager, the library, and the display components */ /** This class represents the Library which is responsible* for storing and searching the books.*/class Library { private HashMap<Integer, Book> books; public Library() { books = new HashMap<Integer, Book>(); } public Boolean addBook(int id, String details, String title) { if (books.containsKey(id)) { return false; } Book book = new Book(id, details, title); books.put(id, book); return true; } public Boolean addBook(Book book) { if (books.containsKey(book.getId())) { return false; } books.put(book.getId(), book); return true; } public boolean remove(Book b) { return remove(b.getId()); } public boolean remove(int id) { if (!books.containsKey(id)) { return false; } books.remove(id); return true; } public Book find(int id) { return books.get(id); }} /** This class represents the UserManager which is responsible * for managing the users, their membership etc.*/ class UserManager { private HashMap<Integer, User> users; public UserManager() { users = new HashMap<Integer, User>(); } public Boolean addUser(int id, String details, String name) { if (users.containsKey(id)) { return false; } User user = new User(id, details, name); users.put(id, user); return true; } public Boolean addUser(User user) { if (users.containsKey(user.getId())) { return false; } users.put(user.getId(), user); return true; } public boolean remove(User u) { return remove(u.getId()); } public boolean remove(int id) { if (users.containsKey(id)) { return false; } users.remove(id); return true; } public User find(int id) { return users.get(id); }} /** This class represents the Display, which is responsible * for displaying the book, it's pages and contents. It also * shows the current user. * It provides the method* turnPageForward, turnPageBackward, refreshPage etc.*/ class Display { private Book activeBook; private User activeUser; private int pageNumber = 0; public void displayUser(User user) { activeUser = user; refreshUsername(); } public void displayBook(Book book) { pageNumber = 0; activeBook = book; refreshTitle(); refreshDetails(); refreshPage(); } public void turnPageForward() { pageNumber++; System.out.println("Turning forward to page no " + pageNumber + " of book having title " + activeBook.getTitle()); refreshPage(); } public void turnPageBackward() { pageNumber--; System.out.println("Turning backward to page no " + pageNumber + " of book having title " + activeBook.getTitle()); refreshPage(); } public void refreshUsername() { /* updates username display */ System.out.println("User name " + activeUser.getName() + " is refreshed"); } public void refreshTitle() { /* updates title display */ System.out.println("Title of the book " + activeBook.getTitle() + " refreshed"); } public void refreshDetails() { /* updates details display */ System.out.println("Details of the book " + activeBook.getTitle() + " refreshed"); } public void refreshPage() { /* updated page display */ System.out.println("Page no " + pageNumber + " refreshed"); }} /* * The classes for User and Book simply hold data and * provide little functionality.* This class represents the Book which is a simple POJO*/ class Book { private int bookId; private String details; private String title; public Book(int id, String details, String title) { bookId = id; this.details = details; this.title = title; } public int getId() { return bookId; } public void setId(int id) { bookId = id; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }} /** This class represents the User which is a simple POJO*/ class User { private int userId; private String name; private String details; public void renewMembership() { } public User(int id, String details, String name) { this.userId = id; this.details = details; this.name = name; } public int getId() { return userId; } public void setId(int id) { userId = id; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getName() { return name; } public void setName(String name) { this.name = name; }} // This class is used to test the Application public class AppTest { public static void main(String[] args) { OnlineReaderSystem onlineReaderSystem = new OnlineReaderSystem(); Book dsBook = new Book(1, "It contains Data Structures", "Ds"); Book algoBook = new Book(2, "It contains Algorithms", "Algo"); onlineReaderSystem.getLibrary().addBook(dsBook); onlineReaderSystem.getLibrary().addBook(algoBook); User user1 = new User(1, " ", "Ram"); User user2 = new User(2, " ", "Gopal"); onlineReaderSystem.getUserManager().addUser(user1); onlineReaderSystem.getUserManager().addUser(user2); onlineReaderSystem.setActiveBook(algoBook); onlineReaderSystem.setActiveUser(user1); onlineReaderSystem.getDisplay().turnPageForward(); onlineReaderSystem.getDisplay().turnPageForward(); onlineReaderSystem.getDisplay().turnPageBackward(); }}
using System;using System.Collections.Generic; /** This class represents the system*/ class OnlineReaderSystem{ private Library library; private UserManager userManager; private Display display; private Book activeBook; private User activeUser; public OnlineReaderSystem() { userManager = new UserManager(); library = new Library(); display = new Display(); } public Library getLibrary() { return library; } public UserManager getUserManager() { return userManager; } public Display getDisplay() { return display; } public Book getActiveBook() { return activeBook; } public void setActiveBook(Book book) { activeBook = book; display.displayBook(book); } public User getActiveUser() { return activeUser; } public void setActiveUser(User user) { activeUser = user; display.displayUser(user); }} /** We then implement separate classes to handle the user* manager, the library, and the display components */ /** This class represents the Library which is responsible* for storing and searching the books.*/class Library { private Dictionary<int, Book> books; public Library() { books = new Dictionary<int, Book>(); } public Boolean addBook(int id, String details, String title) { if (books.ContainsKey(id)) { return false; } Book book = new Book(id, details, title); books.Add(id, book); return true; } public Boolean addBook(Book book) { if (books.ContainsKey(book.getId())) { return false; } books.Add(book.getId(), book); return true; } public bool remove(Book b) { return remove(b.getId()); } public bool remove(int id) { if (!books.ContainsKey(id)) { return false; } books.Remove(id); return true; } public Book find(int id) { return books[id]; }} /** This class represents the UserManager * which is responsible for managing the users, * their membership etc.*/class UserManager{ private Dictionary<int, User> users; public UserManager() { users = new Dictionary<int, User>(); } public Boolean addUser(int id, String details, String name) { if (users.ContainsKey(id)) { return false; } User user = new User(id, details, name); users.Add(id, user); return true; } public Boolean addUser(User user) { if (users.ContainsKey(user.getId())) { return false; } users.Add(user.getId(), user); return true; } public bool remove(User u) { return remove(u.getId()); } public bool remove(int id) { if (users.ContainsKey(id)) { return false; } users.Remove(id); return true; } public User find(int id) { return users[id]; }} /** This class represents the Display, which is responsible * for displaying the book, it's pages and contents. * It also shows the current user. * It provides the method* turnPageForward, turnPageBackward, refreshPage etc.*/class Display{ private Book activeBook; private User activeUser; private int pageNumber = 0; public void displayUser(User user) { activeUser = user; refreshUsername(); } public void displayBook(Book book) { pageNumber = 0; activeBook = book; refreshTitle(); refreshDetails(); refreshPage(); } public void turnPageForward() { pageNumber++; Console.WriteLine("Turning forward to page no " + pageNumber + " of book having title " + activeBook.getTitle()); refreshPage(); } public void turnPageBackward() { pageNumber--; Console.WriteLine("Turning backward to page no " + pageNumber + " of book having title " + activeBook.getTitle()); refreshPage(); } public void refreshUsername() { /* updates username display */ Console.WriteLine("User name " + activeUser.getName() + " is refreshed"); } public void refreshTitle() { /* updates title display */ Console.WriteLine("Title of the book " + activeBook.getTitle() + " refreshed"); } public void refreshDetails() { /* updates details display */ Console.WriteLine("Details of the book " + activeBook.getTitle() + " refreshed"); } public void refreshPage() { /* updated page display */ Console.WriteLine("Page no " + pageNumber + " refreshed"); }} /* * The classes for User and Book simply hold data * and provide little functionality.* This class represents the Book which is * a simple POJO*/class Book{ private int bookId; private String details; private String title; public Book(int id, String details, String title) { bookId = id; this.details = details; this.title = title; } public int getId() { return bookId; } public void setId(int id) { bookId = id; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }} /** This class represents the User * which is a simple POJO*/class User{ private int userId; private String name; private String details; public void renewMembership() { } public User(int id, String details, String name) { this.userId = id; this.details = details; this.name = name; } public int getId() { return userId; } public void setId(int id) { userId = id; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getName() { return name; } public void setName(String name) { this.name = name; }} // This class is used to test the Applicationpublic class AppTest{ public static void Main(String[] args) { OnlineReaderSystem onlineReaderSystem = new OnlineReaderSystem(); Book dsBook = new Book(1, "It contains Data Structures", "Ds"); Book algoBook = new Book(2, "It contains Algorithms", "Algo"); onlineReaderSystem.getLibrary().addBook(dsBook); onlineReaderSystem.getLibrary().addBook(algoBook); User user1 = new User(1, " ", "Ram"); User user2 = new User(2, " ", "Gopal"); onlineReaderSystem.getUserManager().addUser(user1); onlineReaderSystem.getUserManager().addUser(user2); onlineReaderSystem.setActiveBook(algoBook); onlineReaderSystem.setActiveUser(user1); onlineReaderSystem.getDisplay().turnPageForward(); onlineReaderSystem.getDisplay().turnPageForward(); onlineReaderSystem.getDisplay().turnPageBackward(); }} // This code is contributed by 29AjayKumar
Want to get a Software Developer/Engineer job at a leading tech company? or Want to make a smooth transition from SDE I to SDE II or Senior Developer profiles? If yes, then you’re required to dive deep into the System Design world! A decent command over System Design concepts is very much essential, especially for the working professionals, to get a much-needed advantage over others during tech interviews.
And that’s why, GeeksforGeeks is providing you with an in-depth interview-centric System Design – Live Course that will help you prepare for the questions related to System Designs for Google, Amazon, Adobe, Uber, and other product-based companies.
29AjayKumar
Object-Oriented-Design
Design Pattern
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
Factory method design pattern in Java
Builder Design Pattern
MVC Design Pattern
Java Singleton Design Pattern Practices with Examples
Roadmap to Become a Web Developer in 2022
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Socket Programming in C/C++
DSA Sheet by Love Babbar
GET and POST requests using Python
|
[
{
"code": null,
"e": 25068,
"s": 25040,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 25130,
"s": 25068,
"text": "Design an online book reader system (Object-Oriented Design)."
},
{
"code": null,
"e": 25184,
"s": 25130,
"text": "Asked In: Amazon, Microsoft, and many more interviews"
},
{
"code": null,
"e": 25298,
"s": 25184,
"text": "Solution: Let’s assume we want to design a basic online reading system that provides the following functionality:"
},
{
"code": null,
"e": 25463,
"s": 25298,
"text": "• Searching the database of books and reading a book.• User membership creation and extension.• Only one active user at a time and only one active book by this user"
},
{
"code": null,
"e": 25806,
"s": 25463,
"text": "The class OnlineReaderSystem represents the body of our program. We could implementthe class such that it stores information about all the books deals with user management and refreshes the display, but that would make this class rather hefty. Instead, we’ve chosen to tear off these components into Library, UserManager, and Display classes."
},
{
"code": null,
"e": 25819,
"s": 25806,
"text": "The classes:"
},
{
"code": null,
"e": 25889,
"s": 25819,
"text": "1. User2. Book3. Library4. UserManager5. Display6. OnlineReaderSystem"
},
{
"code": null,
"e": 25916,
"s": 25889,
"text": "Full code is given below :"
},
{
"code": null,
"e": 25921,
"s": 25916,
"text": "Java"
},
{
"code": null,
"e": 25924,
"s": 25921,
"text": "C#"
},
{
"code": "import java.util.HashMap; /** This class represents the system*/ class OnlineReaderSystem { private Library library; private UserManager userManager; private Display display; private Book activeBook; private User activeUser; public OnlineReaderSystem() { userManager = new UserManager(); library = new Library(); display = new Display(); } public Library getLibrary() { return library; } public UserManager getUserManager() { return userManager; } public Display getDisplay() { return display; } public Book getActiveBook() { return activeBook; } public void setActiveBook(Book book) { activeBook = book; display.displayBook(book); } public User getActiveUser() { return activeUser; } public void setActiveUser(User user) { activeUser = user; display.displayUser(user); }} /** We then implement separate classes to handle the user* manager, the library, and the display components */ /** This class represents the Library which is responsible* for storing and searching the books.*/class Library { private HashMap<Integer, Book> books; public Library() { books = new HashMap<Integer, Book>(); } public Boolean addBook(int id, String details, String title) { if (books.containsKey(id)) { return false; } Book book = new Book(id, details, title); books.put(id, book); return true; } public Boolean addBook(Book book) { if (books.containsKey(book.getId())) { return false; } books.put(book.getId(), book); return true; } public boolean remove(Book b) { return remove(b.getId()); } public boolean remove(int id) { if (!books.containsKey(id)) { return false; } books.remove(id); return true; } public Book find(int id) { return books.get(id); }} /** This class represents the UserManager which is responsible * for managing the users, their membership etc.*/ class UserManager { private HashMap<Integer, User> users; public UserManager() { users = new HashMap<Integer, User>(); } public Boolean addUser(int id, String details, String name) { if (users.containsKey(id)) { return false; } User user = new User(id, details, name); users.put(id, user); return true; } public Boolean addUser(User user) { if (users.containsKey(user.getId())) { return false; } users.put(user.getId(), user); return true; } public boolean remove(User u) { return remove(u.getId()); } public boolean remove(int id) { if (users.containsKey(id)) { return false; } users.remove(id); return true; } public User find(int id) { return users.get(id); }} /** This class represents the Display, which is responsible * for displaying the book, it's pages and contents. It also * shows the current user. * It provides the method* turnPageForward, turnPageBackward, refreshPage etc.*/ class Display { private Book activeBook; private User activeUser; private int pageNumber = 0; public void displayUser(User user) { activeUser = user; refreshUsername(); } public void displayBook(Book book) { pageNumber = 0; activeBook = book; refreshTitle(); refreshDetails(); refreshPage(); } public void turnPageForward() { pageNumber++; System.out.println(\"Turning forward to page no \" + pageNumber + \" of book having title \" + activeBook.getTitle()); refreshPage(); } public void turnPageBackward() { pageNumber--; System.out.println(\"Turning backward to page no \" + pageNumber + \" of book having title \" + activeBook.getTitle()); refreshPage(); } public void refreshUsername() { /* updates username display */ System.out.println(\"User name \" + activeUser.getName() + \" is refreshed\"); } public void refreshTitle() { /* updates title display */ System.out.println(\"Title of the book \" + activeBook.getTitle() + \" refreshed\"); } public void refreshDetails() { /* updates details display */ System.out.println(\"Details of the book \" + activeBook.getTitle() + \" refreshed\"); } public void refreshPage() { /* updated page display */ System.out.println(\"Page no \" + pageNumber + \" refreshed\"); }} /* * The classes for User and Book simply hold data and * provide little functionality.* This class represents the Book which is a simple POJO*/ class Book { private int bookId; private String details; private String title; public Book(int id, String details, String title) { bookId = id; this.details = details; this.title = title; } public int getId() { return bookId; } public void setId(int id) { bookId = id; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }} /** This class represents the User which is a simple POJO*/ class User { private int userId; private String name; private String details; public void renewMembership() { } public User(int id, String details, String name) { this.userId = id; this.details = details; this.name = name; } public int getId() { return userId; } public void setId(int id) { userId = id; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getName() { return name; } public void setName(String name) { this.name = name; }} // This class is used to test the Application public class AppTest { public static void main(String[] args) { OnlineReaderSystem onlineReaderSystem = new OnlineReaderSystem(); Book dsBook = new Book(1, \"It contains Data Structures\", \"Ds\"); Book algoBook = new Book(2, \"It contains Algorithms\", \"Algo\"); onlineReaderSystem.getLibrary().addBook(dsBook); onlineReaderSystem.getLibrary().addBook(algoBook); User user1 = new User(1, \" \", \"Ram\"); User user2 = new User(2, \" \", \"Gopal\"); onlineReaderSystem.getUserManager().addUser(user1); onlineReaderSystem.getUserManager().addUser(user2); onlineReaderSystem.setActiveBook(algoBook); onlineReaderSystem.setActiveUser(user1); onlineReaderSystem.getDisplay().turnPageForward(); onlineReaderSystem.getDisplay().turnPageForward(); onlineReaderSystem.getDisplay().turnPageBackward(); }}",
"e": 33310,
"s": 25924,
"text": null
},
{
"code": "using System;using System.Collections.Generic; /** This class represents the system*/ class OnlineReaderSystem{ private Library library; private UserManager userManager; private Display display; private Book activeBook; private User activeUser; public OnlineReaderSystem() { userManager = new UserManager(); library = new Library(); display = new Display(); } public Library getLibrary() { return library; } public UserManager getUserManager() { return userManager; } public Display getDisplay() { return display; } public Book getActiveBook() { return activeBook; } public void setActiveBook(Book book) { activeBook = book; display.displayBook(book); } public User getActiveUser() { return activeUser; } public void setActiveUser(User user) { activeUser = user; display.displayUser(user); }} /** We then implement separate classes to handle the user* manager, the library, and the display components */ /** This class represents the Library which is responsible* for storing and searching the books.*/class Library { private Dictionary<int, Book> books; public Library() { books = new Dictionary<int, Book>(); } public Boolean addBook(int id, String details, String title) { if (books.ContainsKey(id)) { return false; } Book book = new Book(id, details, title); books.Add(id, book); return true; } public Boolean addBook(Book book) { if (books.ContainsKey(book.getId())) { return false; } books.Add(book.getId(), book); return true; } public bool remove(Book b) { return remove(b.getId()); } public bool remove(int id) { if (!books.ContainsKey(id)) { return false; } books.Remove(id); return true; } public Book find(int id) { return books[id]; }} /** This class represents the UserManager * which is responsible for managing the users, * their membership etc.*/class UserManager{ private Dictionary<int, User> users; public UserManager() { users = new Dictionary<int, User>(); } public Boolean addUser(int id, String details, String name) { if (users.ContainsKey(id)) { return false; } User user = new User(id, details, name); users.Add(id, user); return true; } public Boolean addUser(User user) { if (users.ContainsKey(user.getId())) { return false; } users.Add(user.getId(), user); return true; } public bool remove(User u) { return remove(u.getId()); } public bool remove(int id) { if (users.ContainsKey(id)) { return false; } users.Remove(id); return true; } public User find(int id) { return users[id]; }} /** This class represents the Display, which is responsible * for displaying the book, it's pages and contents. * It also shows the current user. * It provides the method* turnPageForward, turnPageBackward, refreshPage etc.*/class Display{ private Book activeBook; private User activeUser; private int pageNumber = 0; public void displayUser(User user) { activeUser = user; refreshUsername(); } public void displayBook(Book book) { pageNumber = 0; activeBook = book; refreshTitle(); refreshDetails(); refreshPage(); } public void turnPageForward() { pageNumber++; Console.WriteLine(\"Turning forward to page no \" + pageNumber + \" of book having title \" + activeBook.getTitle()); refreshPage(); } public void turnPageBackward() { pageNumber--; Console.WriteLine(\"Turning backward to page no \" + pageNumber + \" of book having title \" + activeBook.getTitle()); refreshPage(); } public void refreshUsername() { /* updates username display */ Console.WriteLine(\"User name \" + activeUser.getName() + \" is refreshed\"); } public void refreshTitle() { /* updates title display */ Console.WriteLine(\"Title of the book \" + activeBook.getTitle() + \" refreshed\"); } public void refreshDetails() { /* updates details display */ Console.WriteLine(\"Details of the book \" + activeBook.getTitle() + \" refreshed\"); } public void refreshPage() { /* updated page display */ Console.WriteLine(\"Page no \" + pageNumber + \" refreshed\"); }} /* * The classes for User and Book simply hold data * and provide little functionality.* This class represents the Book which is * a simple POJO*/class Book{ private int bookId; private String details; private String title; public Book(int id, String details, String title) { bookId = id; this.details = details; this.title = title; } public int getId() { return bookId; } public void setId(int id) { bookId = id; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }} /** This class represents the User * which is a simple POJO*/class User{ private int userId; private String name; private String details; public void renewMembership() { } public User(int id, String details, String name) { this.userId = id; this.details = details; this.name = name; } public int getId() { return userId; } public void setId(int id) { userId = id; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getName() { return name; } public void setName(String name) { this.name = name; }} // This class is used to test the Applicationpublic class AppTest{ public static void Main(String[] args) { OnlineReaderSystem onlineReaderSystem = new OnlineReaderSystem(); Book dsBook = new Book(1, \"It contains Data Structures\", \"Ds\"); Book algoBook = new Book(2, \"It contains Algorithms\", \"Algo\"); onlineReaderSystem.getLibrary().addBook(dsBook); onlineReaderSystem.getLibrary().addBook(algoBook); User user1 = new User(1, \" \", \"Ram\"); User user2 = new User(2, \" \", \"Gopal\"); onlineReaderSystem.getUserManager().addUser(user1); onlineReaderSystem.getUserManager().addUser(user2); onlineReaderSystem.setActiveBook(algoBook); onlineReaderSystem.setActiveUser(user1); onlineReaderSystem.getDisplay().turnPageForward(); onlineReaderSystem.getDisplay().turnPageForward(); onlineReaderSystem.getDisplay().turnPageBackward(); }} // This code is contributed by 29AjayKumar",
"e": 40999,
"s": 33310,
"text": null
},
{
"code": null,
"e": 41409,
"s": 40999,
"text": "Want to get a Software Developer/Engineer job at a leading tech company? or Want to make a smooth transition from SDE I to SDE II or Senior Developer profiles? If yes, then you’re required to dive deep into the System Design world! A decent command over System Design concepts is very much essential, especially for the working professionals, to get a much-needed advantage over others during tech interviews."
},
{
"code": null,
"e": 41658,
"s": 41409,
"text": "And that’s why, GeeksforGeeks is providing you with an in-depth interview-centric System Design – Live Course that will help you prepare for the questions related to System Designs for Google, Amazon, Adobe, Uber, and other product-based companies."
},
{
"code": null,
"e": 41670,
"s": 41658,
"text": "29AjayKumar"
},
{
"code": null,
"e": 41693,
"s": 41670,
"text": "Object-Oriented-Design"
},
{
"code": null,
"e": 41708,
"s": 41693,
"text": "Design Pattern"
},
{
"code": null,
"e": 41714,
"s": 41708,
"text": "GBlog"
},
{
"code": null,
"e": 41812,
"s": 41714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41861,
"s": 41812,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 41899,
"s": 41861,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 41922,
"s": 41899,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 41941,
"s": 41922,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 41995,
"s": 41941,
"text": "Java Singleton Design Pattern Practices with Examples"
},
{
"code": null,
"e": 42037,
"s": 41995,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 42111,
"s": 42037,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 42139,
"s": 42111,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 42164,
"s": 42139,
"text": "DSA Sheet by Love Babbar"
}
] |
Extracting headers and paragraphs from pdf using PyMuPDF | by Louis de Bruijn | Towards Data Science
|
Here’s for something completely different: parsing pdf documents and extracting the headers and paragraphs! There are various packages that extract text from pdf documents and convert them to HTML, but I’ve found these to be either too elaborate for the task at hand and/or too complex. In my experience, generic pdf parsers generalize okay-ish over all documents, but for a specific use-case of somewhat similarly structured documents, we can enhance performance with some code of our own!
Since pdf files consist of unstructured text, we need to find some similarities over the different documents on how headers and paragraphs are separated. Using a small sample of large (50–150 pages each) pdf files concerning Dutch policy terms for insurers, what I’ve found somewhat consistently is that headers and paragraphs are often separated by the font size and font weight of the text and that the most used font can be considered the paragraph. Now, this is a good starting point for us to create a methodology.
Use PyMuPDF to identify the paragraphs as text with the most used font in the document, headers as anything larger, and subscripts as anything smaller than the paragraph style.Create a dictionary with HTML style element tags such as <h1>, <p> and <s0> for the headers, paragraphs, and subscripts.Annotate pieces of text with these element <tags>.
Use PyMuPDF to identify the paragraphs as text with the most used font in the document, headers as anything larger, and subscripts as anything smaller than the paragraph style.
Create a dictionary with HTML style element tags such as <h1>, <p> and <s0> for the headers, paragraphs, and subscripts.
Annotate pieces of text with these element <tags>.
We’re using the PyMuPDF package for reading the pdf files. This package opens pdf documents page per page and saves all its content in a block and identifies the text size, font, colour and flags. What I’ve found is that some pdf documents discriminate headers and paragraphs only by the font and size, but others use all four attributes. To account for this, we’re going to add a granularity flag so that we can decide which attributes to incorporate in the distinction of the different textual parts in the document.
At this stage, we’re going to create a dictionary with all the different styles and attributes and a list of [(font_size, count), ..] for all these styles.
We iterate over the pages and blocks of the document, which is parsed by the PyMuPDF package (imported as fitz) and identify all the styles and attributes according to our granularity flag.
Output for one of our documents looks like this:
font_counts, styles = fonts(doc, granularity=False)[('9.5', 1079), ('10.0', 190), ('8.5', 28), ('10.5', 24), ...]{'12.0': {'size': 12.0, 'font': 'ArialMT'}, '9.0': {'size': 9.0, 'font': 'XKZKVH+VAGRoundedStd-Light'}, ...}
We can see that the most used font-size is 9.5, with a count of 1079 text spans of this size. It is very likely that this font-size represents the paragraphs in our document.
Next up we’re going to create a dictionary with the element tags for each of the font sizes. Note, we’re only considering the font-sizes here, but with a few extra lines of code, you can find a way to incorporate the other attributes if you’re using the granularity=True flag in the fonts() function!
line 12-13 First we’re identifying the paragraph’s size to discriminate between the type of tag <header>, <paragraph> or <subscript>. line 16-19 we’re sorting the sizes high to low so that we can add the correct integer to each element tag. Note that we’re using 1 for the largest tag and this number decreases as the font-sizes decrease for both the headers and subscripts! We’re doing this because it is in the same fashion as the ordering of HTLM tags. line 22-32 populates the dictionary with the tags, which is shown below.
{60.0: '<h1>', 59.69924545288086: '<h2>', 36.0: '<h3>', 30.0: '<h4>', 24.0: '<h5>', 20.0: '<h6>', 16.0: '<h7>', 14.0: '<h8>', 13.0: '<h9>', 10.5: '<h10>', 10.0: '<h11>', 9.5: '<p>', 9.452380180358887: '<s1>', 9.404520988464355: '<s2>', 8.5: '<s3>', 8.0: '<s4>', 7.5: '<s5>', 7.0: '<s6>'}
We again iterate over the pages of the document and the blocks. For the first block, we initialize the block_string with the element tag and the actual text from the span s['text']. For each following span, we check whether the font size matches the previous span’s font size or whether there is a new text size. Accordingly, we concatenate strings if they’re the same size. blocks are parts of text that are separated and identified by the PyMuPDF package, but I’ve found that they sometimes contain parts of a sentence. Hence, why I concatenate them with a '|' delimiting the fact that a new block has started. In post-processing steps, we can then decide what to do with these pipe-delimited parts (concatenate them or separate them).
We return a list of strings with pipes in them and are then able to identify which textual parts are headers, paragraphs, or subscripts, as shown below.
['<h4>Als onderdeel van het | ZekerheidsPakket Particulieren |', '', '<h1>Informatie over uw|', '<h2>Inboedelverzekering|', '<h1>Basis|', '', '<h6>Inhoud|', '', '<p>pagina| Leeswijzer, Uw verzekering in het kort | 3 | Polisvoorwaarden Inboedelverzekering Basis | 7 |', '', '<s3>3|', '', '<h7>Uw verzekering in het kort|',
As you can see we still need to perform several post-processing steps to clean the data and maybe order it in a different way, but this is at least a starting point. I hope you’ve learned something here and happy coding! The full script and example pdf document can be found here.
|
[
{
"code": null,
"e": 662,
"s": 171,
"text": "Here’s for something completely different: parsing pdf documents and extracting the headers and paragraphs! There are various packages that extract text from pdf documents and convert them to HTML, but I’ve found these to be either too elaborate for the task at hand and/or too complex. In my experience, generic pdf parsers generalize okay-ish over all documents, but for a specific use-case of somewhat similarly structured documents, we can enhance performance with some code of our own!"
},
{
"code": null,
"e": 1182,
"s": 662,
"text": "Since pdf files consist of unstructured text, we need to find some similarities over the different documents on how headers and paragraphs are separated. Using a small sample of large (50–150 pages each) pdf files concerning Dutch policy terms for insurers, what I’ve found somewhat consistently is that headers and paragraphs are often separated by the font size and font weight of the text and that the most used font can be considered the paragraph. Now, this is a good starting point for us to create a methodology."
},
{
"code": null,
"e": 1529,
"s": 1182,
"text": "Use PyMuPDF to identify the paragraphs as text with the most used font in the document, headers as anything larger, and subscripts as anything smaller than the paragraph style.Create a dictionary with HTML style element tags such as <h1>, <p> and <s0> for the headers, paragraphs, and subscripts.Annotate pieces of text with these element <tags>."
},
{
"code": null,
"e": 1706,
"s": 1529,
"text": "Use PyMuPDF to identify the paragraphs as text with the most used font in the document, headers as anything larger, and subscripts as anything smaller than the paragraph style."
},
{
"code": null,
"e": 1827,
"s": 1706,
"text": "Create a dictionary with HTML style element tags such as <h1>, <p> and <s0> for the headers, paragraphs, and subscripts."
},
{
"code": null,
"e": 1878,
"s": 1827,
"text": "Annotate pieces of text with these element <tags>."
},
{
"code": null,
"e": 2397,
"s": 1878,
"text": "We’re using the PyMuPDF package for reading the pdf files. This package opens pdf documents page per page and saves all its content in a block and identifies the text size, font, colour and flags. What I’ve found is that some pdf documents discriminate headers and paragraphs only by the font and size, but others use all four attributes. To account for this, we’re going to add a granularity flag so that we can decide which attributes to incorporate in the distinction of the different textual parts in the document."
},
{
"code": null,
"e": 2553,
"s": 2397,
"text": "At this stage, we’re going to create a dictionary with all the different styles and attributes and a list of [(font_size, count), ..] for all these styles."
},
{
"code": null,
"e": 2743,
"s": 2553,
"text": "We iterate over the pages and blocks of the document, which is parsed by the PyMuPDF package (imported as fitz) and identify all the styles and attributes according to our granularity flag."
},
{
"code": null,
"e": 2792,
"s": 2743,
"text": "Output for one of our documents looks like this:"
},
{
"code": null,
"e": 3014,
"s": 2792,
"text": "font_counts, styles = fonts(doc, granularity=False)[('9.5', 1079), ('10.0', 190), ('8.5', 28), ('10.5', 24), ...]{'12.0': {'size': 12.0, 'font': 'ArialMT'}, '9.0': {'size': 9.0, 'font': 'XKZKVH+VAGRoundedStd-Light'}, ...}"
},
{
"code": null,
"e": 3189,
"s": 3014,
"text": "We can see that the most used font-size is 9.5, with a count of 1079 text spans of this size. It is very likely that this font-size represents the paragraphs in our document."
},
{
"code": null,
"e": 3490,
"s": 3189,
"text": "Next up we’re going to create a dictionary with the element tags for each of the font sizes. Note, we’re only considering the font-sizes here, but with a few extra lines of code, you can find a way to incorporate the other attributes if you’re using the granularity=True flag in the fonts() function!"
},
{
"code": null,
"e": 4019,
"s": 3490,
"text": "line 12-13 First we’re identifying the paragraph’s size to discriminate between the type of tag <header>, <paragraph> or <subscript>. line 16-19 we’re sorting the sizes high to low so that we can add the correct integer to each element tag. Note that we’re using 1 for the largest tag and this number decreases as the font-sizes decrease for both the headers and subscripts! We’re doing this because it is in the same fashion as the ordering of HTLM tags. line 22-32 populates the dictionary with the tags, which is shown below."
},
{
"code": null,
"e": 4307,
"s": 4019,
"text": "{60.0: '<h1>', 59.69924545288086: '<h2>', 36.0: '<h3>', 30.0: '<h4>', 24.0: '<h5>', 20.0: '<h6>', 16.0: '<h7>', 14.0: '<h8>', 13.0: '<h9>', 10.5: '<h10>', 10.0: '<h11>', 9.5: '<p>', 9.452380180358887: '<s1>', 9.404520988464355: '<s2>', 8.5: '<s3>', 8.0: '<s4>', 7.5: '<s5>', 7.0: '<s6>'}"
},
{
"code": null,
"e": 5045,
"s": 4307,
"text": "We again iterate over the pages of the document and the blocks. For the first block, we initialize the block_string with the element tag and the actual text from the span s['text']. For each following span, we check whether the font size matches the previous span’s font size or whether there is a new text size. Accordingly, we concatenate strings if they’re the same size. blocks are parts of text that are separated and identified by the PyMuPDF package, but I’ve found that they sometimes contain parts of a sentence. Hence, why I concatenate them with a '|' delimiting the fact that a new block has started. In post-processing steps, we can then decide what to do with these pipe-delimited parts (concatenate them or separate them)."
},
{
"code": null,
"e": 5198,
"s": 5045,
"text": "We return a list of strings with pipes in them and are then able to identify which textual parts are headers, paragraphs, or subscripts, as shown below."
},
{
"code": null,
"e": 5522,
"s": 5198,
"text": "['<h4>Als onderdeel van het | ZekerheidsPakket Particulieren |', '', '<h1>Informatie over uw|', '<h2>Inboedelverzekering|', '<h1>Basis|', '', '<h6>Inhoud|', '', '<p>pagina| Leeswijzer, Uw verzekering in het kort | 3 | Polisvoorwaarden Inboedelverzekering Basis | 7 |', '', '<s3>3|', '', '<h7>Uw verzekering in het kort|',"
}
] |
Swift - if...else if...else Statement
|
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if, else if, else statements, there are a few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
The syntax of an if...else if...else statement in Swift is as follows −
if boolean_expression_1 {
/* Executes when the boolean expression 1 is true */
} else if boolean_expression_2 {
/* Executes when the boolean expression 2 is true */
} else if boolean_expression_3 {
/* Executes when the boolean expression 3 is true */
} else {
/* Executes when the none of the above condition is true */
}
import Cocoa
var varA:Int = 100;
/* Check the boolean condition using if statement */
if varA == 20 {
/* If condition is true then print the following */
println("varA is equal to than 20");
} else if varA == 50 {
/* If condition is true then print the following */
println("varA is equal to than 50");
} else {
/* If condition is false then print the following */
println("None of the values is matching");
}
println("Value of variable varA is \(varA)");
When the above code is compiled and executed, it produces the following result −
None of the values is matching
Value of variable varA is 100
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2411,
"s": 2253,
"text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement."
},
{
"code": null,
"e": 2492,
"s": 2411,
"text": "When using if, else if, else statements, there are a few points to keep in mind."
},
{
"code": null,
"e": 2564,
"s": 2492,
"text": "An if can have zero or one else's and it must come after any else if's."
},
{
"code": null,
"e": 2638,
"s": 2564,
"text": "An if can have zero to many else if's and they must come before the else."
},
{
"code": null,
"e": 2722,
"s": 2638,
"text": "Once an else if succeeds, none of the remaining else if's or else's will be tested."
},
{
"code": null,
"e": 2794,
"s": 2722,
"text": "The syntax of an if...else if...else statement in Swift is as follows −"
},
{
"code": null,
"e": 3129,
"s": 2794,
"text": "if boolean_expression_1 {\n /* Executes when the boolean expression 1 is true */\n} else if boolean_expression_2 {\n /* Executes when the boolean expression 2 is true */\n} else if boolean_expression_3 {\n /* Executes when the boolean expression 3 is true */\n} else {\n /* Executes when the none of the above condition is true */\n}\n"
},
{
"code": null,
"e": 3605,
"s": 3129,
"text": "import Cocoa\n\nvar varA:Int = 100;\n\n/* Check the boolean condition using if statement */\nif varA == 20 {\n /* If condition is true then print the following */\n println(\"varA is equal to than 20\");\n} else if varA == 50 {\n /* If condition is true then print the following */\n println(\"varA is equal to than 50\");\n} else {\n /* If condition is false then print the following */\n println(\"None of the values is matching\");\n}\nprintln(\"Value of variable varA is \\(varA)\");"
},
{
"code": null,
"e": 3686,
"s": 3605,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3748,
"s": 3686,
"text": "None of the values is matching\nValue of variable varA is 100\n"
},
{
"code": null,
"e": 3781,
"s": 3748,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3796,
"s": 3781,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 3829,
"s": 3796,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3848,
"s": 3829,
"text": " Three Millennials"
},
{
"code": null,
"e": 3880,
"s": 3848,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3899,
"s": 3880,
"text": " Three Millennials"
},
{
"code": null,
"e": 3932,
"s": 3899,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3949,
"s": 3932,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3981,
"s": 3949,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 4001,
"s": 3981,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 4036,
"s": 4001,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4053,
"s": 4036,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 4060,
"s": 4053,
"text": " Print"
},
{
"code": null,
"e": 4071,
"s": 4060,
"text": " Add Notes"
}
] |
strpbrk() in C++
|
This is a string function in C++ that takes in two strings and finds the first occurrence of any character of string2 in string1. It returns the pointer to the character in string1 if there is any, otherwise returns NULL. This is not applicable for terminating NULL characters.
The syntax of strpbrk() is given as follows −
char *strpbrk(const char *str1, const char *str2)
In the above syntax, strpbrk() returns the pointer to the first character in str1 that matches any character in str2.
A program that demonstrates strpbrk() is given as follows.
Live Demo
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[20] = "aeroplane";
char str2[20] = "fun";
char *c;
c = strpbrk(str1, str2);
if (c != 0)
cout<<"First matching character in str1 is "<< *c <<" at position "<< c-str1+1;
else
printf("Character not found");
return 0;
}
First matching character in str1 is n at position 8
In the above program, first the two strings str1 and str2 are defined. The pointer to a character in str1 that is returned by strpbrk() is stored in c. If the value of c is not 0, then the character and its position in str1 is displayed. Otherwise, the character is not there in str1. This is demonstrated by the following code snippet.
char str1[20] = "aeroplane";
char str2[20] = "fun";
char *c;
c = strpbrk(str1, str2);
if (c != 0)
cout<<"First matching character in str1 is "<<*c <<" at position "<< c-str1+1;
else
printf("Character not found");
|
[
{
"code": null,
"e": 1340,
"s": 1062,
"text": "This is a string function in C++ that takes in two strings and finds the first occurrence of any character of string2 in string1. It returns the pointer to the character in string1 if there is any, otherwise returns NULL. This is not applicable for terminating NULL characters."
},
{
"code": null,
"e": 1386,
"s": 1340,
"text": "The syntax of strpbrk() is given as follows −"
},
{
"code": null,
"e": 1436,
"s": 1386,
"text": "char *strpbrk(const char *str1, const char *str2)"
},
{
"code": null,
"e": 1554,
"s": 1436,
"text": "In the above syntax, strpbrk() returns the pointer to the first character in str1 that matches any character in str2."
},
{
"code": null,
"e": 1613,
"s": 1554,
"text": "A program that demonstrates strpbrk() is given as follows."
},
{
"code": null,
"e": 1624,
"s": 1613,
"text": " Live Demo"
},
{
"code": null,
"e": 1950,
"s": 1624,
"text": "#include <iostream>\n#include <cstring>\nusing namespace std;\nint main() {\n char str1[20] = \"aeroplane\";\n char str2[20] = \"fun\";\n char *c;\n c = strpbrk(str1, str2);\n if (c != 0)\n cout<<\"First matching character in str1 is \"<< *c <<\" at position \"<< c-str1+1;\n else\n printf(\"Character not found\");\n return 0;\n}"
},
{
"code": null,
"e": 2002,
"s": 1950,
"text": "First matching character in str1 is n at position 8"
},
{
"code": null,
"e": 2339,
"s": 2002,
"text": "In the above program, first the two strings str1 and str2 are defined. The pointer to a character in str1 that is returned by strpbrk() is stored in c. If the value of c is not 0, then the character and its position in str1 is displayed. Otherwise, the character is not there in str1. This is demonstrated by the following code snippet."
},
{
"code": null,
"e": 2552,
"s": 2339,
"text": "char str1[20] = \"aeroplane\";\nchar str2[20] = \"fun\";\nchar *c;\nc = strpbrk(str1, str2);\nif (c != 0)\ncout<<\"First matching character in str1 is \"<<*c <<\" at position \"<< c-str1+1;\nelse\nprintf(\"Character not found\");"
}
] |
How to find minimum element in an array using binary search in C language?
|
C programming language provides two types of searching techniques. They are as follows −
Linear search
Binary search
This method can be applied only to sorted list.
The given list is divided into two equal parts.
The given key is compared with the middle element of the list.
Here, three situations may occur, which are as follows −
If the middle element matches the key, then the search will end successfully here
If the middle element matches the key, then the search will end successfully here
If the middle element is greater than the key, then the search will proceed in the left partition.
If the middle element is greater than the key, then the search will proceed in the left partition.
If the middle element is lower than the key, then the search will proceed in the right partition.
If the middle element is lower than the key, then the search will proceed in the right partition.
Input (i/p) − Unsorted list of elements, key.
Output (o/p) −
Success – If key is found
Unsuccessful – Otherwise
key = 20
mid = (low +high) /2
Following is the C program to find the minimum element in an array by using binary search −
#include<stdio.h>
int main(){
int a[50], n, i, key, flag = 0, low, mid, high;
printf("enter the no: of elements:");
scanf ("%d",&n);
printf("enter the elements:");
for(i=0; i<n; i++)
scanf( "%d", &a[i]);
printf("enter a key element:");
scanf ("%d", &key);
low = 0;
high = n-1;
while (low<= high ){
mid = (low + high) /2;
if (a[mid] == key){
flag = 1;
break;
}
else{
if (a[mid] > key)
high = mid-1;
else
low = mid+1;
}
}
if (flag == 1)
printf ("search is successful");
else
printf("search is unsuccessful");
return 0;
}
When the above program is executed, it produces the following result −
Run 1:
enter the no: of elements:5
enter the elements:
12
34
11
56
67
enter a key element:45
search is unsuccessful
Run 2:
enter the no: of elements:3
enter the elements:
12
34
56
enter a key element:34
search is successful
Given below is another C program to find the minimum element in an array by using binary search −
#include<stdio.h>
void Bmin(int *a, int i, int n){
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n){
if (j < n && a[j+1] > a[j])
j = j + 1;
if (temp < a[j])
break;
else if (temp >= a[j]){
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j/2] = temp;
return;
}
int binarysearchmin(int *a,int n){
int i;
for(i = n/2; i >= 1; i--){
Bmin(a,i,n);
}
return a[1];
}
int main(){
int n, i, x, min;
int a[20];
printf("Enter no of elements in an array\n");
scanf("%d", &n);
printf("\nEnter %d elements: ", n);
for (i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
min = binarysearchmin(a, n);
printf("\minimum element in an array is : %d", min);
return 0;
}
When the above program is executed, it produces the following result −
Enter no of elements in an array
5
Enter 5 elements:
12
23
34
45
56
minimum element in an array is: 12
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "C programming language provides two types of searching techniques. They are as follows −"
},
{
"code": null,
"e": 1165,
"s": 1151,
"text": "Linear search"
},
{
"code": null,
"e": 1179,
"s": 1165,
"text": "Binary search"
},
{
"code": null,
"e": 1227,
"s": 1179,
"text": "This method can be applied only to sorted list."
},
{
"code": null,
"e": 1275,
"s": 1227,
"text": "The given list is divided into two equal parts."
},
{
"code": null,
"e": 1338,
"s": 1275,
"text": "The given key is compared with the middle element of the list."
},
{
"code": null,
"e": 1395,
"s": 1338,
"text": "Here, three situations may occur, which are as follows −"
},
{
"code": null,
"e": 1477,
"s": 1395,
"text": "If the middle element matches the key, then the search will end successfully here"
},
{
"code": null,
"e": 1559,
"s": 1477,
"text": "If the middle element matches the key, then the search will end successfully here"
},
{
"code": null,
"e": 1658,
"s": 1559,
"text": "If the middle element is greater than the key, then the search will proceed in the left partition."
},
{
"code": null,
"e": 1757,
"s": 1658,
"text": "If the middle element is greater than the key, then the search will proceed in the left partition."
},
{
"code": null,
"e": 1855,
"s": 1757,
"text": "If the middle element is lower than the key, then the search will proceed in the right partition."
},
{
"code": null,
"e": 1953,
"s": 1855,
"text": "If the middle element is lower than the key, then the search will proceed in the right partition."
},
{
"code": null,
"e": 1999,
"s": 1953,
"text": "Input (i/p) − Unsorted list of elements, key."
},
{
"code": null,
"e": 2014,
"s": 1999,
"text": "Output (o/p) −"
},
{
"code": null,
"e": 2040,
"s": 2014,
"text": "Success – If key is found"
},
{
"code": null,
"e": 2065,
"s": 2040,
"text": "Unsuccessful – Otherwise"
},
{
"code": null,
"e": 2095,
"s": 2065,
"text": "key = 20\nmid = (low +high) /2"
},
{
"code": null,
"e": 2187,
"s": 2095,
"text": "Following is the C program to find the minimum element in an array by using binary search −"
},
{
"code": null,
"e": 2856,
"s": 2187,
"text": "#include<stdio.h>\nint main(){\n int a[50], n, i, key, flag = 0, low, mid, high;\n printf(\"enter the no: of elements:\");\n scanf (\"%d\",&n);\n printf(\"enter the elements:\");\n for(i=0; i<n; i++)\n scanf( \"%d\", &a[i]);\n printf(\"enter a key element:\");\n scanf (\"%d\", &key);\n low = 0;\n high = n-1;\n while (low<= high ){\n mid = (low + high) /2;\n if (a[mid] == key){\n flag = 1;\n break;\n }\n else{\n if (a[mid] > key)\n high = mid-1;\n else\n low = mid+1;\n }\n }\n if (flag == 1)\n printf (\"search is successful\");\n else\n printf(\"search is unsuccessful\");\n return 0;\n}"
},
{
"code": null,
"e": 2927,
"s": 2856,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3151,
"s": 2927,
"text": "Run 1:\nenter the no: of elements:5\nenter the elements:\n12\n34\n11\n56\n67\nenter a key element:45\nsearch is unsuccessful\nRun 2:\nenter the no: of elements:3\nenter the elements:\n12\n34\n56\nenter a key element:34\nsearch is successful"
},
{
"code": null,
"e": 3249,
"s": 3151,
"text": "Given below is another C program to find the minimum element in an array by using binary search −"
},
{
"code": null,
"e": 4013,
"s": 3249,
"text": "#include<stdio.h>\nvoid Bmin(int *a, int i, int n){\n int j, temp;\n temp = a[i];\n j = 2 * i;\n while (j <= n){\n if (j < n && a[j+1] > a[j])\n j = j + 1;\n if (temp < a[j])\n break;\n else if (temp >= a[j]){\n a[j / 2] = a[j];\n j = 2 * j;\n }\n }\n a[j/2] = temp;\n return;\n}\nint binarysearchmin(int *a,int n){\n int i;\n for(i = n/2; i >= 1; i--){\n Bmin(a,i,n);\n }\n return a[1];\n}\nint main(){\n int n, i, x, min;\n int a[20];\n printf(\"Enter no of elements in an array\\n\");\n scanf(\"%d\", &n);\n printf(\"\\nEnter %d elements: \", n);\n for (i = 1; i <= n; i++){\n scanf(\"%d\", &a[i]);\n }\n min = binarysearchmin(a, n);\n printf(\"\\minimum element in an array is : %d\", min);\n return 0;\n}"
},
{
"code": null,
"e": 4084,
"s": 4013,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 4187,
"s": 4084,
"text": "Enter no of elements in an array\n5\nEnter 5 elements:\n12\n23\n34\n45\n56\nminimum element in an array is: 12"
}
] |
Count Number | Practice | GeeksforGeeks
|
Given an array arr consisting of integers of size n and 2 additional integers k and x, you need to find the number of subsets of this array of size k, where Absolute difference between the Maximum and Minimum number of the subset is at most x.
Note: As this number that you need to find can be rather large, print it Modulo 109+7
Example 1:
Input:
n = 5, k = 3, x = 5
arr[] = {1, 2, 3, 4, 5}
Output:
10
Explanation :
Possible subsets of size 3 are :-
{1,2,3} {1,2,4} {1,2,5} {1,3,4}
{1,3,5} {1,4,5} {2,3,4} {2,3,5}
{2,4,5} {3,4,5} having difference
of maximum and minimum
element less than equal to 5.
Example 2:
Input:
n = 8, k = 4, x = 6
arr[] = {2, 4, 6, 8, 10, 12, 14, 16}
Output:
5
Explanation :
Possible subsets of size 4 are:-
{2,4,6,8} {4,6,8,10} {6,8,10,12}
{8,10,12,14} {10,12,14,16} having
difference of maximum and minimum
element less than equal to 6.
Your Task:
You don't have to print anything, printing is done by the driver code itself. Your task is to complete the function getAnswer() which takes the array arr[], its size n and two integers k and x as inputs and returns the required result, Modulo 109+7.
Expected Time Complexity: O(n. log(n))
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 5×105
1 ≤ k ≤ n
1 ≤ arr[i], x ≤ 109
0
Navenkumar Duraisamy
This comment was deleted.
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": 470,
"s": 226,
"text": "Given an array arr consisting of integers of size n and 2 additional integers k and x, you need to find the number of subsets of this array of size k, where Absolute difference between the Maximum and Minimum number of the subset is at most x."
},
{
"code": null,
"e": 556,
"s": 470,
"text": "Note: As this number that you need to find can be rather large, print it Modulo 109+7"
},
{
"code": null,
"e": 569,
"s": 558,
"text": "Example 1:"
},
{
"code": null,
"e": 830,
"s": 569,
"text": "Input:\nn = 5, k = 3, x = 5\narr[] = {1, 2, 3, 4, 5}\nOutput:\n10\nExplanation :\nPossible subsets of size 3 are :-\n{1,2,3} {1,2,4} {1,2,5} {1,3,4}\n{1,3,5} {1,4,5} {2,3,4} {2,3,5}\n{2,4,5} {3,4,5} having difference\nof maximum and minimum\nelement less than equal to 5."
},
{
"code": null,
"e": 843,
"s": 832,
"text": "Example 2:"
},
{
"code": null,
"e": 1096,
"s": 843,
"text": "Input:\nn = 8, k = 4, x = 6\narr[] = {2, 4, 6, 8, 10, 12, 14, 16}\nOutput:\n5\nExplanation :\nPossible subsets of size 4 are:-\n{2,4,6,8} {4,6,8,10} {6,8,10,12}\n{8,10,12,14} {10,12,14,16} having\ndifference of maximum and minimum \nelement less than equal to 6."
},
{
"code": null,
"e": 1359,
"s": 1096,
"text": "\n\nYour Task:\nYou don't have to print anything, printing is done by the driver code itself. Your task is to complete the function getAnswer() which takes the array arr[], its size n and two integers k and x as inputs and returns the required result, Modulo 109+7."
},
{
"code": null,
"e": 1431,
"s": 1361,
"text": "Expected Time Complexity: O(n. log(n))\nExpected Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1490,
"s": 1433,
"text": "Constraints:\n1 ≤ n ≤ 5×105\n1 ≤ k ≤ n\n1 ≤ arr[i], x ≤ 109"
},
{
"code": null,
"e": 1492,
"s": 1490,
"text": "0"
},
{
"code": null,
"e": 1513,
"s": 1492,
"text": "Navenkumar Duraisamy"
},
{
"code": null,
"e": 1539,
"s": 1513,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1685,
"s": 1539,
"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": 1721,
"s": 1685,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 1731,
"s": 1721,
"text": "\nProblem\n"
},
{
"code": null,
"e": 1741,
"s": 1731,
"text": "\nContest\n"
},
{
"code": null,
"e": 1804,
"s": 1741,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 1952,
"s": 1804,
"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": 2160,
"s": 1952,
"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": 2266,
"s": 2160,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
DAX Other - GROUPBY function
|
Returns a table with a set of selected columns. Permits DAX CURRENTGROUP function to be used inside aggregation functions in the extension columns that it adds. GROUPBY attempts to reuse the data that has been grouped making it highly performant.
DAX GROUPBY function is similar to DAX SUMMARIZE function. However, GROUPBY does not do an implicit CALCULATE for any extension columns that it adds.
DAX GROUPBY function is new in Excel 2016.
GROUPBY (<table>, [<groupBy_columnName1>], [<name>, <expression>] ...)
table
Any DAX expression that returns a table of data.
groupBy_columnName1
The name of an existing column in the table (or in a related table), by which the data is to be grouped.
This parameter cannot be an expression.
name
The name given to a new column that is being added to the list of GroupBy columns, enclosed in double quotes.
expression
Any DAX expression that returns a single scalar value, where the expression is to be evaluated for each set of GroupBy values.
It can include any of the “X” aggregation functions, such as SUMX, AVERAGEX, MINX, MAXX, etc. and when one of these functions is used in this way, the table parameter (which is a table expression) can be replaced by CURRENTGROUP function. (Refer Remarks Section for details).
It can include any of the “X” aggregation functions, such as SUMX, AVERAGEX, MINX, MAXX, etc. and when one of these functions is used in this way, the table parameter (which is a table expression) can be replaced by CURRENTGROUP function. (Refer Remarks Section for details).
However, CURRENTGROUP function can only be used at the top level of table scans in the expression. That means,
ABS (SUMX (CURRENTGROUP (), [Column])) is allowed, since ABS does not perform a scan.
But, SUMX (<table>, SUMX (CURRENTGROUP () ...)) is not allowed.
However, CURRENTGROUP function can only be used at the top level of table scans in the expression. That means,
ABS (SUMX (CURRENTGROUP (), [Column])) is allowed, since ABS does not perform a scan.
ABS (SUMX (CURRENTGROUP (), [Column])) is allowed, since ABS does not perform a scan.
But, SUMX (<table>, SUMX (CURRENTGROUP () ...)) is not allowed.
But, SUMX (<table>, SUMX (CURRENTGROUP () ...)) is not allowed.
DAX CALCULATE function and calculated fields are not allowed in the expression
DAX CALCULATE function and calculated fields are not allowed in the expression
A table with the selected columns for the groupBy_columnName parameters and the grouped by columns designated by the name parameters.
The GROUPBY function does the following −
Start with the specified table (and all related tables in the “to-one” direction).
Start with the specified table (and all related tables in the “to-one” direction).
Create a grouping using all of the GroupBy columns (which are required to exist in the table from step 1).
Create a grouping using all of the GroupBy columns (which are required to exist in the table from step 1).
Each group is one row in the result, but represents a set of rows in the original table.
Each group is one row in the result, but represents a set of rows in the original table.
For each group, evaluate the extension columns being added. Unlike the SUMMARIZE function, an implied CALCULATE is not performed, and the group is not placed into the filter context.
For each group, evaluate the extension columns being added. Unlike the SUMMARIZE function, an implied CALCULATE is not performed, and the group is not placed into the filter context.
Each column for which you define a name must have a corresponding expression. Otherwise, an error is returned.
The first parameter, name, defines the name of the column in the results. The second parameter, expression, defines the calculation performed to obtain the value for each row in that column.
Each name must be enclosed in double quotation marks.
Each column for which you define a name must have a corresponding expression. Otherwise, an error is returned.
The first parameter, name, defines the name of the column in the results. The second parameter, expression, defines the calculation performed to obtain the value for each row in that column.
The first parameter, name, defines the name of the column in the results. The second parameter, expression, defines the calculation performed to obtain the value for each row in that column.
Each name must be enclosed in double quotation marks.
Each name must be enclosed in double quotation marks.
groupBy_columnName must be either in a table or in a related table.
The function groups a selected set of rows into a set of summary rows by the values of one or more groupBy_columnName columns. One row is returned for each group.
groupBy_columnName must be either in a table or in a related table.
The function groups a selected set of rows into a set of summary rows by the values of one or more groupBy_columnName columns. One row is returned for each group.
The function groups a selected set of rows into a set of summary rows by the values of one or more groupBy_columnName columns. One row is returned for each group.
CURRENTGROUP function can only be used in an expression that defines a column within the GROUPBY function.
CURRENTGROUP function can only be used in an expression that defines a column within the GROUPBY function.
CURRENTGROUP returns a set of rows from the table parameter of GROUPBY that belong to the current row of the GROUPBY result.
CURRENTGROUP returns a set of rows from the table parameter of GROUPBY that belong to the current row of the GROUPBY result.
CURRENTGROUP function takes no parameters and is only supported as the first parameter to one of the following aggregation functions: AverageX, CountAX, CountX, GeoMeanX, MaxX, MinX, ProductX, StDevX.S, StDevX.P, SumX, VarX.S, VarX.P.
CURRENTGROUP function takes no parameters and is only supported as the first parameter to one of the following aggregation functions: AverageX, CountAX, CountX, GeoMeanX, MaxX, MinX, ProductX, StDevX.S, StDevX.P, SumX, VarX.S, VarX.P.
= GROUPBY (
Sales,Sales[Salesperson],Products[Product],"Total Sales",
SUMX (CURRENTGROUP (),[Sales Amount])
)
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2248,
"s": 2001,
"text": "Returns a table with a set of selected columns. Permits DAX CURRENTGROUP function to be used inside aggregation functions in the extension columns that it adds. GROUPBY attempts to reuse the data that has been grouped making it highly performant."
},
{
"code": null,
"e": 2398,
"s": 2248,
"text": "DAX GROUPBY function is similar to DAX SUMMARIZE function. However, GROUPBY does not do an implicit CALCULATE for any extension columns that it adds."
},
{
"code": null,
"e": 2441,
"s": 2398,
"text": "DAX GROUPBY function is new in Excel 2016."
},
{
"code": null,
"e": 2514,
"s": 2441,
"text": "GROUPBY (<table>, [<groupBy_columnName1>], [<name>, <expression>] ...) \n"
},
{
"code": null,
"e": 2520,
"s": 2514,
"text": "table"
},
{
"code": null,
"e": 2569,
"s": 2520,
"text": "Any DAX expression that returns a table of data."
},
{
"code": null,
"e": 2589,
"s": 2569,
"text": "groupBy_columnName1"
},
{
"code": null,
"e": 2694,
"s": 2589,
"text": "The name of an existing column in the table (or in a related table), by which the data is to be grouped."
},
{
"code": null,
"e": 2734,
"s": 2694,
"text": "This parameter cannot be an expression."
},
{
"code": null,
"e": 2739,
"s": 2734,
"text": "name"
},
{
"code": null,
"e": 2849,
"s": 2739,
"text": "The name given to a new column that is being added to the list of GroupBy columns, enclosed in double quotes."
},
{
"code": null,
"e": 2860,
"s": 2849,
"text": "expression"
},
{
"code": null,
"e": 2987,
"s": 2860,
"text": "Any DAX expression that returns a single scalar value, where the expression is to be evaluated for each set of GroupBy values."
},
{
"code": null,
"e": 3263,
"s": 2987,
"text": "It can include any of the “X” aggregation functions, such as SUMX, AVERAGEX, MINX, MAXX, etc. and when one of these functions is used in this way, the table parameter (which is a table expression) can be replaced by CURRENTGROUP function. (Refer Remarks Section for details)."
},
{
"code": null,
"e": 3539,
"s": 3263,
"text": "It can include any of the “X” aggregation functions, such as SUMX, AVERAGEX, MINX, MAXX, etc. and when one of these functions is used in this way, the table parameter (which is a table expression) can be replaced by CURRENTGROUP function. (Refer Remarks Section for details)."
},
{
"code": null,
"e": 3803,
"s": 3539,
"text": "However, CURRENTGROUP function can only be used at the top level of table scans in the expression. That means,\n\nABS (SUMX (CURRENTGROUP (), [Column])) is allowed, since ABS does not perform a scan.\nBut, SUMX (<table>, SUMX (CURRENTGROUP () ...)) is not allowed.\n\n"
},
{
"code": null,
"e": 3914,
"s": 3803,
"text": "However, CURRENTGROUP function can only be used at the top level of table scans in the expression. That means,"
},
{
"code": null,
"e": 4000,
"s": 3914,
"text": "ABS (SUMX (CURRENTGROUP (), [Column])) is allowed, since ABS does not perform a scan."
},
{
"code": null,
"e": 4086,
"s": 4000,
"text": "ABS (SUMX (CURRENTGROUP (), [Column])) is allowed, since ABS does not perform a scan."
},
{
"code": null,
"e": 4150,
"s": 4086,
"text": "But, SUMX (<table>, SUMX (CURRENTGROUP () ...)) is not allowed."
},
{
"code": null,
"e": 4214,
"s": 4150,
"text": "But, SUMX (<table>, SUMX (CURRENTGROUP () ...)) is not allowed."
},
{
"code": null,
"e": 4293,
"s": 4214,
"text": "DAX CALCULATE function and calculated fields are not allowed in the expression"
},
{
"code": null,
"e": 4372,
"s": 4293,
"text": "DAX CALCULATE function and calculated fields are not allowed in the expression"
},
{
"code": null,
"e": 4506,
"s": 4372,
"text": "A table with the selected columns for the groupBy_columnName parameters and the grouped by columns designated by the name parameters."
},
{
"code": null,
"e": 4548,
"s": 4506,
"text": "The GROUPBY function does the following −"
},
{
"code": null,
"e": 4631,
"s": 4548,
"text": "Start with the specified table (and all related tables in the “to-one” direction)."
},
{
"code": null,
"e": 4714,
"s": 4631,
"text": "Start with the specified table (and all related tables in the “to-one” direction)."
},
{
"code": null,
"e": 4821,
"s": 4714,
"text": "Create a grouping using all of the GroupBy columns (which are required to exist in the table from step 1)."
},
{
"code": null,
"e": 4928,
"s": 4821,
"text": "Create a grouping using all of the GroupBy columns (which are required to exist in the table from step 1)."
},
{
"code": null,
"e": 5017,
"s": 4928,
"text": "Each group is one row in the result, but represents a set of rows in the original table."
},
{
"code": null,
"e": 5106,
"s": 5017,
"text": "Each group is one row in the result, but represents a set of rows in the original table."
},
{
"code": null,
"e": 5289,
"s": 5106,
"text": "For each group, evaluate the extension columns being added. Unlike the SUMMARIZE function, an implied CALCULATE is not performed, and the group is not placed into the filter context."
},
{
"code": null,
"e": 5472,
"s": 5289,
"text": "For each group, evaluate the extension columns being added. Unlike the SUMMARIZE function, an implied CALCULATE is not performed, and the group is not placed into the filter context."
},
{
"code": null,
"e": 5832,
"s": 5472,
"text": "Each column for which you define a name must have a corresponding expression. Otherwise, an error is returned.\n\nThe first parameter, name, defines the name of the column in the results. The second parameter, expression, defines the calculation performed to obtain the value for each row in that column.\nEach name must be enclosed in double quotation marks.\n\n"
},
{
"code": null,
"e": 5944,
"s": 5832,
"text": "Each column for which you define a name must have a corresponding expression. Otherwise, an error is returned."
},
{
"code": null,
"e": 6135,
"s": 5944,
"text": "The first parameter, name, defines the name of the column in the results. The second parameter, expression, defines the calculation performed to obtain the value for each row in that column."
},
{
"code": null,
"e": 6326,
"s": 6135,
"text": "The first parameter, name, defines the name of the column in the results. The second parameter, expression, defines the calculation performed to obtain the value for each row in that column."
},
{
"code": null,
"e": 6380,
"s": 6326,
"text": "Each name must be enclosed in double quotation marks."
},
{
"code": null,
"e": 6434,
"s": 6380,
"text": "Each name must be enclosed in double quotation marks."
},
{
"code": null,
"e": 6668,
"s": 6434,
"text": "groupBy_columnName must be either in a table or in a related table.\n\nThe function groups a selected set of rows into a set of summary rows by the values of one or more groupBy_columnName columns. One row is returned for each group.\n\n"
},
{
"code": null,
"e": 6736,
"s": 6668,
"text": "groupBy_columnName must be either in a table or in a related table."
},
{
"code": null,
"e": 6899,
"s": 6736,
"text": "The function groups a selected set of rows into a set of summary rows by the values of one or more groupBy_columnName columns. One row is returned for each group."
},
{
"code": null,
"e": 7062,
"s": 6899,
"text": "The function groups a selected set of rows into a set of summary rows by the values of one or more groupBy_columnName columns. One row is returned for each group."
},
{
"code": null,
"e": 7169,
"s": 7062,
"text": "CURRENTGROUP function can only be used in an expression that defines a column within the GROUPBY function."
},
{
"code": null,
"e": 7276,
"s": 7169,
"text": "CURRENTGROUP function can only be used in an expression that defines a column within the GROUPBY function."
},
{
"code": null,
"e": 7401,
"s": 7276,
"text": "CURRENTGROUP returns a set of rows from the table parameter of GROUPBY that belong to the current row of the GROUPBY result."
},
{
"code": null,
"e": 7526,
"s": 7401,
"text": "CURRENTGROUP returns a set of rows from the table parameter of GROUPBY that belong to the current row of the GROUPBY result."
},
{
"code": null,
"e": 7761,
"s": 7526,
"text": "CURRENTGROUP function takes no parameters and is only supported as the first parameter to one of the following aggregation functions: AverageX, CountAX, CountX, GeoMeanX, MaxX, MinX, ProductX, StDevX.S, StDevX.P, SumX, VarX.S, VarX.P."
},
{
"code": null,
"e": 7996,
"s": 7761,
"text": "CURRENTGROUP function takes no parameters and is only supported as the first parameter to one of the following aggregation functions: AverageX, CountAX, CountX, GeoMeanX, MaxX, MinX, ProductX, StDevX.S, StDevX.P, SumX, VarX.S, VarX.P."
},
{
"code": null,
"e": 8116,
"s": 7996,
"text": "= GROUPBY ( \n Sales,Sales[Salesperson],Products[Product],\"Total Sales\", \n SUMX (CURRENTGROUP (),[Sales Amount]) \n)"
},
{
"code": null,
"e": 8151,
"s": 8116,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8165,
"s": 8151,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 8198,
"s": 8165,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8212,
"s": 8198,
"text": " Randy Minder"
},
{
"code": null,
"e": 8247,
"s": 8212,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8261,
"s": 8247,
"text": " Randy Minder"
},
{
"code": null,
"e": 8268,
"s": 8261,
"text": " Print"
},
{
"code": null,
"e": 8279,
"s": 8268,
"text": " Add Notes"
}
] |
Transmitting data over WiFi using HTTP
|
HTTP (HyperText Transfer Protocol) is one of the most common forms of communications and with ESP32 we can interact with any web server using HTTP requests. Let's understand how in this chapter.
The HTTP request happens between a client and a server. A server, as the name suggests, 'serves' information to the client on request. A web server serves web pages generally. For instance, when you type https://www.linkedin.com/login in your internet browser, your PC or laptop acts as a client and requests for the page corresponding to the /login address, from the server hosting linkedin.com. You get an HTML page in return, which is then displayed by your browser.
HTTP follows the request-response model, meaning that communication is always initiated by the client. The server cannot talk to any client out−of−the−blue, or can't start communication with any client. The communication always has to be initiated by the client in the form of a request and the server can only respond to that request. The response of the server contains the status code (remember 404? That's a status code) and, if applicable, the content requested. The list of all status codes can be found here.
Now, how does a server identify an HTTP request? Through the structure of the request. An HTTP request follows a fixed structure which consists of 3 parts:
The request line followed by carriage return line feed (CRLF = \r\n)
The request line followed by carriage return line feed (CRLF = \r\n)
Zero or more header lines followed by CRLF and an empty line, again followed by CRLF
Zero or more header lines followed by CRLF and an empty line, again followed by CRLF
Optional body
Optional body
This is how a typical HTTP request looks like:
POST / HTTP/1.1 //Request line, containing request method (POST in this case)
Host: www.example.com //Headers
//Empty line between headers
key1=value1&key2=value2 //Body
This is how a server response looks like −
HTTP/1.1 200 OK //Response line; 200 is the status code
Date: Mon, 23 May 2005 22:38:34 GMT //Headers
Content-Type: text/html; charset=UTF-8
Content-Length: 155
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f−1b6−3e1cb03b"
Accept-Ranges: bytes
Connection: close
//Empty line between headers and body
<html>
<head>
<title>An Example Page</title>
</head>
<body>
<p>Hello World, this is a very simple HTML document.</p>
</body>
</html>
In fact, there is a very good tutorial on HTTP request structure on TutorialsPoint itself. It also introduces you to the various request methods (GET, POST, PUT, etc.). For this chapter, we will be concerned with the GET and POST methods.
The GET request contains all parameters in the form of a key value pair in the request URL itself. For example, if instead of POST, the same example request above was to be sent using GET, it would look like:
GET /test/demo_form.php?key1=value1&key2=value2 HTTP/1.1 //Request line
Host: www.example.com //Headers
//No need for a body
The POST request, as you would have guessed by now, contains the parameters in the body instead of the URL. There are several more differences between GET and POST, which you can
read here. But the crux is that you will use POST for sharing sensitive information, like passwords, with the server.
For this chapter, we will write our HTTP request from scratch. There are libraries like httpClient available specifically for handling the ESP32 HTTP requests which take care of constructing the HTTP requests, but we will construct our request ourselves. That gives us much more flexibility. We will be restricting to the ESP32 Client mode for this tutorial. The HTTP server mode is also possible with ESP32, but that is for you to explore.
We will be using httpbin.org as our server. It is basically built for you to test your HTTP requests. You can test GET, POST, and a variety of other methods using this server. See this.
The code can be found on GitHub
We begin with the inclusion of the WiFi library.
#include <WiFi.h>
Next, we will define some constants. For HTTP, the port that is used is 80. That is the standard. Similarly, we use 443 for HTTPS, 21 for FTP, 53 for DNS, and so on. These are reserved port numbers.
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* server = "httpbin.org";
const int port = 80;
Finally, we create our WiFiClient object.
WiFiClient client
In the setup, we simply connect to the WiFi in the station mode using the credentials provided.
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA); //The WiFi is in station mode. The other is the softAP mode
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(""); Serial.print("WiFi connected to: "); Serial.println(ssid); Serial.println("IP address: "); Serial.println(WiFi.localIP());
delay(2000);
}
The loop becomes important here. That's where the HTTP request gets executed. We first begin by reading the Chip ID of our ESP32. We will be sending that as a parameter to the server along with our name. We will construct the body of our HTTP request using these parameters.
void loop() {
int conn;
int chip_id = ESP.getEfuseMac();;
Serial.printf(" Flash Chip id = %08X\t", chip_id);
Serial.println();
Serial.println();
String body = "ChipId=" + String(chip_id) + "&SentBy=" + "your_name";
int body_len = body.length();
Notice the & before the SentBy field. & is used as a separator between different key-value pairs in the HTTP requests. Next, we connect to the server.
Serial.println(".....");
Serial.println(); Serial.print("For sending parameters, connecting to "); Serial.println(server);
conn = client.connect(server, port);
If our connection is successful, client.connect() will return 1. We check that before making the request.
if (conn == 1) {
Serial.println(); Serial.print("Sending Parameters...");
//Request
client.println("POST /post HTTP/1.1");
//Headers
client.print("Host: "); client.println(server);
client.println("Content-Type: application/x−www−form−urlencoded");
client.print("Content-Length: "); client.println(body_len);
client.println("Connection: Close");
client.println();
//Body
client.println(body);
client.println();
//Wait for server response
while (client.available() == 0);
//Print Server Response
while (client.available()) {
char c = client.read();
Serial.write(c);
}
} else {
client.stop();
Serial.println("Connection Failed");
}
As you can see, we use the client.print() or client.println() for sending our request lines. The request, headers, and body are clearly indicated via comments. In the Request line, POST /post HTTP/1.1 is equivalent to POST http://httpbin.org/post HTTP/1.1. Since we have already mentioned the server in the client.connect(server,port), it is understood that /post refers to the server/post URL.
For POST requests especially, the Content-Length header is very important. Without it, several servers assume that the content-length is 0, meaning there is no body. The Content-Type has been kept as application/x−www−form−urlencoded because our body represents a form data. In a typical form submission, you will have keys like Name, Address, etc., and corresponding values. You can have several other content types. For the full list, see this.
The Connection: Close header tells the server to close the connection after the request has been processed. You could have alternatively send Connection: Keep-Alive if you wanted the connection to be kept alive after the request was processed.
These are just some of the headers that we could have included. The full list of HTTP headers can be found here.
Now, the httpbin.org/post URL typically just echoes back our body. A sample response is the following −
HTTP/1.1 200 OK
Date: Sat, 21 Nov 2020 16:25:47 GMT
Content−Type: application/json
Content−Length: 402
Connection: close
Server: gunicorn/19.9.0
Access−Control−Allow−Origin: *
Access−Control−Allow−Credentials: true
{
"args": {},
"data": "",
"files": {},
"form": {
"ChipId": "1780326616",
"SentBy": "Yash"
},
"headers": {
"Content−Length": "34",
"Content−Type": "application/x−www−form−urlencoded",
"Host": "httpbin.org",
"X-Amzn−Trace−Id": "Root=1−5fb93f8b−574bfb57002c108a1d7958bb"
},
"json": null,
"origin": "183.87.63.113",
"url": "http://httpbin.org/post"
}
As you can see, the content of the POST body has been echoed back in the "form" field. You should see something similar to the above printed on your serial monitor. Also note the URL field.
It clearly shows that the /post address in the request line was interpreted as http://httpbin.org/post.
Finally, we will wait for 5 seconds, before ending the loop, and thus, making the request again.
delay(5000);
}
At this point, you would be wondering, what changes would you need to make to convert this POST request to GET request. It is quite simple actually. You would, first of all, invoke the /get address instead of /post. Then you'll append the content of the body to the URL after a ? sign. Finally, you will replace the method to GET. Also, the Content-Length and Content−Type headers are no longer required, since your body is empty. Thus, your request block would look like −
if (conn == 1) {
String path = String("/get") + String("?") +body;
Serial.println(); Serial.print("Sending Parameters...");
//Request
client.println("GET "+path+" HTTP/1.1");
//Headers
client.print("Host: "); client.println(server);
client.println("Connection: Close");
client.println();
//No Body
//Wait for server response
while (client.available() == 0);
//Print Server Response
while (client.available()) {
char c = client.read();
Serial.write(c);
}
} else {
client.stop();
Serial.println("Connection Failed");
}
The corresponding response would look like −
HTTP/1.1 200 OK
Date: Tue, 17 Nov 2020 18:05:34 GMT
Content-Type: application/json
Content-Length: 497
Connection: close
Server: gunicorn/19.9.0
Access-Control−Allow−Origin: *
Access-Control-Allow-Credentials: true
{
"args": {
"ChipID": "3F:A0:A1:77:0D:84",
"SentBy": "Yash"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
"X−Amzn−Trace−Id": "Root=1−5fb410ee−3630963b0b7980c959c34038"
},
"origin": "206.189.180.4",
"url": "https://httpbin.org/get?ChipID=3F:A0:A1:77:0D:84&SentBy=Yash"
}
As you can see, the parameters send to the server are now returned in the args field, because they were sent as arguments in the URL itself.
Congratulations!! You've successfully sent your HTTP requests using ESP32.
HTTP Methods − Get vs POST
HTTP Methods − Get vs POST
HTTP Requests
HTTP Requests
54 Lectures
4.5 hours
Frahaan Hussain
20 Lectures
5 hours
Azaz Patel
20 Lectures
4 hours
Azaz Patel
0 Lectures
0 mins
Eduonix Learning Solutions
169 Lectures
12.5 hours
Kalob Taulien
29 Lectures
2 hours
Zenva
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2378,
"s": 2183,
"text": "HTTP (HyperText Transfer Protocol) is one of the most common forms of communications and with ESP32 we can interact with any web server using HTTP requests. Let's understand how in this chapter."
},
{
"code": null,
"e": 2849,
"s": 2378,
"text": "The HTTP request happens between a client and a server. A server, as the name suggests, 'serves' information to the client on request. A web server serves web pages generally. For instance, when you type https://www.linkedin.com/login in your internet browser, your PC or laptop acts as a client and requests for the page corresponding to the /login address, from the server hosting linkedin.com. You get an HTML page in return, which is then displayed by your browser. "
},
{
"code": null,
"e": 3365,
"s": 2849,
"text": "HTTP follows the request-response model, meaning that communication is always initiated by the client. The server cannot talk to any client out−of−the−blue, or can't start communication with any client. The communication always has to be initiated by the client in the form of a request and the server can only respond to that request. The response of the server contains the status code (remember 404? That's a status code) and, if applicable, the content requested. The list of all status codes can be found here."
},
{
"code": null,
"e": 3521,
"s": 3365,
"text": "Now, how does a server identify an HTTP request? Through the structure of the request. An HTTP request follows a fixed structure which consists of 3 parts:"
},
{
"code": null,
"e": 3590,
"s": 3521,
"text": "The request line followed by carriage return line feed (CRLF = \\r\\n)"
},
{
"code": null,
"e": 3659,
"s": 3590,
"text": "The request line followed by carriage return line feed (CRLF = \\r\\n)"
},
{
"code": null,
"e": 3744,
"s": 3659,
"text": "Zero or more header lines followed by CRLF and an empty line, again followed by CRLF"
},
{
"code": null,
"e": 3829,
"s": 3744,
"text": "Zero or more header lines followed by CRLF and an empty line, again followed by CRLF"
},
{
"code": null,
"e": 3843,
"s": 3829,
"text": "Optional body"
},
{
"code": null,
"e": 3857,
"s": 3843,
"text": "Optional body"
},
{
"code": null,
"e": 3904,
"s": 3857,
"text": "This is how a typical HTTP request looks like:"
},
{
"code": null,
"e": 4111,
"s": 3904,
"text": "POST / HTTP/1.1 //Request line, containing request method (POST in this case)\nHost: www.example.com //Headers\n //Empty line between headers\nkey1=value1&key2=value2 //Body\t"
},
{
"code": null,
"e": 4154,
"s": 4111,
"text": "This is how a server response looks like −"
},
{
"code": null,
"e": 4721,
"s": 4154,
"text": "HTTP/1.1 200 OK //Response line; 200 is the status code\nDate: Mon, 23 May 2005 22:38:34 GMT //Headers\nContent-Type: text/html; charset=UTF-8\nContent-Length: 155\nLast-Modified: Wed, 08 Jan 2003 23:11:55 GMT\nServer: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)\nETag: \"3f80f−1b6−3e1cb03b\"\nAccept-Ranges: bytes\nConnection: close\n //Empty line between headers and body\n<html>\t\t\t\t\t\t\n <head>\n <title>An Example Page</title>\n </head>\n <body>\n <p>Hello World, this is a very simple HTML document.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 4961,
"s": 4721,
"text": "In fact, there is a very good tutorial on HTTP request structure on TutorialsPoint itself. It also introduces you to the various request methods (GET, POST, PUT, etc.). For this chapter, we will be concerned with the GET and POST methods. "
},
{
"code": null,
"e": 5170,
"s": 4961,
"text": "The GET request contains all parameters in the form of a key value pair in the request URL itself. For example, if instead of POST, the same example request above was to be sent using GET, it would look like:"
},
{
"code": null,
"e": 5393,
"s": 5170,
"text": "GET /test/demo_form.php?key1=value1&key2=value2 HTTP/1.1 //Request line\nHost: www.example.com //Headers\t\n //No need for a body\n"
},
{
"code": null,
"e": 5692,
"s": 5393,
"text": "The POST request, as you would have guessed by now, contains the parameters in the body instead of the URL. There are several more differences between GET and POST, which you can \nread here. But the crux is that you will use POST for sharing sensitive information, like passwords, with the server. "
},
{
"code": null,
"e": 6134,
"s": 5692,
"text": "For this chapter, we will write our HTTP request from scratch. There are libraries like httpClient available specifically for handling the ESP32 HTTP requests which take care of constructing the HTTP requests, but we will construct our request ourselves. That gives us much more flexibility. We will be restricting to the ESP32 Client mode for this tutorial. The HTTP server mode is also possible with ESP32, but that is for you to explore. "
},
{
"code": null,
"e": 6320,
"s": 6134,
"text": "We will be using httpbin.org as our server. It is basically built for you to test your HTTP requests. You can test GET, POST, and a variety of other methods using this server. See this."
},
{
"code": null,
"e": 6353,
"s": 6320,
"text": "The code can be found on GitHub\n"
},
{
"code": null,
"e": 6402,
"s": 6353,
"text": "We begin with the inclusion of the WiFi library."
},
{
"code": null,
"e": 6420,
"s": 6402,
"text": "#include <WiFi.h>"
},
{
"code": null,
"e": 6620,
"s": 6420,
"text": "Next, we will define some constants. For HTTP, the port that is used is 80. That is the standard. Similarly, we use 443 for HTTPS, 21 for FTP, 53 for DNS, and so on. These are reserved port numbers. "
},
{
"code": null,
"e": 6750,
"s": 6620,
"text": "const char* ssid = \"YOUR_SSID\";\nconst char* password = \"YOUR_PASSWORD\";\n\nconst char* server = \"httpbin.org\";\nconst int port = 80;"
},
{
"code": null,
"e": 6792,
"s": 6750,
"text": "Finally, we create our WiFiClient object."
},
{
"code": null,
"e": 6811,
"s": 6792,
"text": "WiFiClient client\n"
},
{
"code": null,
"e": 6907,
"s": 6811,
"text": "In the setup, we simply connect to the WiFi in the station mode using the credentials provided."
},
{
"code": null,
"e": 7329,
"s": 6907,
"text": "void setup() {\n Serial.begin(115200);\n WiFi.mode(WIFI_STA); //The WiFi is in station mode. The other is the softAP mode\n WiFi.begin(ssid, password);\n while (WiFi.status() != WL_CONNECTED) {\n delay(500);\n Serial.print(\".\");\n }\n Serial.println(\"\"); Serial.print(\"WiFi connected to: \"); Serial.println(ssid); Serial.println(\"IP address: \"); Serial.println(WiFi.localIP());\n delay(2000);\n}"
},
{
"code": null,
"e": 7604,
"s": 7329,
"text": "The loop becomes important here. That's where the HTTP request gets executed. We first begin by reading the Chip ID of our ESP32. We will be sending that as a parameter to the server along with our name. We will construct the body of our HTTP request using these parameters."
},
{
"code": null,
"e": 7872,
"s": 7604,
"text": "void loop() {\n int conn;\n int chip_id = ESP.getEfuseMac();;\n Serial.printf(\" Flash Chip id = %08X\\t\", chip_id);\n Serial.println();\n Serial.println();\n String body = \"ChipId=\" + String(chip_id) + \"&SentBy=\" + \"your_name\";\n int body_len = body.length();"
},
{
"code": null,
"e": 8023,
"s": 7872,
"text": "Notice the & before the SentBy field. & is used as a separator between different key-value pairs in the HTTP requests. Next, we connect to the server."
},
{
"code": null,
"e": 8188,
"s": 8023,
"text": "Serial.println(\".....\");\nSerial.println(); Serial.print(\"For sending parameters, connecting to \"); Serial.println(server);\nconn = client.connect(server, port);"
},
{
"code": null,
"e": 8295,
"s": 8188,
"text": "If our connection is successful, client.connect() will return 1. We check that before making the request. "
},
{
"code": null,
"e": 8996,
"s": 8295,
"text": "if (conn == 1) {\n Serial.println(); Serial.print(\"Sending Parameters...\");\n //Request\n client.println(\"POST /post HTTP/1.1\");\n //Headers\n client.print(\"Host: \"); client.println(server);\n client.println(\"Content-Type: application/x−www−form−urlencoded\");\n client.print(\"Content-Length: \"); client.println(body_len);\n client.println(\"Connection: Close\");\n client.println();\n //Body\n client.println(body);\n client.println();\n\n //Wait for server response\n while (client.available() == 0);\n\n //Print Server Response\n while (client.available()) {\n char c = client.read();\n Serial.write(c);\n }\n} else {\n client.stop();\n Serial.println(\"Connection Failed\");\n}"
},
{
"code": null,
"e": 9392,
"s": 8996,
"text": "As you can see, we use the client.print() or client.println() for sending our request lines. The request, headers, and body are clearly indicated via comments. In the Request line, POST /post HTTP/1.1 is equivalent to POST http://httpbin.org/post HTTP/1.1. Since we have already mentioned the server in the client.connect(server,port), it is understood that /post refers to the server/post URL. "
},
{
"code": null,
"e": 9839,
"s": 9392,
"text": "For POST requests especially, the Content-Length header is very important. Without it, several servers assume that the content-length is 0, meaning there is no body. The Content-Type has been kept as application/x−www−form−urlencoded because our body represents a form data. In a typical form submission, you will have keys like Name, Address, etc., and corresponding values. You can have several other content types. For the full list, see this."
},
{
"code": null,
"e": 10083,
"s": 9839,
"text": "The Connection: Close header tells the server to close the connection after the request has been processed. You could have alternatively send Connection: Keep-Alive if you wanted the connection to be kept alive after the request was processed."
},
{
"code": null,
"e": 10196,
"s": 10083,
"text": "These are just some of the headers that we could have included. The full list of HTTP headers can be found here."
},
{
"code": null,
"e": 10300,
"s": 10196,
"text": "Now, the httpbin.org/post URL typically just echoes back our body. A sample response is the following −"
},
{
"code": null,
"e": 10939,
"s": 10300,
"text": "HTTP/1.1 200 OK\nDate: Sat, 21 Nov 2020 16:25:47 GMT\nContent−Type: application/json\nContent−Length: 402\nConnection: close\nServer: gunicorn/19.9.0\nAccess−Control−Allow−Origin: *\nAccess−Control−Allow−Credentials: true\n{\n \"args\": {}, \n \"data\": \"\", \n \"files\": {}, \n \"form\": {\n \"ChipId\": \"1780326616\", \n \"SentBy\": \"Yash\"\n }, \n \"headers\": {\n \"Content−Length\": \"34\", \n \"Content−Type\": \"application/x−www−form−urlencoded\", \n \"Host\": \"httpbin.org\", \n \"X-Amzn−Trace−Id\": \"Root=1−5fb93f8b−574bfb57002c108a1d7958bb\"\n }, \n \"json\": null, \n \"origin\": \"183.87.63.113\", \n \"url\": \"http://httpbin.org/post\"\n}"
},
{
"code": null,
"e": 11233,
"s": 10939,
"text": "As you can see, the content of the POST body has been echoed back in the \"form\" field. You should see something similar to the above printed on your serial monitor. Also note the URL field.\nIt clearly shows that the /post address in the request line was interpreted as http://httpbin.org/post."
},
{
"code": null,
"e": 11330,
"s": 11233,
"text": "Finally, we will wait for 5 seconds, before ending the loop, and thus, making the request again."
},
{
"code": null,
"e": 11348,
"s": 11330,
"text": " delay(5000);\n}\n"
},
{
"code": null,
"e": 11822,
"s": 11348,
"text": "At this point, you would be wondering, what changes would you need to make to convert this POST request to GET request. It is quite simple actually. You would, first of all, invoke the /get address instead of /post. Then you'll append the content of the body to the URL after a ? sign. Finally, you will replace the method to GET. Also, the Content-Length and Content−Type headers are no longer required, since your body is empty. Thus, your request block would look like −"
},
{
"code": null,
"e": 12401,
"s": 11822,
"text": "if (conn == 1) {\n String path = String(\"/get\") + String(\"?\") +body;\n Serial.println(); Serial.print(\"Sending Parameters...\");\n //Request\n client.println(\"GET \"+path+\" HTTP/1.1\");\n //Headers\n client.print(\"Host: \"); client.println(server);\n client.println(\"Connection: Close\");\n client.println();\n //No Body\n\n //Wait for server response\n while (client.available() == 0);\n\n //Print Server Response\n while (client.available()) {\n char c = client.read();\n Serial.write(c);\n }\n} else {\n client.stop();\n Serial.println(\"Connection Failed\");\n}"
},
{
"code": null,
"e": 12446,
"s": 12401,
"text": "The corresponding response would look like −"
},
{
"code": null,
"e": 13179,
"s": 12446,
"text": "HTTP/1.1 200 OK\nDate: Tue, 17 Nov 2020 18:05:34 GMT\nContent-Type: application/json\nContent-Length: 497\nConnection: close\nServer: gunicorn/19.9.0\nAccess-Control−Allow−Origin: *\nAccess-Control-Allow-Credentials: true\n\n{\n \"args\": {\n \"ChipID\": \"3F:A0:A1:77:0D:84\", \n \"SentBy\": \"Yash\"\n }, \n \"headers\": {\n \"Accept\": \"*/*\", \n \"Accept-Encoding\": \"deflate, gzip\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36\", \n \"X−Amzn−Trace−Id\": \"Root=1−5fb410ee−3630963b0b7980c959c34038\"\n }, \n \"origin\": \"206.189.180.4\", \n \"url\": \"https://httpbin.org/get?ChipID=3F:A0:A1:77:0D:84&SentBy=Yash\"\n}"
},
{
"code": null,
"e": 13320,
"s": 13179,
"text": "As you can see, the parameters send to the server are now returned in the args field, because they were sent as arguments in the URL itself."
},
{
"code": null,
"e": 13395,
"s": 13320,
"text": "Congratulations!! You've successfully sent your HTTP requests using ESP32."
},
{
"code": null,
"e": 13422,
"s": 13395,
"text": "HTTP Methods − Get vs POST"
},
{
"code": null,
"e": 13449,
"s": 13422,
"text": "HTTP Methods − Get vs POST"
},
{
"code": null,
"e": 13463,
"s": 13449,
"text": "HTTP Requests"
},
{
"code": null,
"e": 13477,
"s": 13463,
"text": "HTTP Requests"
},
{
"code": null,
"e": 13512,
"s": 13477,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13529,
"s": 13512,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 13562,
"s": 13529,
"text": "\n 20 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13574,
"s": 13562,
"text": " Azaz Patel"
},
{
"code": null,
"e": 13607,
"s": 13574,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13619,
"s": 13607,
"text": " Azaz Patel"
},
{
"code": null,
"e": 13649,
"s": 13619,
"text": "\n 0 Lectures \n 0 mins\n"
},
{
"code": null,
"e": 13677,
"s": 13649,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 13714,
"s": 13677,
"text": "\n 169 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 13729,
"s": 13714,
"text": " Kalob Taulien"
},
{
"code": null,
"e": 13762,
"s": 13729,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13769,
"s": 13762,
"text": " Zenva"
},
{
"code": null,
"e": 13776,
"s": 13769,
"text": " Print"
},
{
"code": null,
"e": 13787,
"s": 13776,
"text": " Add Notes"
}
] |
How to check a checkbox with jQuery? - GeeksforGeeks
|
03 Aug, 2021
There are two methods by which you can dynamically check the currently selected checkbox by changing the checked property of the input type.
Method 1: Using the prop method: The input can be accessed and its property can be set by using the prop method. This method manipulates the ‘checked’ property and sets it to true or false depending on whether we want to check or uncheck it.Syntax:
$("element").prop("checked", true)
Example:
<!DOCTYPE html> <head> <title> How to check a checkbox with jQuery? </title> <script src="https://code.jquery.com/jquery-2.2.4.min.js"> </script></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> jQuery Check/Uncheck Checkbox </b> <p> <input type="checkbox" name="option" id="front"> Front-End <input type="checkbox" name="option" id="back"> Back-End </p> <p> <button type="button" class="check-front"> Subscribe Front-End </button> <button type="button" class="check-back"> Subscribe Back-End </button> <button type="button" class="reset"> Reset </button> </p> <script type="text/javascript"> $(document).ready(function() { $(".check-front").click(function() { $("#front").prop("checked", true); }); $(".check-back").click(function() { $("#back").prop("checked", true); }); $(".reset").click(function() { $("#front").prop("checked", false); $("#back").prop("checked", false); }); }); </script> </center></body> </html>
Output:
Before clicking any button:
Clicking on the button:
Clicking on the ‘Reset’ button:
Method 2: Using the attr method: It is similar to the above method and more suitable for older jQuery versions. The input can be accessed and its property can be set by using the attr method. We have to manipulate the ‘checked’ property and set it to true or false depending on whether we want to check or uncheck it.Note: It is necessary to add a click method when setting the attribute to ‘true’ to make sure that the option gets updated in the option group.Syntax:
$("element").attr("checked", true)
Example:
<!DOCTYPE html> <head> <title> How to check a checkbox with jQuery? </title> <script src="https://code.jquery.com/jquery-2.2.4.min.js"> </script></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> jQuery Check/Uncheck Checkbox </b> <p> <input type="checkbox" name="option" id="Front"> Front-End <input type="checkbox" name="option" id="Back"> Back-End </p> <p> <button type="button" class="check-Front"> Subscribe Front-End </button> <button type="button" class="check-Back"> Subscribe Back-End </button> <button type="button" class="reset"> Reset </button> </p> <script type="text/javascript"> $(document).ready(function() { $(".check-Front").click(function() { $("#Front").attr("checked", true); }); $(".check-Back").click(function() { $("#Back").attr("checked", true); }); $(".reset").click(function() { $("#Front").attr("checked", false); $("#Back").attr("checked", false); }); }); </script> </center></body> </html>
Output:
Before clicking any button:
Clicking on the button:
Clicking on the ‘Reset’ button:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
JavaScript
JQuery
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
Set the value of an input field in JavaScript
How to Use the JavaScript Fetch API to Get Data?
Node.js | fs.writeFileSync() Method
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery?
|
[
{
"code": null,
"e": 24970,
"s": 24942,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25111,
"s": 24970,
"text": "There are two methods by which you can dynamically check the currently selected checkbox by changing the checked property of the input type."
},
{
"code": null,
"e": 25360,
"s": 25111,
"text": "Method 1: Using the prop method: The input can be accessed and its property can be set by using the prop method. This method manipulates the ‘checked’ property and sets it to true or false depending on whether we want to check or uncheck it.Syntax:"
},
{
"code": null,
"e": 25395,
"s": 25360,
"text": "$(\"element\").prop(\"checked\", true)"
},
{
"code": null,
"e": 25404,
"s": 25395,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <head> <title> How to check a checkbox with jQuery? </title> <script src=\"https://code.jquery.com/jquery-2.2.4.min.js\"> </script></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> jQuery Check/Uncheck Checkbox </b> <p> <input type=\"checkbox\" name=\"option\" id=\"front\"> Front-End <input type=\"checkbox\" name=\"option\" id=\"back\"> Back-End </p> <p> <button type=\"button\" class=\"check-front\"> Subscribe Front-End </button> <button type=\"button\" class=\"check-back\"> Subscribe Back-End </button> <button type=\"button\" class=\"reset\"> Reset </button> </p> <script type=\"text/javascript\"> $(document).ready(function() { $(\".check-front\").click(function() { $(\"#front\").prop(\"checked\", true); }); $(\".check-back\").click(function() { $(\"#back\").prop(\"checked\", true); }); $(\".reset\").click(function() { $(\"#front\").prop(\"checked\", false); $(\"#back\").prop(\"checked\", false); }); }); </script> </center></body> </html>",
"e": 26829,
"s": 25404,
"text": null
},
{
"code": null,
"e": 26837,
"s": 26829,
"text": "Output:"
},
{
"code": null,
"e": 26865,
"s": 26837,
"text": "Before clicking any button:"
},
{
"code": null,
"e": 26889,
"s": 26865,
"text": "Clicking on the button:"
},
{
"code": null,
"e": 26921,
"s": 26889,
"text": "Clicking on the ‘Reset’ button:"
},
{
"code": null,
"e": 27389,
"s": 26921,
"text": "Method 2: Using the attr method: It is similar to the above method and more suitable for older jQuery versions. The input can be accessed and its property can be set by using the attr method. We have to manipulate the ‘checked’ property and set it to true or false depending on whether we want to check or uncheck it.Note: It is necessary to add a click method when setting the attribute to ‘true’ to make sure that the option gets updated in the option group.Syntax:"
},
{
"code": null,
"e": 27424,
"s": 27389,
"text": "$(\"element\").attr(\"checked\", true)"
},
{
"code": null,
"e": 27433,
"s": 27424,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <head> <title> How to check a checkbox with jQuery? </title> <script src=\"https://code.jquery.com/jquery-2.2.4.min.js\"> </script></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> jQuery Check/Uncheck Checkbox </b> <p> <input type=\"checkbox\" name=\"option\" id=\"Front\"> Front-End <input type=\"checkbox\" name=\"option\" id=\"Back\"> Back-End </p> <p> <button type=\"button\" class=\"check-Front\"> Subscribe Front-End </button> <button type=\"button\" class=\"check-Back\"> Subscribe Back-End </button> <button type=\"button\" class=\"reset\"> Reset </button> </p> <script type=\"text/javascript\"> $(document).ready(function() { $(\".check-Front\").click(function() { $(\"#Front\").attr(\"checked\", true); }); $(\".check-Back\").click(function() { $(\"#Back\").attr(\"checked\", true); }); $(\".reset\").click(function() { $(\"#Front\").attr(\"checked\", false); $(\"#Back\").attr(\"checked\", false); }); }); </script> </center></body> </html>",
"e": 28845,
"s": 27433,
"text": null
},
{
"code": null,
"e": 28853,
"s": 28845,
"text": "Output:"
},
{
"code": null,
"e": 28881,
"s": 28853,
"text": "Before clicking any button:"
},
{
"code": null,
"e": 28905,
"s": 28881,
"text": "Clicking on the button:"
},
{
"code": null,
"e": 28937,
"s": 28905,
"text": "Clicking on the ‘Reset’ button:"
},
{
"code": null,
"e": 29205,
"s": 28937,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 29217,
"s": 29205,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29228,
"s": 29217,
"text": "JavaScript"
},
{
"code": null,
"e": 29235,
"s": 29228,
"text": "JQuery"
},
{
"code": null,
"e": 29252,
"s": 29235,
"text": "Web Technologies"
},
{
"code": null,
"e": 29279,
"s": 29252,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29377,
"s": 29279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29386,
"s": 29377,
"text": "Comments"
},
{
"code": null,
"e": 29399,
"s": 29386,
"text": "Old Comments"
},
{
"code": null,
"e": 29460,
"s": 29399,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29501,
"s": 29460,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29547,
"s": 29501,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 29596,
"s": 29547,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 29632,
"s": 29596,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 29678,
"s": 29632,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 29707,
"s": 29678,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29770,
"s": 29707,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 29847,
"s": 29770,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
JBoss Fuse - Apache Camel
|
In this chapter, we will discuss what Apache Camel is and how it effectively routes data between endpoints, along with a few examples.
Apache Camel is an open source integration framework which was started in early 2007.
It is an EIP (Enterprise Integration Pattern) based approach which provides several out of the box patterns implementations that can be used to solve enterprise integration problems. EIP are nothing but proven solutions to the well documented and recurring problems in enterprise integration.
Camel is also known as routing and mediation engine as it effectively routes data between endpoints, while taking heavy load like transformation of data formats, endpoint connectivity and many more.
The prerequisites to use Apache Camel are −
Java
Maven
Redhat JBoss Fuse 6.1-GA-379
mvn:archetype generate
–DgroupId = com.tutorialpoint.app
–DartifactId = camel-first-app
–DarchetypeGroupId = org.apache.camel.archetypes
–DarchetypeArtifactId = camel-archetype-spring
–DinteractiveMode = false -X
This should generate the following directory structure.
This is a basic skeleton of our Camel application being generated.
Edit camel-first-app → src → main → resources → META-INF\spring\camel-context.xml to match as below
<?xml version = "1.0" encoding = "UTF-8"?>
<!-- Configures the Camel Context-->
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns = "http://camel.apache.org/schema/spring">
<!-- here is a sample which processes the input file
(leaving them in place - see the 'noop' flag)
then performs content based routing on the message using XPath -->
<route>
<from uri = "file:///d:/src/data?noop=false"/>
<choice>
<when>
<xpath>/person/city = 'London'</xpath>
<log message = "UK message"/>
<to uri = "file:///d:/target/messages/uk"/>
</when>
<otherwise>
<log message = "Other message"/>
<to uri = "file:///d:/target/messages/others"/>
</otherwise>
</choice>
</route>
</camelContext>
</beans>
Add the following code inside <plugins></plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.3.4</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>
${project.artifactId}
</Bundle-SymbolicName>
<Import-Package>*</Import-Package>
</instructions>
</configuration>
</plugin>
Change packaging type from jar → bundle.
<packaging>bundle</packaging>
Build the project using the following command −
mvn clean install
Start Fuse using Fuse.bat/start.bat. If you start Fuse using start.bat, use client.bat to connect to Fuse. You should get the UI as shown in the following screenshot.
This is the CLI for accessing Karaf and Fuse commands.
install –s mvn:com.tutorialpoint.app/camel-firt-app/1.0-SNAPSHOT
Now your application should be installed in Fuse. Copy data directory inside camel-first-app and place it in D:/src/ and it should copy message having city = London into D:/target/merssages/uk.
Place the input file in D:/src/data
Input
Message1.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<person user = "james">
<firstName>James</firstName>
<lastName>Strachan</lastName>
<city>London</city>
</person>
Message2.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<person user = "hiram">
<firstName>Hiram</firstName>
<lastName>Chirino</lastName>
<city>Tampa</city>
</person>
Output
In D:/target/messages/uk
<?xml version = "1.0" encoding = "UTF-8"?>
<person user = "james">
<firstName>James</firstName>
<lastName>Strachan</lastName>
<city>London</city>
</person>
In D:/target/messages/others
<?xml version = "1.0" encoding = "UTF-8"?>
<person user = "hiram">
<firstName>Hiram</firstName>
<lastName>Chirino</lastName>
<city>Tampa</city>
</person>
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2051,
"s": 1916,
"text": "In this chapter, we will discuss what Apache Camel is and how it effectively routes data between endpoints, along with a few examples."
},
{
"code": null,
"e": 2137,
"s": 2051,
"text": "Apache Camel is an open source integration framework which was started in early 2007."
},
{
"code": null,
"e": 2430,
"s": 2137,
"text": "It is an EIP (Enterprise Integration Pattern) based approach which provides several out of the box patterns implementations that can be used to solve enterprise integration problems. EIP are nothing but proven solutions to the well documented and recurring problems in enterprise integration."
},
{
"code": null,
"e": 2629,
"s": 2430,
"text": "Camel is also known as routing and mediation engine as it effectively routes data between endpoints, while taking heavy load like transformation of data formats, endpoint connectivity and many more."
},
{
"code": null,
"e": 2673,
"s": 2629,
"text": "The prerequisites to use Apache Camel are −"
},
{
"code": null,
"e": 2678,
"s": 2673,
"text": "Java"
},
{
"code": null,
"e": 2684,
"s": 2678,
"text": "Maven"
},
{
"code": null,
"e": 2713,
"s": 2684,
"text": "Redhat JBoss Fuse 6.1-GA-379"
},
{
"code": null,
"e": 2931,
"s": 2713,
"text": "mvn:archetype generate \n–DgroupId = com.tutorialpoint.app \n–DartifactId = camel-first-app \n–DarchetypeGroupId = org.apache.camel.archetypes\n–DarchetypeArtifactId = camel-archetype-spring \n–DinteractiveMode = false -X\n"
},
{
"code": null,
"e": 2987,
"s": 2931,
"text": "This should generate the following directory structure."
},
{
"code": null,
"e": 3054,
"s": 2987,
"text": "This is a basic skeleton of our Camel application being generated."
},
{
"code": null,
"e": 3154,
"s": 3054,
"text": "Edit camel-first-app → src → main → resources → META-INF\\spring\\camel-context.xml to match as below"
},
{
"code": null,
"e": 4371,
"s": 3154,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!-- Configures the Camel Context-->\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans.xsd\n http://camel.apache.org/schema/spring\n http://camel.apache.org/schema/spring/camel-spring.xsd\">\n\n <camelContext xmlns = \"http://camel.apache.org/schema/spring\">\n <!-- here is a sample which processes the input file\n (leaving them in place - see the 'noop' flag) \n then performs content based routing on the message using XPath -->\n\t\t\t\n <route>\n <from uri = \"file:///d:/src/data?noop=false\"/>\n <choice>\n <when>\n <xpath>/person/city = 'London'</xpath>\n <log message = \"UK message\"/>\n <to uri = \"file:///d:/target/messages/uk\"/>\n </when>\n\t\t\t\t\n <otherwise>\n <log message = \"Other message\"/>\n <to uri = \"file:///d:/target/messages/others\"/>\n </otherwise>\n\t\t\t\t\n </choice>\n\t\t\t\n </route>\n </camelContext>\n</beans>"
},
{
"code": null,
"e": 4421,
"s": 4371,
"text": "Add the following code inside <plugins></plugins>"
},
{
"code": null,
"e": 4815,
"s": 4421,
"text": "<plugin>\n <groupId>org.apache.felix</groupId>\n <artifactId>maven-bundle-plugin</artifactId>\n <version>2.3.4</version>\n <extensions>true</extensions>\n\t\n <configuration>\n <instructions>\n <Bundle-SymbolicName>\n ${project.artifactId}\n </Bundle-SymbolicName>\n <Import-Package>*</Import-Package>\n </instructions>\n </configuration>\n\t\n</plugin>"
},
{
"code": null,
"e": 4856,
"s": 4815,
"text": "Change packaging type from jar → bundle."
},
{
"code": null,
"e": 4887,
"s": 4856,
"text": "<packaging>bundle</packaging>\n"
},
{
"code": null,
"e": 4935,
"s": 4887,
"text": "Build the project using the following command −"
},
{
"code": null,
"e": 4954,
"s": 4935,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 5121,
"s": 4954,
"text": "Start Fuse using Fuse.bat/start.bat. If you start Fuse using start.bat, use client.bat to connect to Fuse. You should get the UI as shown in the following screenshot."
},
{
"code": null,
"e": 5176,
"s": 5121,
"text": "This is the CLI for accessing Karaf and Fuse commands."
},
{
"code": null,
"e": 5242,
"s": 5176,
"text": "install –s mvn:com.tutorialpoint.app/camel-firt-app/1.0-SNAPSHOT\n"
},
{
"code": null,
"e": 5436,
"s": 5242,
"text": "Now your application should be installed in Fuse. Copy data directory inside camel-first-app and place it in D:/src/ and it should copy message having city = London into D:/target/merssages/uk."
},
{
"code": null,
"e": 5472,
"s": 5436,
"text": "Place the input file in D:/src/data"
},
{
"code": null,
"e": 5478,
"s": 5472,
"text": "Input"
},
{
"code": null,
"e": 5491,
"s": 5478,
"text": "Message1.xml"
},
{
"code": null,
"e": 5656,
"s": 5491,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<person user = \"james\">\n <firstName>James</firstName>\n <lastName>Strachan</lastName>\n <city>London</city>\n</person>"
},
{
"code": null,
"e": 5669,
"s": 5656,
"text": "Message2.xml"
},
{
"code": null,
"e": 5832,
"s": 5669,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<person user = \"hiram\">\n <firstName>Hiram</firstName>\n <lastName>Chirino</lastName>\n <city>Tampa</city>\n</person>"
},
{
"code": null,
"e": 5839,
"s": 5832,
"text": "Output"
},
{
"code": null,
"e": 5864,
"s": 5839,
"text": "In D:/target/messages/uk"
},
{
"code": null,
"e": 6030,
"s": 5864,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<person user = \"james\">\n <firstName>James</firstName>\n <lastName>Strachan</lastName>\n <city>London</city>\n</person>\n"
},
{
"code": null,
"e": 6059,
"s": 6030,
"text": "In D:/target/messages/others"
},
{
"code": null,
"e": 6223,
"s": 6059,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<person user = \"hiram\">\n <firstName>Hiram</firstName>\n <lastName>Chirino</lastName>\n <city>Tampa</city>\n</person>\n"
},
{
"code": null,
"e": 6230,
"s": 6223,
"text": " Print"
},
{
"code": null,
"e": 6241,
"s": 6230,
"text": " Add Notes"
}
] |
Superscript and subscript axis labels in ggplot2 in R - GeeksforGeeks
|
28 Sep, 2021
In this article, we will see how to use Superscript and Subscript axis labels in ggplot2 in R Programming Language.
First we should load ggplot2 package using library() function. To install and load the ggplot2 package, write following command to R Console.
# To Install ggplot2 package
# (Write this command to R Console)
install.packages("ggplot2")
# Load ggplot2 package
library("ggplot2")
Now, let’s create a DataFrame. Here we will create a simple DataFrame with two variables named X & Y then assign it to the data object. Let’s named it DF. Here we have generated 10 random values for x and y axis using rnorm() function.
# Load Package
library("ggplot2")
# Create a DataFrame
DF <- data.frame(X = rnorm(10),
Y = rnorm(10))
To create an R plot, we use ggplot() function and for make it scattered we add geom_point() function to ggplot() function. Here we use some parameters size, fill, color, shape only for better appearance of points on ScatterPlot. For labels at X and Y axis, we use xlab() and ylab() functions respectively.
Syntax:
xlab(“Label for X-Axis”)
ylab(“Label for Y-Axis”)
Example:
R
# Load Packagelibrary("ggplot2") # Create a DataFrame DF <- data.frame(X = rnorm(10), Y = rnorm(10)) # Create a ScatterPlot with simple labelsggplot(DF,aes(X, Y))+ geom_point(size = 8, fill = "green", color = "black", shape = 21)+ xlab("X-Axis")+ ylab("Y-Axis")
Output:
ScatterPlot with Simple Axis Labels
Now we will change the label of X to ” X-Axissuperscript ” and Y to ” Y-Axissuperscript “. For that bquote() function is used to quote the argument passed to it.
Syntax : bquote(expr)
Parameter :
expr : language object
bquote() For SuperScript :
bquote(math superscript(^) Notation)
Example:
R
# Load ggplot2 Packagelibrary("ggplot2") # Create a DataFrame For PlottingDF <- data.frame(X = rnorm(10), Y = rnorm(10)) # Create ggplot2 ScatterPlot with SuperScripted # value of Label of Axis.ggplot(DF,aes(X, Y))+ geom_point(size = 8, fill = "green", color = "black", shape = 21)+ xlab(bquote(X-Axis^superscript))+ ylab(bquote(Y-Axis^superscript))
Output:
ScatterPlot with Superscripted Axis Labels
We will change the label of X to ” X-Axissubscript ” and Y to “ Y-Axissubscript “. For that, we will again use the bquote() function but with different Mathematical Notation for subscript.
bquote() For Subscript :
bquote(math subscript([]) Notation)
Example:
R
# Load ggplot2 Packagelibrary("ggplot2") # Create a DataFrame For PlottingDF <- data.frame(X = rnorm(10), Y = rnorm(10)) # Create ggplot2 ScatterPlot with SubScripted # value of Label of Axis.ggplot(DF,aes(X, Y))+ geom_point(size = 8, fill = "green", color = "black", shape = 21)+ xlab(bquote(X-Axis[subscript]))+ ylab(bquote(Y-Axis[subscript]))
Output:
ScatterPlot with Subscripted Axis Labels
anikakapoor
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
Replace Specific Characters in String in R
|
[
{
"code": null,
"e": 24377,
"s": 24349,
"text": "\n28 Sep, 2021"
},
{
"code": null,
"e": 24494,
"s": 24377,
"text": "In this article, we will see how to use Superscript and Subscript axis labels in ggplot2 in R Programming Language. "
},
{
"code": null,
"e": 24636,
"s": 24494,
"text": "First we should load ggplot2 package using library() function. To install and load the ggplot2 package, write following command to R Console."
},
{
"code": null,
"e": 24773,
"s": 24636,
"text": "# To Install ggplot2 package \n# (Write this command to R Console)\ninstall.packages(\"ggplot2\")\n\n# Load ggplot2 package\nlibrary(\"ggplot2\")"
},
{
"code": null,
"e": 25009,
"s": 24773,
"text": "Now, let’s create a DataFrame. Here we will create a simple DataFrame with two variables named X & Y then assign it to the data object. Let’s named it DF. Here we have generated 10 random values for x and y axis using rnorm() function."
},
{
"code": null,
"e": 25153,
"s": 25009,
"text": "# Load Package\nlibrary(\"ggplot2\")\n\n# Create a DataFrame\nDF <- data.frame(X = rnorm(10), \n Y = rnorm(10))"
},
{
"code": null,
"e": 25459,
"s": 25153,
"text": "To create an R plot, we use ggplot() function and for make it scattered we add geom_point() function to ggplot() function. Here we use some parameters size, fill, color, shape only for better appearance of points on ScatterPlot. For labels at X and Y axis, we use xlab() and ylab() functions respectively."
},
{
"code": null,
"e": 25467,
"s": 25459,
"text": "Syntax:"
},
{
"code": null,
"e": 25492,
"s": 25467,
"text": "xlab(“Label for X-Axis”)"
},
{
"code": null,
"e": 25517,
"s": 25492,
"text": "ylab(“Label for Y-Axis”)"
},
{
"code": null,
"e": 25526,
"s": 25517,
"text": "Example:"
},
{
"code": null,
"e": 25528,
"s": 25526,
"text": "R"
},
{
"code": "# Load Packagelibrary(\"ggplot2\") # Create a DataFrame DF <- data.frame(X = rnorm(10), Y = rnorm(10)) # Create a ScatterPlot with simple labelsggplot(DF,aes(X, Y))+ geom_point(size = 8, fill = \"green\", color = \"black\", shape = 21)+ xlab(\"X-Axis\")+ ylab(\"Y-Axis\")",
"e": 25847,
"s": 25528,
"text": null
},
{
"code": null,
"e": 25855,
"s": 25847,
"text": "Output:"
},
{
"code": null,
"e": 25891,
"s": 25855,
"text": "ScatterPlot with Simple Axis Labels"
},
{
"code": null,
"e": 26053,
"s": 25891,
"text": "Now we will change the label of X to ” X-Axissuperscript ” and Y to ” Y-Axissuperscript “. For that bquote() function is used to quote the argument passed to it."
},
{
"code": null,
"e": 26075,
"s": 26053,
"text": "Syntax : bquote(expr)"
},
{
"code": null,
"e": 26087,
"s": 26075,
"text": "Parameter :"
},
{
"code": null,
"e": 26110,
"s": 26087,
"text": "expr : language object"
},
{
"code": null,
"e": 26137,
"s": 26110,
"text": "bquote() For SuperScript :"
},
{
"code": null,
"e": 26174,
"s": 26137,
"text": "bquote(math superscript(^) Notation)"
},
{
"code": null,
"e": 26183,
"s": 26174,
"text": "Example:"
},
{
"code": null,
"e": 26185,
"s": 26183,
"text": "R"
},
{
"code": "# Load ggplot2 Packagelibrary(\"ggplot2\") # Create a DataFrame For PlottingDF <- data.frame(X = rnorm(10), Y = rnorm(10)) # Create ggplot2 ScatterPlot with SuperScripted # value of Label of Axis.ggplot(DF,aes(X, Y))+ geom_point(size = 8, fill = \"green\", color = \"black\", shape = 21)+ xlab(bquote(X-Axis^superscript))+ ylab(bquote(Y-Axis^superscript))",
"e": 26593,
"s": 26185,
"text": null
},
{
"code": null,
"e": 26601,
"s": 26593,
"text": "Output:"
},
{
"code": null,
"e": 26644,
"s": 26601,
"text": "ScatterPlot with Superscripted Axis Labels"
},
{
"code": null,
"e": 26833,
"s": 26644,
"text": "We will change the label of X to ” X-Axissubscript ” and Y to “ Y-Axissubscript “. For that, we will again use the bquote() function but with different Mathematical Notation for subscript."
},
{
"code": null,
"e": 26858,
"s": 26833,
"text": "bquote() For Subscript :"
},
{
"code": null,
"e": 26894,
"s": 26858,
"text": "bquote(math subscript([]) Notation)"
},
{
"code": null,
"e": 26903,
"s": 26894,
"text": "Example:"
},
{
"code": null,
"e": 26905,
"s": 26903,
"text": "R"
},
{
"code": "# Load ggplot2 Packagelibrary(\"ggplot2\") # Create a DataFrame For PlottingDF <- data.frame(X = rnorm(10), Y = rnorm(10)) # Create ggplot2 ScatterPlot with SubScripted # value of Label of Axis.ggplot(DF,aes(X, Y))+ geom_point(size = 8, fill = \"green\", color = \"black\", shape = 21)+ xlab(bquote(X-Axis[subscript]))+ ylab(bquote(Y-Axis[subscript]))",
"e": 27308,
"s": 26905,
"text": null
},
{
"code": null,
"e": 27317,
"s": 27308,
"text": "Output: "
},
{
"code": null,
"e": 27358,
"s": 27317,
"text": "ScatterPlot with Subscripted Axis Labels"
},
{
"code": null,
"e": 27370,
"s": 27358,
"text": "anikakapoor"
},
{
"code": null,
"e": 27377,
"s": 27370,
"text": "Picked"
},
{
"code": null,
"e": 27386,
"s": 27377,
"text": "R-ggplot"
},
{
"code": null,
"e": 27397,
"s": 27386,
"text": "R Language"
},
{
"code": null,
"e": 27495,
"s": 27397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27504,
"s": 27495,
"text": "Comments"
},
{
"code": null,
"e": 27517,
"s": 27504,
"text": "Old Comments"
},
{
"code": null,
"e": 27561,
"s": 27517,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27613,
"s": 27561,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27665,
"s": 27613,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27697,
"s": 27665,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27735,
"s": 27697,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27793,
"s": 27735,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27828,
"s": 27793,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27864,
"s": 27828,
"text": "K-Means Clustering in R Programming"
},
{
"code": null,
"e": 27913,
"s": 27864,
"text": "Remove rows with NA in one column of R DataFrame"
}
] |
How to create a numpy array within a given range?
|
We have to create a numpy array in the range provided by the user. We will use the arange() function in the numpy library to get our output.
Step1: Import numpy.
Step 2: Take start_value, end_value and Step from the user.
Step 3: Print the array using arange() function in numpy.
import numpy as np
start_val = int(input("Enter starting value: "))
end_val = int(input("Enter ending value: "))
Step_val = int(input("Enter Step value: "))
print(np.arange(start_val, end_val, Step_val))
Enter starting value: 5
Enter ending value: 50
Enter Step value: 5
[ 5 10 15 20 25 30 35 40 45]
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "We have to create a numpy array in the range provided by the user. We will use the arange() function in the numpy library to get our output."
},
{
"code": null,
"e": 1342,
"s": 1203,
"text": "Step1: Import numpy.\nStep 2: Take start_value, end_value and Step from the user.\nStep 3: Print the array using arange() function in numpy."
},
{
"code": null,
"e": 1547,
"s": 1342,
"text": "import numpy as np\n\nstart_val = int(input(\"Enter starting value: \"))\nend_val = int(input(\"Enter ending value: \"))\nStep_val = int(input(\"Enter Step value: \"))\nprint(np.arange(start_val, end_val, Step_val))"
},
{
"code": null,
"e": 1643,
"s": 1547,
"text": "Enter starting value: 5\nEnter ending value: 50\nEnter Step value: 5\n[ 5 10 15 20 25 30 35 40 45]"
}
] |
Convert INT to DATETIME in MySQL?
|
You can use the in-built function from_unixtime() to convert INT to DATETIME. The syntax is as follows −
SELECT FROM_UNIXTIME(yourColumnName,’%Y-%m-%d') as AnyVariableName from
yourTableName;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table IntToDateDemo
-> (
-> Number int
-> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command. The query to insert record is as follows −
mysql> truncate table IntToDateDemo;
Query OK, 0 rows affected (4.11 sec)
mysql> insert into IntToDateDemo values(1545284721);
Query OK, 1 row affected (0.19 sec)
mysql> insert into IntToDateDemo values(1576820738);
Query OK, 1 row affected (0.19 sec)
mysql> insert into IntToDateDemo values(1513748752);
Query OK, 1 row affected (0.24 sec)
mysql> insert into IntToDateDemo values(1671515204);
Query OK, 1 row affected (0.18 sec)
Now you can display all records from the table using select statement. The query is as follows −
mysql> select *from IntToDateDemo;
+------------+
| Number |
+------------+
| 1545284721 |
| 1576820738 |
| 1513748752 |
| 1671515204 |
+------------+
4 rows in set (0.00 sec)
Here is the query that converts int to datetime using from_unixtime() function. The query is as follows −
mysql> select from_unixtime(Number,'%Y-%m-%d') as DateDemo from IntToDateDemo;
The following is the output displaying the converted datetime −
+------------+
| DateDemo |
+------------+
| 2018-12-20 |
| 2019-12-20 |
| 2017-12-20 |
| 2022-12-20 |
+------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1167,
"s": 1062,
"text": "You can use the in-built function from_unixtime() to convert INT to DATETIME. The syntax is as follows −"
},
{
"code": null,
"e": 1254,
"s": 1167,
"text": "SELECT FROM_UNIXTIME(yourColumnName,’%Y-%m-%d') as AnyVariableName from\nyourTableName;"
},
{
"code": null,
"e": 1359,
"s": 1254,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1464,
"s": 1359,
"text": "mysql> create table IntToDateDemo\n -> (\n -> Number int\n -> );\nQuery OK, 0 rows affected (0.59 sec)"
},
{
"code": null,
"e": 1562,
"s": 1464,
"text": "Insert some records in the table using insert command. The query to insert record is as follows −"
},
{
"code": null,
"e": 1996,
"s": 1562,
"text": "mysql> truncate table IntToDateDemo;\nQuery OK, 0 rows affected (4.11 sec)\n\nmysql> insert into IntToDateDemo values(1545284721);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into IntToDateDemo values(1576820738);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into IntToDateDemo values(1513748752);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into IntToDateDemo values(1671515204);\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 2093,
"s": 1996,
"text": "Now you can display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2128,
"s": 2093,
"text": "mysql> select *from IntToDateDemo;"
},
{
"code": null,
"e": 2273,
"s": 2128,
"text": "+------------+\n| Number |\n+------------+\n| 1545284721 |\n| 1576820738 |\n| 1513748752 |\n| 1671515204 |\n+------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2379,
"s": 2273,
"text": "Here is the query that converts int to datetime using from_unixtime() function. The query is as follows −"
},
{
"code": null,
"e": 2458,
"s": 2379,
"text": "mysql> select from_unixtime(Number,'%Y-%m-%d') as DateDemo from IntToDateDemo;"
},
{
"code": null,
"e": 2522,
"s": 2458,
"text": "The following is the output displaying the converted datetime −"
},
{
"code": null,
"e": 2667,
"s": 2522,
"text": "+------------+\n| DateDemo |\n+------------+\n| 2018-12-20 |\n| 2019-12-20 |\n| 2017-12-20 |\n| 2022-12-20 |\n+------------+\n4 rows in set (0.00 sec)"
}
] |
LESS - Parent Selectors
|
In this chapter, let us understand how Parent Selectors work. It is possible to reference the parent selector by using the &(ampersand) operator. Parent selectors of a nested rule is represented by the & operator and is used when applying a modifying class or pseudo class to an existing selector.
The following table shows the types of parent selector −
The & will represent the nearest selector and also all the parent selectors.
Prepending a selector to the inherited (parent) selectors is useful when selector ordering is changed.
The & can also produce all the possible permutation of selectors in a list separated by commas.
The following example demonstrates the use of parent selector in the LESS file −
<!doctype html>
<head>
<link rel = "stylesheet" href = "style.css" type = "text/css" />
<title>Parent Selector</title>
</head>
<body>
<h2>Welcome to TutorialsPoint</h2>
<ul>
<li><a>SASS</a></li>
<li><a>LESS</a></li>
</ul>
</body>
</html>
Next, create the style.less file.
a {
color: #5882FA;
&:hover {
background-color: #A9F5F2;
}
}
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
a {
color: #5882FA;
}
a:hover {
background-color: red;
}
In the above example, & refers to selector a.
Follow these steps to see how the above code works −
Save the above html code in the parent_selector1.htm file.
Save the above html code in the parent_selector1.htm file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.
The Parent selectors operator has many uses like, when you need to combine the nested rule's selectors in other way than the default. Another typical use of & is to generate class names repeatedly. For more information click here.
20 Lectures
1 hours
Anadi Sharma
44 Lectures
7.5 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Zach Miller
23 Lectures
1.5 hours
Zach Miller
34 Lectures
4 hours
Syed Raza
31 Lectures
3 hours
Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2848,
"s": 2550,
"text": "In this chapter, let us understand how Parent Selectors work. It is possible to reference the parent selector by using the &(ampersand) operator. Parent selectors of a nested rule is represented by the & operator and is used when applying a modifying class or pseudo class to an existing selector."
},
{
"code": null,
"e": 2905,
"s": 2848,
"text": "The following table shows the types of parent selector −"
},
{
"code": null,
"e": 2982,
"s": 2905,
"text": "The & will represent the nearest selector and also all the parent selectors."
},
{
"code": null,
"e": 3085,
"s": 2982,
"text": "Prepending a selector to the inherited (parent) selectors is useful when selector ordering is changed."
},
{
"code": null,
"e": 3181,
"s": 3085,
"text": "The & can also produce all the possible permutation of selectors in a list separated by commas."
},
{
"code": null,
"e": 3262,
"s": 3181,
"text": "The following example demonstrates the use of parent selector in the LESS file −"
},
{
"code": null,
"e": 3561,
"s": 3262,
"text": "<!doctype html>\n <head>\n <link rel = \"stylesheet\" href = \"style.css\" type = \"text/css\" />\n <title>Parent Selector</title>\n </head>\n\n <body>\n <h2>Welcome to TutorialsPoint</h2>\n <ul>\n <li><a>SASS</a></li>\n <li><a>LESS</a></li>\n </ul>\n </body>\n</html>"
},
{
"code": null,
"e": 3595,
"s": 3561,
"text": "Next, create the style.less file."
},
{
"code": null,
"e": 3671,
"s": 3595,
"text": "a {\n color: #5882FA;\n &:hover {\n background-color: #A9F5F2;\n }\n}"
},
{
"code": null,
"e": 3753,
"s": 3671,
"text": "You can compile the style.less file to style.css by using the following command −"
},
{
"code": null,
"e": 3781,
"s": 3753,
"text": "lessc style.less style.css\n"
},
{
"code": null,
"e": 3882,
"s": 3781,
"text": "Execute the above command; it will create the style.css file automatically with the following code −"
},
{
"code": null,
"e": 3946,
"s": 3882,
"text": "a {\n color: #5882FA;\n}\n\na:hover {\n background-color: red;\n}"
},
{
"code": null,
"e": 3992,
"s": 3946,
"text": "In the above example, & refers to selector a."
},
{
"code": null,
"e": 4045,
"s": 3992,
"text": "Follow these steps to see how the above code works −"
},
{
"code": null,
"e": 4104,
"s": 4045,
"text": "Save the above html code in the parent_selector1.htm file."
},
{
"code": null,
"e": 4163,
"s": 4104,
"text": "Save the above html code in the parent_selector1.htm file."
},
{
"code": null,
"e": 4238,
"s": 4163,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 4313,
"s": 4238,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 4544,
"s": 4313,
"text": "The Parent selectors operator has many uses like, when you need to combine the nested rule's selectors in other way than the default. Another typical use of & is to generate class names repeatedly. For more information click here."
},
{
"code": null,
"e": 4577,
"s": 4544,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4591,
"s": 4577,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4626,
"s": 4591,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4654,
"s": 4626,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4687,
"s": 4654,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4700,
"s": 4687,
"text": " Zach Miller"
},
{
"code": null,
"e": 4735,
"s": 4700,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4748,
"s": 4735,
"text": " Zach Miller"
},
{
"code": null,
"e": 4781,
"s": 4748,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4792,
"s": 4781,
"text": " Syed Raza"
},
{
"code": null,
"e": 4825,
"s": 4792,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4845,
"s": 4825,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4852,
"s": 4845,
"text": " Print"
},
{
"code": null,
"e": 4863,
"s": 4852,
"text": " Add Notes"
}
] |
3 Top Machine Learning Algorithms | Towards Data Science
|
IntroductionLSTMXGBoostCatBoostSummaryReferences
Introduction
LSTM
XGBoost
CatBoost
Summary
References
There are several machine learning algorithms that you can either study in academia or employ in the workplace, but some might be more useful than others to practice and apply. It can ultimately depend on a few factors, like the problem you are solving, the data you have, the resources your company has, and so on. However, I have seen a few algorithms that seem to be more unique, popular, or more accurate. Keep in mind, these top algorithms are formed by my opinion, and experience as a professional data scientist and interviewer. With that in mind, let’s discuss the reasons why you would want to show off these machine learning algorithms in particular.
I surprisingly have not seen many people include this algorithm, LSTM (long short-term memory), on their resume at all; it is usually one of the popular tree-based algorithms and perhaps a SARIMA model (seasonal auto-regressive integrated moving average) instead. With that being said, the main reason for including this machine learning algorithm on your resume is because it is unique and can essentially set you apart from other applicants.
Not only that, but this algorithm is also useful and can be highly accurate, of course, depending on other factors, but the opportunity does seem to be better than when compared to other similar algorithms. It can also be used for classification and time-series-based problems, as well as be more controllable or flexible in its process.
Here are some of the benefits of putting LSTM on your resume:
It is unique
It is more complex so some people are less willing to learn or master this algorithm
It can be better than RNN because of its flexibility
It has the opportunity to be more accurate or more predictively powerful
As you can see, including and knowing this algorithm can make you a unique applicant.
Perhaps the most popular of the three, this algorithm is more of a core algorithm to include in your toolkit. This algorithm is one that you should know and, of course, include on your resume. Because it is so popular already, it has the benefit of having a lot more documentation.
XGBoot is better at a lot of things, but if you were to rank the tree algorithms I would say it goes from decision trees → random forest → XGBoost, then to another, a new algorithm that I include below.
Here are some further reasons why you would put XGBoost on your resume:
High performance
Often one of the most accurate algorithms, so you can be more competitive
Tons of documentation, examples, so interviewers are familiar with discussing this algorithm more so than the other two
There are countless reasons to use the algorithm itself, but for the purpose of including it on your resume, it will show that you are a steady applicant that has the base knowledge that can be applied to many more algorithms.
Perhaps the most superior, and newest, is CatBoost. Apply everything you know about XGBoost, but add that it is even faster, easier to use, more accurate, and can deal with categorical features exceptionally well. It is so new that some interviewers might not even know about this algorithm yet, so you can really show off on your resume when you include this algorithm, but it is not so far off that they cannot understand it, especially if they are familiar with most tree algorithms and especially XGBoost.
To add to the previously mentioned note, now we can include the final rank to include CatBoost:
Decision trees → random forest → XGBoost → CatBoost
Here are some more reasons you should include CatBoost on your data science resume:
Very new, and will make you more of a competitive applicant
Can show the interviews that you can work with an algorithm that is highly accurate and efficient
Can show that you can work with an algorithm that deals with categorical future well, nearly all algorithms perform poorly in someway with categorical features, like using one-hot-encoding that creates a large, sparse dataframe
... Where you could instead retain the categorical feature column as it is originally, making it easier to collaborate with stakeholders like software engineers, ML engineers, or product matters
As you can see, I included the best for last. CatBoost is a great algorithm for a variety of reasons and is something you should include on your resume.
You cannot go wrong with any of these machine learning algorithms, they are highly useful for different reasons. Whether you are predicting a continuous target, or trying to classify a category, or even predicting a time-series target, these algorithms can all help to produce great results, and that is valuable for you in an interview.
To summarize, here at the top three machine learning algorithms that you should include on your data science resume:
* LSTM* XGBoost* CatBoost
I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these top machine learning algorithms. Why or why not? What other algorithms do you think you include on your data science resume? These can certainly be clarified even further, but I hope I was able to shed some light on data science resumes. Thank you for reading!
I am not affiliated with any of these companies.
Please feel free to check out my profile, Matt Przybyla, and other articles, as well as subscribe to receive email notifications for my blogs by following the link below, or by clicking on the subscribe icon on the top of the screen by the follow icon, and reach out to me on LinkedIn if you have any questions or comments.
Subscribe link: https://datascience2.medium.com/subscribe
[1] Photo by Kote Puerto on Unsplash, (2018)
[2] Photo by Fakurian Design on Unsplash, (2021)
[3] Photo by Johann Siemens on Unsplash, (2014)
[4] Photo by Ludemeula Fernandes on Unsplash, (2017)
|
[
{
"code": null,
"e": 220,
"s": 171,
"text": "IntroductionLSTMXGBoostCatBoostSummaryReferences"
},
{
"code": null,
"e": 233,
"s": 220,
"text": "Introduction"
},
{
"code": null,
"e": 238,
"s": 233,
"text": "LSTM"
},
{
"code": null,
"e": 246,
"s": 238,
"text": "XGBoost"
},
{
"code": null,
"e": 255,
"s": 246,
"text": "CatBoost"
},
{
"code": null,
"e": 263,
"s": 255,
"text": "Summary"
},
{
"code": null,
"e": 274,
"s": 263,
"text": "References"
},
{
"code": null,
"e": 935,
"s": 274,
"text": "There are several machine learning algorithms that you can either study in academia or employ in the workplace, but some might be more useful than others to practice and apply. It can ultimately depend on a few factors, like the problem you are solving, the data you have, the resources your company has, and so on. However, I have seen a few algorithms that seem to be more unique, popular, or more accurate. Keep in mind, these top algorithms are formed by my opinion, and experience as a professional data scientist and interviewer. With that in mind, let’s discuss the reasons why you would want to show off these machine learning algorithms in particular."
},
{
"code": null,
"e": 1379,
"s": 935,
"text": "I surprisingly have not seen many people include this algorithm, LSTM (long short-term memory), on their resume at all; it is usually one of the popular tree-based algorithms and perhaps a SARIMA model (seasonal auto-regressive integrated moving average) instead. With that being said, the main reason for including this machine learning algorithm on your resume is because it is unique and can essentially set you apart from other applicants."
},
{
"code": null,
"e": 1717,
"s": 1379,
"text": "Not only that, but this algorithm is also useful and can be highly accurate, of course, depending on other factors, but the opportunity does seem to be better than when compared to other similar algorithms. It can also be used for classification and time-series-based problems, as well as be more controllable or flexible in its process."
},
{
"code": null,
"e": 1779,
"s": 1717,
"text": "Here are some of the benefits of putting LSTM on your resume:"
},
{
"code": null,
"e": 1792,
"s": 1779,
"text": "It is unique"
},
{
"code": null,
"e": 1877,
"s": 1792,
"text": "It is more complex so some people are less willing to learn or master this algorithm"
},
{
"code": null,
"e": 1930,
"s": 1877,
"text": "It can be better than RNN because of its flexibility"
},
{
"code": null,
"e": 2003,
"s": 1930,
"text": "It has the opportunity to be more accurate or more predictively powerful"
},
{
"code": null,
"e": 2089,
"s": 2003,
"text": "As you can see, including and knowing this algorithm can make you a unique applicant."
},
{
"code": null,
"e": 2371,
"s": 2089,
"text": "Perhaps the most popular of the three, this algorithm is more of a core algorithm to include in your toolkit. This algorithm is one that you should know and, of course, include on your resume. Because it is so popular already, it has the benefit of having a lot more documentation."
},
{
"code": null,
"e": 2574,
"s": 2371,
"text": "XGBoot is better at a lot of things, but if you were to rank the tree algorithms I would say it goes from decision trees → random forest → XGBoost, then to another, a new algorithm that I include below."
},
{
"code": null,
"e": 2646,
"s": 2574,
"text": "Here are some further reasons why you would put XGBoost on your resume:"
},
{
"code": null,
"e": 2663,
"s": 2646,
"text": "High performance"
},
{
"code": null,
"e": 2737,
"s": 2663,
"text": "Often one of the most accurate algorithms, so you can be more competitive"
},
{
"code": null,
"e": 2857,
"s": 2737,
"text": "Tons of documentation, examples, so interviewers are familiar with discussing this algorithm more so than the other two"
},
{
"code": null,
"e": 3084,
"s": 2857,
"text": "There are countless reasons to use the algorithm itself, but for the purpose of including it on your resume, it will show that you are a steady applicant that has the base knowledge that can be applied to many more algorithms."
},
{
"code": null,
"e": 3594,
"s": 3084,
"text": "Perhaps the most superior, and newest, is CatBoost. Apply everything you know about XGBoost, but add that it is even faster, easier to use, more accurate, and can deal with categorical features exceptionally well. It is so new that some interviewers might not even know about this algorithm yet, so you can really show off on your resume when you include this algorithm, but it is not so far off that they cannot understand it, especially if they are familiar with most tree algorithms and especially XGBoost."
},
{
"code": null,
"e": 3690,
"s": 3594,
"text": "To add to the previously mentioned note, now we can include the final rank to include CatBoost:"
},
{
"code": null,
"e": 3742,
"s": 3690,
"text": "Decision trees → random forest → XGBoost → CatBoost"
},
{
"code": null,
"e": 3826,
"s": 3742,
"text": "Here are some more reasons you should include CatBoost on your data science resume:"
},
{
"code": null,
"e": 3886,
"s": 3826,
"text": "Very new, and will make you more of a competitive applicant"
},
{
"code": null,
"e": 3984,
"s": 3886,
"text": "Can show the interviews that you can work with an algorithm that is highly accurate and efficient"
},
{
"code": null,
"e": 4212,
"s": 3984,
"text": "Can show that you can work with an algorithm that deals with categorical future well, nearly all algorithms perform poorly in someway with categorical features, like using one-hot-encoding that creates a large, sparse dataframe"
},
{
"code": null,
"e": 4407,
"s": 4212,
"text": "... Where you could instead retain the categorical feature column as it is originally, making it easier to collaborate with stakeholders like software engineers, ML engineers, or product matters"
},
{
"code": null,
"e": 4560,
"s": 4407,
"text": "As you can see, I included the best for last. CatBoost is a great algorithm for a variety of reasons and is something you should include on your resume."
},
{
"code": null,
"e": 4898,
"s": 4560,
"text": "You cannot go wrong with any of these machine learning algorithms, they are highly useful for different reasons. Whether you are predicting a continuous target, or trying to classify a category, or even predicting a time-series target, these algorithms can all help to produce great results, and that is valuable for you in an interview."
},
{
"code": null,
"e": 5015,
"s": 4898,
"text": "To summarize, here at the top three machine learning algorithms that you should include on your data science resume:"
},
{
"code": null,
"e": 5041,
"s": 5015,
"text": "* LSTM* XGBoost* CatBoost"
},
{
"code": null,
"e": 5434,
"s": 5041,
"text": "I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these top machine learning algorithms. Why or why not? What other algorithms do you think you include on your data science resume? These can certainly be clarified even further, but I hope I was able to shed some light on data science resumes. Thank you for reading!"
},
{
"code": null,
"e": 5483,
"s": 5434,
"text": "I am not affiliated with any of these companies."
},
{
"code": null,
"e": 5807,
"s": 5483,
"text": "Please feel free to check out my profile, Matt Przybyla, and other articles, as well as subscribe to receive email notifications for my blogs by following the link below, or by clicking on the subscribe icon on the top of the screen by the follow icon, and reach out to me on LinkedIn if you have any questions or comments."
},
{
"code": null,
"e": 5865,
"s": 5807,
"text": "Subscribe link: https://datascience2.medium.com/subscribe"
},
{
"code": null,
"e": 5910,
"s": 5865,
"text": "[1] Photo by Kote Puerto on Unsplash, (2018)"
},
{
"code": null,
"e": 5959,
"s": 5910,
"text": "[2] Photo by Fakurian Design on Unsplash, (2021)"
},
{
"code": null,
"e": 6007,
"s": 5959,
"text": "[3] Photo by Johann Siemens on Unsplash, (2014)"
}
] |
Visualizing a Sparse Matrix. How do you know if you have a sparse... | by Kamil Mysiak | Towards Data Science
|
Many areas in machine learning commonly employ the use of a sparse matrix. If you have ever vectorized a NLP dictionary using One-Hot-Encoding, CountVectorizing or TfidVectorizing you know what I’m pertaining to.
In simplest terms, a sparse matrix is one containing many zeros and a dense matrix which does not.
import scipy.sparse as sparseimport matplotlib.pyplot as plt%matplotlib inline# adjust the density parametersparse = sparse.random(10,10, density=0.015)sparse.toarray()
plt.figure(figsize=(15, 15))plt.spy(sparse, markersize=1)
I’m currently working with an NLP dictionary of over 15,000 words and I always wanted to see what a sparse matrix of that size would look life. Enjoy!
|
[
{
"code": null,
"e": 385,
"s": 172,
"text": "Many areas in machine learning commonly employ the use of a sparse matrix. If you have ever vectorized a NLP dictionary using One-Hot-Encoding, CountVectorizing or TfidVectorizing you know what I’m pertaining to."
},
{
"code": null,
"e": 484,
"s": 385,
"text": "In simplest terms, a sparse matrix is one containing many zeros and a dense matrix which does not."
},
{
"code": null,
"e": 653,
"s": 484,
"text": "import scipy.sparse as sparseimport matplotlib.pyplot as plt%matplotlib inline# adjust the density parametersparse = sparse.random(10,10, density=0.015)sparse.toarray()"
},
{
"code": null,
"e": 711,
"s": 653,
"text": "plt.figure(figsize=(15, 15))plt.spy(sparse, markersize=1)"
}
] |
How to find the range for 95% of all values in an R vector?
|
The range for 95% of all values actually represents the middle 95% values. Therefore, we can find the 2.5th percentile and 97.5th percentile so that the range for middle 95% can be obtained. For this purpose, we can use quantile function in R. To find the 2.5th percentile, we would need to use the probability = 0.025 and for the 97.5th percentile we can use probability = 0.0975.
Live Demo
x1<-1:10
x1
[1] 1 2 3 4 5 6 7 8 9 10
quantile(x1,probs=c(0.025,0.975))
2.5% 97.5%
1.225 9.775
Live Demo
x2<-sample(0:9,200,replace=TRUE)
x2
[1] 8 1 5 4 7 9 7 4 3 9 3 0 5 4 4 3 8 2 7 7 4 0 1 8 2 1 0 2 6 3 3 5 7 0 9 6 9
[38] 1 3 2 7 9 2 3 9 0 5 2 7 6 6 2 4 5 1 6 6 7 9 8 5 7 5 4 8 4 3 3 8 6 1 1 1 9
[75] 6 2 0 9 8 0 2 2 2 6 2 8 8 7 4 5 1 0 1 3 7 9 5 4 5 2 5 5 4 7 5 4 5 6 6 2 9
[112] 6 9 2 7 1 5 0 1 4 7 0 8 8 2 5 4 9 4 8 4 0 7 2 1 7 0 6 5 2 5 6 3 2 1 5 6 6
[149] 6 0 4 1 8 7 1 5 0 1 8 9 8 6 8 7 6 8 4 3 9 3 9 2 0 3 8 3 7 8 9 6 4 3 4 5 6
[186] 4 1 6 0 5 8 1 5 1 3 7 2 3 3 3
> quantile(x2,probs=c(0.025,0.975))
2.5% 97.5%
0 9
Live Demo
x3<-sample(1:100,200,replace=TRUE)
x3
[1] 14 49 72 45 19 80 43 88 73 100 83 55 10 50 71 69 47 22
[19] 15 99 30 2 51 89 69 66 87 25 59 34 77 40 40 44 41 5
[37] 75 35 33 40 7 40 64 17 79 77 27 49 8 20 30 29 15 67
[55] 36 18 53 80 57 71 96 40 12 92 94 87 14 17 43 73 90 28
[73] 44 41 47 44 57 23 54 88 64 26 33 80 44 9 2 49 36 40
[91] 38 74 48 49 75 83 71 55 8 99 32 8 89 23 62 86 4 14
[109] 33 30 1 77 73 3 66 90 39 84 73 25 45 74 33 97 46 82
[127] 68 6 18 43 20 76 42 69 52 98 14 27 13 62 33 65 16 100
[145] 9 5 22 29 3 30 91 63 25 86 71 75 36 85 56 80 42 89
[163] 56 44 16 23 94 13 14 89 83 100 40 94 36 85 74 57 77 95
[181] 23 84 53 1 48 62 92 27 8 32 63 52 99 10 12 71 59 64
[199] 42 54
quantile(x3,probs=c(0.025,0.975))
2.5% 97.5%
3 99
Live Demo
x4<-sample(100:999,200)
x4
[1] 820 234 148 100 865 811 694 864 197 140 815 588 158 521 542 115 675 932
[19] 169 494 257 549 963 340 595 814 324 182 952 291 936 601 743 794 610 377
[37] 495 179 284 739 484 901 627 376 609 220 784 418 721 488 738 944 712 458
[55] 551 166 138 857 801 785 500 722 989 394 517 640 238 688 485 426 637 133
[73] 881 504 625 809 445 916 200 802 306 955 581 937 466 639 247 502 146 740
[91] 413 655 767 996 886 935 723 361 286 131 269 167 186 959 396 805 665 218
[109] 696 883 253 454 400 949 175 777 758 971 691 395 603 435 934 406 843 281
[127] 553 976 267 888 127 913 178 987 787 354 290 977 225 539 995 803 419 288
[145] 221 294 550 442 525 782 366 586 501 875 567 543 828 451 830 821 992 342
[163] 737 611 806 753 876 487 449 313 719 578 983 160 768 556 933 680 956 375
[181] 761 678 279 398 755 139 330 686 824 321 819 335 580 674 348 671 246 509
[199] 447 499
quantile(x4,probs=c(0.025,0.975))
2.5% 97.5%
137.875 983.100
Live Demo
x5<-rnorm(80,5,2)
x5
[1] 6.98972600 3.17248565 5.13234480 4.11901047 7.77081721 4.70660218
[7] 4.34543482 5.32969562 3.85105871 4.92334515 10.38088424 2.78494280
[13] 2.17723638 5.89778299 3.25433020 5.76595115 6.58821842 2.16789176
[19] 6.70022121 4.33298204 2.52347763 7.17797129 5.96444881 -0.49521879
[25] 3.32652489 6.36352461 7.02582094 4.76756040 0.05690139 3.60584007
[31] 6.43240996 1.91232232 4.03257916 9.08311081 8.88715843 7.76594592
[37] 5.80933391 3.37731011 3.14555718 6.14552974 5.65748181 2.88725211
[43] 6.81291913 5.28996898 6.84361973 4.71988891 3.13190129 3.45525499
[49] 6.02927444 4.99564376 7.46594963 0.70237604 5.29670524 4.31319790
[55] 4.31986763 2.19272850 4.03273654 6.97718448 4.50745487 4.36807171
[61] 7.39283829 2.14748082 4.48435806 4.51189441 5.35723362 8.93982200
[67] 6.83182644 4.27771018 7.26854753 3.78881429 4.19227762 4.24381458
[73] 2.93295093 7.40268495 3.35842472 3.73021960 5.85442187 7.90967270
[79] 2.90778517 6.01023427
quantile(x5,probs=c(0.025,0.975))
2.5% 97.5%
0.6862392 8.9434042
Live Demo
x6<-rnorm(50)
x6
[1] 0.3331076074 0.6607651759 0.0240865785 -0.1448891552 -0.6969449129
[6] 0.0166860867 -1.2130240135 -0.9468299995 0.7802634147 0.9585927355
[11] -1.6272935094 1.3593188263 -0.0935888333 2.0885770523 -0.4199458516
[16] -0.0089055888 -0.1935638804 -1.6772774160 -2.0102456085 0.0009071378
[21] 1.9596100041 0.3502070761 0.6889992063 0.9485294768 0.4670174843
[26] 0.4977238683 -0.2571625431 -0.2327554066 -0.7488511452 0.7068129587
[31] 0.6054530742 1.6431915914 0.8637796961 -0.3100868562 1.9966920903
[36] 0.1412141929 0.3438465534 -0.3179982685 0.5358806944 1.9328734967
[41] -0.4732611071 -0.3964032732 -0.6116624673 -0.4275941636 0.3976625756
[46] 1.1928187412 0.5876758446 0.2999995481 0.3585979367 0.2490096352
quantile(x6,probs=c(0.025,0.975))
2.5% 97.5%
-1.666031 1.988349
Live Demo
x7<-rpois(120,5)
x7
[1] 5 4 8 6 7 6 2 7 6 1 8 6 6 1 6 7 5 2 7 3 8 5 6 6 7
[26] 1 5 8 6 0 1 1 4 5 5 7 4 2 5 6 4 6 13 12 4 5 4 3 3 2
[51] 5 6 4 5 3 8 2 2 6 4 3 4 4 9 5 1 5 5 5 7 9 2 1 6 2
[76] 5 6 7 3 7 9 4 2 3 3 1 5 3 5 7 10 7 3 4 2 4 7 3 3 5
[101] 6 4 4 3 4 2 6 3 5 6 2 9 2 2 2 6 5 3 7 3
quantile(x7,probs=c(0.025,0.975))
2.5% 97.5%
1.000 9.025
|
[
{
"code": null,
"e": 1444,
"s": 1062,
"text": "The range for 95% of all values actually represents the middle 95% values. Therefore, we can find the 2.5th percentile and 97.5th percentile so that the range for middle 95% can be obtained. For this purpose, we can use quantile function in R. To find the 2.5th percentile, we would need to use the probability = 0.025 and for the 97.5th percentile we can use probability = 0.0975."
},
{
"code": null,
"e": 1455,
"s": 1444,
"text": " Live Demo"
},
{
"code": null,
"e": 1467,
"s": 1455,
"text": "x1<-1:10\nx1"
},
{
"code": null,
"e": 1492,
"s": 1467,
"text": "[1] 1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 1526,
"s": 1492,
"text": "quantile(x1,probs=c(0.025,0.975))"
},
{
"code": null,
"e": 1549,
"s": 1526,
"text": "2.5% 97.5%\n1.225 9.775"
},
{
"code": null,
"e": 1560,
"s": 1549,
"text": " Live Demo"
},
{
"code": null,
"e": 1596,
"s": 1560,
"text": "x2<-sample(0:9,200,replace=TRUE)\nx2"
},
{
"code": null,
"e": 2028,
"s": 1596,
"text": "[1] 8 1 5 4 7 9 7 4 3 9 3 0 5 4 4 3 8 2 7 7 4 0 1 8 2 1 0 2 6 3 3 5 7 0 9 6 9\n[38] 1 3 2 7 9 2 3 9 0 5 2 7 6 6 2 4 5 1 6 6 7 9 8 5 7 5 4 8 4 3 3 8 6 1 1 1 9\n[75] 6 2 0 9 8 0 2 2 2 6 2 8 8 7 4 5 1 0 1 3 7 9 5 4 5 2 5 5 4 7 5 4 5 6 6 2 9\n[112] 6 9 2 7 1 5 0 1 4 7 0 8 8 2 5 4 9 4 8 4 0 7 2 1 7 0 6 5 2 5 6 3 2 1 5 6 6\n[149] 6 0 4 1 8 7 1 5 0 1 8 9 8 6 8 7 6 8 4 3 9 3 9 2 0 3 8 3 7 8 9 6 4 3 4 5 6\n[186] 4 1 6 0 5 8 1 5 1 3 7 2 3 3 3"
},
{
"code": null,
"e": 2064,
"s": 2028,
"text": "> quantile(x2,probs=c(0.025,0.975))"
},
{
"code": null,
"e": 2079,
"s": 2064,
"text": "2.5% 97.5%\n0 9"
},
{
"code": null,
"e": 2090,
"s": 2079,
"text": " Live Demo"
},
{
"code": null,
"e": 2128,
"s": 2090,
"text": "x3<-sample(1:100,200,replace=TRUE)\nx3"
},
{
"code": null,
"e": 2779,
"s": 2128,
"text": "[1] 14 49 72 45 19 80 43 88 73 100 83 55 10 50 71 69 47 22\n[19] 15 99 30 2 51 89 69 66 87 25 59 34 77 40 40 44 41 5\n[37] 75 35 33 40 7 40 64 17 79 77 27 49 8 20 30 29 15 67\n[55] 36 18 53 80 57 71 96 40 12 92 94 87 14 17 43 73 90 28\n[73] 44 41 47 44 57 23 54 88 64 26 33 80 44 9 2 49 36 40\n[91] 38 74 48 49 75 83 71 55 8 99 32 8 89 23 62 86 4 14\n[109] 33 30 1 77 73 3 66 90 39 84 73 25 45 74 33 97 46 82\n[127] 68 6 18 43 20 76 42 69 52 98 14 27 13 62 33 65 16 100\n[145] 9 5 22 29 3 30 91 63 25 86 71 75 36 85 56 80 42 89\n[163] 56 44 16 23 94 13 14 89 83 100 40 94 36 85 74 57 77 95\n[181] 23 84 53 1 48 62 92 27 8 32 63 52 99 10 12 71 59 64\n[199] 42 54"
},
{
"code": null,
"e": 2813,
"s": 2779,
"text": "quantile(x3,probs=c(0.025,0.975))"
},
{
"code": null,
"e": 2829,
"s": 2813,
"text": "2.5% 97.5%\n3 99"
},
{
"code": null,
"e": 2840,
"s": 2829,
"text": " Live Demo"
},
{
"code": null,
"e": 2867,
"s": 2840,
"text": "x4<-sample(100:999,200)\nx4"
},
{
"code": null,
"e": 3732,
"s": 2867,
"text": "[1] 820 234 148 100 865 811 694 864 197 140 815 588 158 521 542 115 675 932\n[19] 169 494 257 549 963 340 595 814 324 182 952 291 936 601 743 794 610 377\n[37] 495 179 284 739 484 901 627 376 609 220 784 418 721 488 738 944 712 458\n[55] 551 166 138 857 801 785 500 722 989 394 517 640 238 688 485 426 637 133\n[73] 881 504 625 809 445 916 200 802 306 955 581 937 466 639 247 502 146 740\n[91] 413 655 767 996 886 935 723 361 286 131 269 167 186 959 396 805 665 218\n[109] 696 883 253 454 400 949 175 777 758 971 691 395 603 435 934 406 843 281\n[127] 553 976 267 888 127 913 178 987 787 354 290 977 225 539 995 803 419 288\n[145] 221 294 550 442 525 782 366 586 501 875 567 543 828 451 830 821 992 342\n[163] 737 611 806 753 876 487 449 313 719 578 983 160 768 556 933 680 956 375\n[181] 761 678 279 398 755 139 330 686 824 321 819 335 580 674 348 671 246 509\n[199] 447 499"
},
{
"code": null,
"e": 3766,
"s": 3732,
"text": "quantile(x4,probs=c(0.025,0.975))"
},
{
"code": null,
"e": 3793,
"s": 3766,
"text": "2.5% 97.5%\n137.875 983.100"
},
{
"code": null,
"e": 3804,
"s": 3793,
"text": " Live Demo"
},
{
"code": null,
"e": 3825,
"s": 3804,
"text": "x5<-rnorm(80,5,2)\nx5"
},
{
"code": null,
"e": 4775,
"s": 3825,
"text": "[1] 6.98972600 3.17248565 5.13234480 4.11901047 7.77081721 4.70660218\n[7] 4.34543482 5.32969562 3.85105871 4.92334515 10.38088424 2.78494280\n[13] 2.17723638 5.89778299 3.25433020 5.76595115 6.58821842 2.16789176\n[19] 6.70022121 4.33298204 2.52347763 7.17797129 5.96444881 -0.49521879\n[25] 3.32652489 6.36352461 7.02582094 4.76756040 0.05690139 3.60584007\n[31] 6.43240996 1.91232232 4.03257916 9.08311081 8.88715843 7.76594592\n[37] 5.80933391 3.37731011 3.14555718 6.14552974 5.65748181 2.88725211\n[43] 6.81291913 5.28996898 6.84361973 4.71988891 3.13190129 3.45525499\n[49] 6.02927444 4.99564376 7.46594963 0.70237604 5.29670524 4.31319790\n[55] 4.31986763 2.19272850 4.03273654 6.97718448 4.50745487 4.36807171\n[61] 7.39283829 2.14748082 4.48435806 4.51189441 5.35723362 8.93982200\n[67] 6.83182644 4.27771018 7.26854753 3.78881429 4.19227762 4.24381458\n[73] 2.93295093 7.40268495 3.35842472 3.73021960 5.85442187 7.90967270\n[79] 2.90778517 6.01023427"
},
{
"code": null,
"e": 4809,
"s": 4775,
"text": "quantile(x5,probs=c(0.025,0.975))"
},
{
"code": null,
"e": 4840,
"s": 4809,
"text": "2.5% 97.5%\n0.6862392 8.9434042"
},
{
"code": null,
"e": 4851,
"s": 4840,
"text": " Live Demo"
},
{
"code": null,
"e": 4868,
"s": 4851,
"text": "x6<-rnorm(50)\nx6"
},
{
"code": null,
"e": 5586,
"s": 4868,
"text": "[1] 0.3331076074 0.6607651759 0.0240865785 -0.1448891552 -0.6969449129\n[6] 0.0166860867 -1.2130240135 -0.9468299995 0.7802634147 0.9585927355\n[11] -1.6272935094 1.3593188263 -0.0935888333 2.0885770523 -0.4199458516\n[16] -0.0089055888 -0.1935638804 -1.6772774160 -2.0102456085 0.0009071378\n[21] 1.9596100041 0.3502070761 0.6889992063 0.9485294768 0.4670174843\n[26] 0.4977238683 -0.2571625431 -0.2327554066 -0.7488511452 0.7068129587\n[31] 0.6054530742 1.6431915914 0.8637796961 -0.3100868562 1.9966920903\n[36] 0.1412141929 0.3438465534 -0.3179982685 0.5358806944 1.9328734967\n[41] -0.4732611071 -0.3964032732 -0.6116624673 -0.4275941636 0.3976625756\n[46] 1.1928187412 0.5876758446 0.2999995481 0.3585979367 0.2490096352"
},
{
"code": null,
"e": 5620,
"s": 5586,
"text": "quantile(x6,probs=c(0.025,0.975))"
},
{
"code": null,
"e": 5650,
"s": 5620,
"text": "2.5% 97.5%\n-1.666031 1.988349"
},
{
"code": null,
"e": 5661,
"s": 5650,
"text": " Live Demo"
},
{
"code": null,
"e": 5681,
"s": 5661,
"text": "x7<-rpois(120,5)\nx7"
},
{
"code": null,
"e": 5949,
"s": 5681,
"text": "[1] 5 4 8 6 7 6 2 7 6 1 8 6 6 1 6 7 5 2 7 3 8 5 6 6 7\n[26] 1 5 8 6 0 1 1 4 5 5 7 4 2 5 6 4 6 13 12 4 5 4 3 3 2\n[51] 5 6 4 5 3 8 2 2 6 4 3 4 4 9 5 1 5 5 5 7 9 2 1 6 2\n[76] 5 6 7 3 7 9 4 2 3 3 1 5 3 5 7 10 7 3 4 2 4 7 3 3 5\n[101] 6 4 4 3 4 2 6 3 5 6 2 9 2 2 2 6 5 3 7 3"
},
{
"code": null,
"e": 5983,
"s": 5949,
"text": "quantile(x7,probs=c(0.025,0.975))"
},
{
"code": null,
"e": 6006,
"s": 5983,
"text": "2.5% 97.5%\n1.000 9.025"
}
] |
How to find the sum of every n values in R data frame columns?
|
To find the sum of every n values in R data frame columns, we can use rowsum function along with rep function that will repeat the sum for rows. For example, if we have a data frame called df that contains 4 columns each containing twenty values then we can find the column sums for every 5 rows by using the command rowsum(df,rep(1:5,each=4)).
Consider the below data frame −
Live Demo
x1<-rpois(20,5)
x2<-rpois(20,2)
df1<-data.frame(x1,x2)
df1
x1 x2
1 7 3
2 9 4
3 7 3
4 3 3
5 9 1
6 4 1
7 7 3
8 4 3
9 6 3
10 5 0
11 4 4
12 5 4
13 5 1
14 6 2
15 1 3
16 1 2
17 6 1
18 6 2
19 1 2
20 8 2
Finding the column sums for every 5 rows in df1 −
rowsum(df1,rep(1:5,each=4))
x1 x2
1 26 13
2 24 8
3 20 11
4 13 8
5 21 7
Live Demo
y1<-rnorm(20)
y2<-rnorm(20)
y3<-rnorm(20)
df2<-data.frame(y1,y2,y3)
df2
y1 y2 y3
1 -0.46478980 0.61742170 -0.21406143
2 1.42820694 -1.68668632 -1.69183062
3 -1.09014651 -0.80538397 -1.73060665
4 0.04143155 -0.86250648 -0.50698176
5 1.31066192 1.98317492 0.81144732
6 1.05362995 1.31032857 -0.48538293
7 1.13221772 3.27862204 -1.42116882
8 -2.30864576 -0.02998736 -0.35898649
9 -1.30371212 0.26152070 -0.25968593
10 -0.93208053 0.59726153 0.31393063
11 0.23612475 1.72240765 -2.21882009
12 0.58740869 0.53739269 0.52578465
13 0.42427296 -0.84617072 -0.35684917
14 -0.33885432 0.09297437 -0.61340922
15 -0.40246042 -0.94370468 0.01108134
16 -0.97853686 1.08559425 0.71596796
17 0.28577367 -0.57999260 -0.14349388
18 -0.78154458 -2.40582173 2.50692776
19 0.05791671 0.94479521 0.79723502
20 -0.03289249 -1.46621425 -0.89169830
Finding the column sums for every 5 rows in df2 −
rowsum(df2,rep(1:5,each=4))
y1 y2 y3
1 -0.08529781 -2.7371551 -4.1434804
2 1.18786383 6.5421382 -1.4540909
3 -1.41225921 3.1185826 -1.6387907
4 -1.29557865 -0.6113068 -0.2432091
5 -0.47074670 -3.5072334 2.2689706
|
[
{
"code": null,
"e": 1407,
"s": 1062,
"text": "To find the sum of every n values in R data frame columns, we can use rowsum function along with rep function that will repeat the sum for rows. For example, if we have a data frame called df that contains 4 columns each containing twenty values then we can find the column sums for every 5 rows by using the command rowsum(df,rep(1:5,each=4))."
},
{
"code": null,
"e": 1439,
"s": 1407,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1450,
"s": 1439,
"text": " Live Demo"
},
{
"code": null,
"e": 1509,
"s": 1450,
"text": "x1<-rpois(20,5)\nx2<-rpois(20,2)\ndf1<-data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1678,
"s": 1509,
"text": " x1 x2\n1 7 3\n2 9 4\n3 7 3\n4 3 3\n5 9 1\n6 4 1\n7 7 3\n8 4 3\n9 6 3\n10 5 0\n11 4 4\n12 5 4\n13 5 1\n14 6 2\n15 1 3\n16 1 2\n17 6 1\n18 6 2\n19 1 2\n20 8 2"
},
{
"code": null,
"e": 1728,
"s": 1678,
"text": "Finding the column sums for every 5 rows in df1 −"
},
{
"code": null,
"e": 1756,
"s": 1728,
"text": "rowsum(df1,rep(1:5,each=4))"
},
{
"code": null,
"e": 1809,
"s": 1756,
"text": " x1 x2\n1 26 13\n2 24 8\n3 20 11\n4 13 8\n5 21 7"
},
{
"code": null,
"e": 1820,
"s": 1809,
"text": " Live Demo"
},
{
"code": null,
"e": 1892,
"s": 1820,
"text": "y1<-rnorm(20)\ny2<-rnorm(20)\ny3<-rnorm(20)\ndf2<-data.frame(y1,y2,y3)\ndf2"
},
{
"code": null,
"e": 2747,
"s": 1892,
"text": " y1 y2 y3\n1 -0.46478980 0.61742170 -0.21406143\n2 1.42820694 -1.68668632 -1.69183062\n3 -1.09014651 -0.80538397 -1.73060665\n4 0.04143155 -0.86250648 -0.50698176\n5 1.31066192 1.98317492 0.81144732\n6 1.05362995 1.31032857 -0.48538293\n7 1.13221772 3.27862204 -1.42116882\n8 -2.30864576 -0.02998736 -0.35898649\n9 -1.30371212 0.26152070 -0.25968593\n10 -0.93208053 0.59726153 0.31393063\n11 0.23612475 1.72240765 -2.21882009\n12 0.58740869 0.53739269 0.52578465\n13 0.42427296 -0.84617072 -0.35684917\n14 -0.33885432 0.09297437 -0.61340922\n15 -0.40246042 -0.94370468 0.01108134\n16 -0.97853686 1.08559425 0.71596796\n17 0.28577367 -0.57999260 -0.14349388\n18 -0.78154458 -2.40582173 2.50692776\n19 0.05791671 0.94479521 0.79723502\n20 -0.03289249 -1.46621425 -0.89169830"
},
{
"code": null,
"e": 2797,
"s": 2747,
"text": "Finding the column sums for every 5 rows in df2 −"
},
{
"code": null,
"e": 2825,
"s": 2797,
"text": "rowsum(df2,rep(1:5,each=4))"
},
{
"code": null,
"e": 3055,
"s": 2825,
"text": " y1 y2 y3\n1 -0.08529781 -2.7371551 -4.1434804\n2 1.18786383 6.5421382 -1.4540909\n3 -1.41225921 3.1185826 -1.6387907\n4 -1.29557865 -0.6113068 -0.2432091\n5 -0.47074670 -3.5072334 2.2689706"
}
] |
How to draw a png image on a Python tkinter canvas?
|
To work with images in tkinter, Python provides PIL or Pillow toolkit. It has many built-in functions that can be used to operate an image of different formats.
To open an image in a canvas widget, we have use create_image(x, y, image, **options) constructor. When we pass the Image value to the constructor, it will display the image in the canvas.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x600")
# Create a canvas widget
canvas=Canvas(win, width=700, height=600)
canvas.pack()
# Load the image
img=ImageTk.PhotoImage(file="Monalisa.png")
# Add the image in the canvas
canvas.create_image(350, 400, image=img, anchor="center")
win.mainloop()
Running the above code will display a window that contains image in the canvas.
|
[
{
"code": null,
"e": 1223,
"s": 1062,
"text": "To work with images in tkinter, Python provides PIL or Pillow toolkit. It has many built-in functions that can be used to operate an image of different formats."
},
{
"code": null,
"e": 1412,
"s": 1223,
"text": "To open an image in a canvas widget, we have use create_image(x, y, image, **options) constructor. When we pass the Image value to the constructor, it will display the image in the canvas."
},
{
"code": null,
"e": 1858,
"s": 1412,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x600\")\n\n# Create a canvas widget\ncanvas=Canvas(win, width=700, height=600)\ncanvas.pack()\n\n# Load the image\nimg=ImageTk.PhotoImage(file=\"Monalisa.png\")\n\n# Add the image in the canvas\ncanvas.create_image(350, 400, image=img, anchor=\"center\")\n\nwin.mainloop()"
},
{
"code": null,
"e": 1938,
"s": 1858,
"text": "Running the above code will display a window that contains image in the canvas."
}
] |
Count Number of Characters in String in R - GeeksforGeeks
|
16 May, 2021
In this article, we will discuss how to find the number of characters in a string using R Programming Language. The number of characters in a string means the length of the string.
Examples:
Input: Geeksforgeeks
Output: 13
Explanation: Total 13 characters in the given string.
Input: Hello world
Output: 11
This can be calculated using the below-mentioned functions:
Using nchar() method
Using str_length() method
Using stri_length() method
Method 1: Using nchar() method.
nchar() method in R programming is used to get the length of a string.
Syntax: nchar(string)
Parameter: string
Return: Returns the length of a string
Code:
R
# R program to calculate length # of string # Given Stringgfg <- "Geeks For Geeks" # Using nchar() methodanswer <- nchar(gfg) print(answer)
Output:
[1] 15
This method can be used to return the length of multiple strings passed as a parameter.
Code:
R
nchar(c("Hello World!","Akshit"));
Output:
[1] 12 6
Method 2. Using str_length () method.
The function str_length() belonging to the ‘stringr’ package can be used to determine the length of strings in R.
Syntax: str_length (str)
Parameter: string as str
Return value: Length of string
Code:
R
# R program for finding length# of string # Importing packagelibrary(stringr) # Calculating length of string str_length("hello")
Output:
[1] 5
This method can be used to return the length of multiple strings passed as a parameter.
Code:
R
# Codelibrary(stringr); str_length(c("Hello World!","Akshit"));
Output:
[1] 12 6
Method 3. Using stri_length() method.
This function returns the number of code points in each string.
Syntax: stri_length(str)
Parameter: str as character vector
Return Value: Returns an integer vector of the same length as str.
Note that the number of code points is not the same as the `width` of the string when printed on the console.
Code:
R
library(stringi); stri_length(c("Akshit"));
Output:
[1] 6
This method can be used to return the length of multiple strings passed as a parameter.
R
library(stringi); stri_length(c("Hello World","Akshit"));
Output:
[1] 11 6
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 25424,
"s": 25242,
"text": "In this article, we will discuss how to find the number of characters in a string using R Programming Language. The number of characters in a string means the length of the string. "
},
{
"code": null,
"e": 25434,
"s": 25424,
"text": "Examples:"
},
{
"code": null,
"e": 25455,
"s": 25434,
"text": "Input: Geeksforgeeks"
},
{
"code": null,
"e": 25466,
"s": 25455,
"text": "Output: 13"
},
{
"code": null,
"e": 25520,
"s": 25466,
"text": "Explanation: Total 13 characters in the given string."
},
{
"code": null,
"e": 25539,
"s": 25520,
"text": "Input: Hello world"
},
{
"code": null,
"e": 25550,
"s": 25539,
"text": "Output: 11"
},
{
"code": null,
"e": 25610,
"s": 25550,
"text": "This can be calculated using the below-mentioned functions:"
},
{
"code": null,
"e": 25631,
"s": 25610,
"text": "Using nchar() method"
},
{
"code": null,
"e": 25657,
"s": 25631,
"text": "Using str_length() method"
},
{
"code": null,
"e": 25684,
"s": 25657,
"text": "Using stri_length() method"
},
{
"code": null,
"e": 25716,
"s": 25684,
"text": "Method 1: Using nchar() method."
},
{
"code": null,
"e": 25787,
"s": 25716,
"text": "nchar() method in R programming is used to get the length of a string."
},
{
"code": null,
"e": 25809,
"s": 25787,
"text": "Syntax: nchar(string)"
},
{
"code": null,
"e": 25827,
"s": 25809,
"text": "Parameter: string"
},
{
"code": null,
"e": 25866,
"s": 25827,
"text": "Return: Returns the length of a string"
},
{
"code": null,
"e": 25872,
"s": 25866,
"text": "Code:"
},
{
"code": null,
"e": 25874,
"s": 25872,
"text": "R"
},
{
"code": "# R program to calculate length # of string # Given Stringgfg <- \"Geeks For Geeks\" # Using nchar() methodanswer <- nchar(gfg) print(answer)",
"e": 26017,
"s": 25874,
"text": null
},
{
"code": null,
"e": 26025,
"s": 26017,
"text": "Output:"
},
{
"code": null,
"e": 26032,
"s": 26025,
"text": "[1] 15"
},
{
"code": null,
"e": 26120,
"s": 26032,
"text": "This method can be used to return the length of multiple strings passed as a parameter."
},
{
"code": null,
"e": 26126,
"s": 26120,
"text": "Code:"
},
{
"code": null,
"e": 26128,
"s": 26126,
"text": "R"
},
{
"code": "nchar(c(\"Hello World!\",\"Akshit\"));",
"e": 26163,
"s": 26128,
"text": null
},
{
"code": null,
"e": 26171,
"s": 26163,
"text": "Output:"
},
{
"code": null,
"e": 26181,
"s": 26171,
"text": "[1] 12 6"
},
{
"code": null,
"e": 26219,
"s": 26181,
"text": "Method 2. Using str_length () method."
},
{
"code": null,
"e": 26333,
"s": 26219,
"text": "The function str_length() belonging to the ‘stringr’ package can be used to determine the length of strings in R."
},
{
"code": null,
"e": 26358,
"s": 26333,
"text": "Syntax: str_length (str)"
},
{
"code": null,
"e": 26383,
"s": 26358,
"text": "Parameter: string as str"
},
{
"code": null,
"e": 26414,
"s": 26383,
"text": "Return value: Length of string"
},
{
"code": null,
"e": 26420,
"s": 26414,
"text": "Code:"
},
{
"code": null,
"e": 26422,
"s": 26420,
"text": "R"
},
{
"code": "# R program for finding length# of string # Importing packagelibrary(stringr) # Calculating length of string str_length(\"hello\")",
"e": 26556,
"s": 26422,
"text": null
},
{
"code": null,
"e": 26564,
"s": 26556,
"text": "Output:"
},
{
"code": null,
"e": 26570,
"s": 26564,
"text": "[1] 5"
},
{
"code": null,
"e": 26658,
"s": 26570,
"text": "This method can be used to return the length of multiple strings passed as a parameter."
},
{
"code": null,
"e": 26664,
"s": 26658,
"text": "Code:"
},
{
"code": null,
"e": 26666,
"s": 26664,
"text": "R"
},
{
"code": "# Codelibrary(stringr); str_length(c(\"Hello World!\",\"Akshit\"));",
"e": 26731,
"s": 26666,
"text": null
},
{
"code": null,
"e": 26739,
"s": 26731,
"text": "Output:"
},
{
"code": null,
"e": 26749,
"s": 26739,
"text": "[1] 12 6"
},
{
"code": null,
"e": 26787,
"s": 26749,
"text": "Method 3. Using stri_length() method."
},
{
"code": null,
"e": 26851,
"s": 26787,
"text": "This function returns the number of code points in each string."
},
{
"code": null,
"e": 26876,
"s": 26851,
"text": "Syntax: stri_length(str)"
},
{
"code": null,
"e": 26911,
"s": 26876,
"text": "Parameter: str as character vector"
},
{
"code": null,
"e": 26978,
"s": 26911,
"text": "Return Value: Returns an integer vector of the same length as str."
},
{
"code": null,
"e": 27088,
"s": 26978,
"text": "Note that the number of code points is not the same as the `width` of the string when printed on the console."
},
{
"code": null,
"e": 27094,
"s": 27088,
"text": "Code:"
},
{
"code": null,
"e": 27096,
"s": 27094,
"text": "R"
},
{
"code": "library(stringi); stri_length(c(\"Akshit\"));",
"e": 27141,
"s": 27096,
"text": null
},
{
"code": null,
"e": 27149,
"s": 27141,
"text": "Output:"
},
{
"code": null,
"e": 27155,
"s": 27149,
"text": "[1] 6"
},
{
"code": null,
"e": 27243,
"s": 27155,
"text": "This method can be used to return the length of multiple strings passed as a parameter."
},
{
"code": null,
"e": 27245,
"s": 27243,
"text": "R"
},
{
"code": "library(stringi); stri_length(c(\"Hello World\",\"Akshit\"));",
"e": 27304,
"s": 27245,
"text": null
},
{
"code": null,
"e": 27312,
"s": 27304,
"text": "Output:"
},
{
"code": null,
"e": 27322,
"s": 27312,
"text": "[1] 11 6"
},
{
"code": null,
"e": 27329,
"s": 27322,
"text": "Picked"
},
{
"code": null,
"e": 27347,
"s": 27329,
"text": "R String-Programs"
},
{
"code": null,
"e": 27357,
"s": 27347,
"text": "R-strings"
},
{
"code": null,
"e": 27368,
"s": 27357,
"text": "R Language"
},
{
"code": null,
"e": 27379,
"s": 27368,
"text": "R Programs"
},
{
"code": null,
"e": 27477,
"s": 27379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27486,
"s": 27477,
"text": "Comments"
},
{
"code": null,
"e": 27499,
"s": 27486,
"text": "Old Comments"
},
{
"code": null,
"e": 27551,
"s": 27499,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27589,
"s": 27551,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27624,
"s": 27589,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27682,
"s": 27624,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27731,
"s": 27682,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27789,
"s": 27731,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27838,
"s": 27789,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27888,
"s": 27838,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27931,
"s": 27888,
"text": "Replace Specific Characters in String in R"
}
] |
PHP 7 - Environment Setup
|
In order to develop and run PHP Web pages, three vital components need to be installed on your computer system.
Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi
Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi
Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/
Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/
PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer.
PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer.
Before you proceed, it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP. Store the following php file in Apache's htdocs folder.
<?php
phpinfo();
?>
Type the following address into your browser's address box.
http://127.0.0.1/phpinfo.php
If this displays a page showing your PHP installation related information, then it means you have PHP and Webserver installed properly. Otherwise, you have to follow the given procedure to install PHP on your computer.
This section will guide you to install and configure PHP over the following four platforms −
PHP Installation on Linux or Unix with Apache
PHP Installation on Linux or Unix with Apache
PHP Installation on Mac OS X with Apache
PHP Installation on Mac OS X with Apache
PHP Installation on Windows NT/2000/XP with IIS
PHP Installation on Windows NT/2000/XP with IIS
PHP Installation on Windows NT/2000/XP with Apache
PHP Installation on Windows NT/2000/XP with Apache
If you are using Apache as a Web Server, then this section will guide you to edit Apache Configuration Files.
Check here − PHP Configuration in Apache Server
The PHP configuration file, php.ini, is the final and immediate way to affect PHP's functionality.
Check here − PHP.INI File Configuration
To configure IIS on your Windows machine, you can refer your IIS Reference Manual shipped along with IIS.
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2189,
"s": 2077,
"text": "In order to develop and run PHP Web pages, three vital components need to be installed on your computer system."
},
{
"code": null,
"e": 2415,
"s": 2189,
"text": "Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi"
},
{
"code": null,
"e": 2641,
"s": 2415,
"text": "Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi"
},
{
"code": null,
"e": 2837,
"s": 2641,
"text": "Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/"
},
{
"code": null,
"e": 3033,
"s": 2837,
"text": "Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/"
},
{
"code": null,
"e": 3252,
"s": 3033,
"text": "PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer."
},
{
"code": null,
"e": 3471,
"s": 3252,
"text": "PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer."
},
{
"code": null,
"e": 3671,
"s": 3471,
"text": "Before you proceed, it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP. Store the following php file in Apache's htdocs folder."
},
{
"code": null,
"e": 3694,
"s": 3671,
"text": "<?php\n phpinfo();\n?>"
},
{
"code": null,
"e": 3754,
"s": 3694,
"text": "Type the following address into your browser's address box."
},
{
"code": null,
"e": 3784,
"s": 3754,
"text": "http://127.0.0.1/phpinfo.php\n"
},
{
"code": null,
"e": 4003,
"s": 3784,
"text": "If this displays a page showing your PHP installation related information, then it means you have PHP and Webserver installed properly. Otherwise, you have to follow the given procedure to install PHP on your computer."
},
{
"code": null,
"e": 4096,
"s": 4003,
"text": "This section will guide you to install and configure PHP over the following four platforms −"
},
{
"code": null,
"e": 4142,
"s": 4096,
"text": "PHP Installation on Linux or Unix with Apache"
},
{
"code": null,
"e": 4188,
"s": 4142,
"text": "PHP Installation on Linux or Unix with Apache"
},
{
"code": null,
"e": 4229,
"s": 4188,
"text": "PHP Installation on Mac OS X with Apache"
},
{
"code": null,
"e": 4270,
"s": 4229,
"text": "PHP Installation on Mac OS X with Apache"
},
{
"code": null,
"e": 4319,
"s": 4270,
"text": "PHP Installation on Windows NT/2000/XP with IIS"
},
{
"code": null,
"e": 4368,
"s": 4319,
"text": "PHP Installation on Windows NT/2000/XP with IIS"
},
{
"code": null,
"e": 4420,
"s": 4368,
"text": "PHP Installation on Windows NT/2000/XP with Apache"
},
{
"code": null,
"e": 4472,
"s": 4420,
"text": "PHP Installation on Windows NT/2000/XP with Apache"
},
{
"code": null,
"e": 4582,
"s": 4472,
"text": "If you are using Apache as a Web Server, then this section will guide you to edit Apache Configuration Files."
},
{
"code": null,
"e": 4631,
"s": 4582,
"text": "Check here − PHP Configuration in Apache Server"
},
{
"code": null,
"e": 4730,
"s": 4631,
"text": "The PHP configuration file, php.ini, is the final and immediate way to affect PHP's functionality."
},
{
"code": null,
"e": 4770,
"s": 4730,
"text": "Check here − PHP.INI File Configuration"
},
{
"code": null,
"e": 4876,
"s": 4770,
"text": "To configure IIS on your Windows machine, you can refer your IIS Reference Manual shipped along with IIS."
},
{
"code": null,
"e": 4909,
"s": 4876,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4925,
"s": 4909,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4958,
"s": 4925,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4969,
"s": 4958,
"text": " Syed Raza"
},
{
"code": null,
"e": 5004,
"s": 4969,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5021,
"s": 5004,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5054,
"s": 5021,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5069,
"s": 5054,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 5104,
"s": 5069,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 5116,
"s": 5104,
"text": " Azaz Patel"
},
{
"code": null,
"e": 5151,
"s": 5116,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5179,
"s": 5151,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5186,
"s": 5179,
"text": " Print"
},
{
"code": null,
"e": 5197,
"s": 5186,
"text": " Add Notes"
}
] |
AtomicInteger for Lock Free Algorithms in Java - GeeksforGeeks
|
18 Sep, 2020
Lock-Free Algorithms is one of the mechanisms in which thread-safe access to shared data is possible without the use of Synchronization primitives like mutexes. Multi-threaded applications have shared resources that may be passed among different threads used in the application.
This poses the threat of race conditions and data races among the threads. In order to handle this situation, various techniques are used. One of the most common ways is to use synchronization and locks(also called monitors) which ensures thread safety. However, If excessive synchronization is used, the application performance would be hugely impacted along with the application getting more and more complex.
We need to write applications that are thread-safe but at the same time, they should give us high performance and the benefit of concurrent execution. So, in order to minimize the usage of synchronization and reduce the complexity of locks, Java has a whole set of classes in the java.util.the concurrent package which provides many advanced operations that are lock-free and atomic.
A large set of operations, in an application, can be performed without the need to synchronize most of the code. We need to understand what applies best in a situation and use the right tool for the job.
We will see an example where first we display how synchronized locking is used in multi-threaded applications to achieve concurrency, and then we will see a solution providing a lock-free solution of the same problem.
The following example shows how synchronization and the locking mechanisms are used as a solution for concurrency.
Java
// Java Program to demonstrate the // Synchronization of threads// using Locks import java.io.*; class GFG { public static void main(String[] args) throws InterruptedException { // Creating Obj for CountTrees Class CountTrees countTrees = new CountTrees(); // Creating Obj for IncreaseTrees Class IncreaseTrees increaseTreesThread = new IncreaseTrees(countTrees); // Creating Obj for IncreaseConcrete Class IncreaseConcrete increaseConcreteThread = new IncreaseConcrete(countTrees); // Starting both Thread increaseTreesThread // And increaseConcreteThread by using start method. increaseTreesThread.start(); increaseConcreteThread.start(); // Join method Enable threads wait to complete increaseTreesThread.join(); increaseConcreteThread.join(); // To print the no. of trees by getting current // value by using countTrees Obj. System.out.println("Number of trees in your area ::" + countTrees.getNumOfTrees()); }} // Implementation of IncreaseTrees using Threadclass IncreaseTrees extends Thread { private CountTrees countTrees; IncreaseTrees(CountTrees countTrees) { this.countTrees = countTrees; } @Override public void run() { System.out.println("Planting trees in progress..."); countTrees.plantTrees(); }} // Implementation of IncreaseConcrete using Threadclass IncreaseConcrete extends Thread { private CountTrees countTrees; IncreaseConcrete(CountTrees countTrees) { this.countTrees = countTrees; } @Override public void run() { System.out.println("Concretization in progress..."); countTrees.concretizing(); }} // Synchronizing the shared resourcesclass CountTrees { private int trees = 10000; public synchronized void plantTrees() { for (int i = 0; i < 10000; i++) trees++; } public synchronized void concretizing() { for (int i = 0; i < 10000; i++) trees--; } public synchronized int getNumOfTrees() { return this.trees; }}
Output:
Planting trees in progress...
Concretization in progress...
Number of trees in your area:: 10000
Now to convert the above example into a simple lock-free sample, we use the AtomicInteger class of Java which is part of the Concurrent package java.util.concurrent.atomic.AtomicInteger. It is a very useful class which can be easily used in concurrent applications as below :
Java
// Java program to demonstrate to achieve concurrency// with the help of AtomicInteger class which is used// in application like atomically incremented the counter // Lock Free program for achieving concurrencyimport java.io.*; // Java provides wrapper class to achieve atomic // operations without the use of synchronization // like java.util.concurrent.atomic.AtomicIntegerimport java.util.concurrent.atomic.AtomicInteger; class GFG { public static void main(String[] args) throws InterruptedException { // Creating Obj for CountTrees Class CountTrees countTrees = new CountTrees(); // Creating Obj for IncreaseTrees Class IncreaseTrees increaseTreesThread = new IncreaseTrees(countTrees); // Creating Obj for IncreaseConcrete Class IncreaseConcrete increaseConcreteThread = new IncreaseConcrete(countTrees); // Starting both Thread increaseTreesThread // and increaseConcreteThread by using // start method. increaseTreesThread.start(); increaseConcreteThread.start(); // join method Enable threads wait to complete increaseTreesThread.join(); increaseConcreteThread.join(); // To print the no. of trees by getting current // value by using countTrees Obj. System.out.println("Number of trees in your area ::" + countTrees.getNumOfTrees()); }} // Implementation of IncreaseTrees classclass IncreaseTrees extends Thread { private CountTrees countTrees; IncreaseTrees(CountTrees countTrees) { this.countTrees = countTrees; } @Override public void run() { System.out.println("Planting trees in process..."); countTrees.plantTrees(); }} class IncreaseConcrete extends Thread { private CountTrees countTrees; IncreaseConcrete(CountTrees countTrees) { this.countTrees = countTrees; } @Override public void run() { System.out.println("Concretization in progress..."); countTrees.concretizing(); }} // Implementation of CountTrees Classclass CountTrees { // In java AtomicInteger Class provides operations on // underlying int value that can be read and // written atomically. private AtomicInteger trees = new AtomicInteger(10000); // Implementation of plantTrees method public void plantTrees() { // AtomicInteger class obj trees // atomically incremented the value. for (int i = 0; i < 10000; i++) trees.incrementAndGet(); } // Implementation of concretizing method public void concretizing() { // AtomicInteger class obj trees // decremented the value. for (int i = 0; i < 10000; i++) trees.decrementAndGet(); } public int getNumOfTrees() { // AtomicInteger class obj // trees Gets the current // value. return trees.get(); }}
Output:
Concretization in progress...
Planting trees in process...
Number of trees in your area::10000
Summary and Key Takeaways :
The AtomicInteger class is a great tool that can be used in simple applications like concurrent counting and building simple readable code without the complexity of using a lock.
AtomicInteger should be used only when atomic operations are needed. Also, the race condition can still exist between two separate atomic operations.
The AtomicInteger class is on par and can sometimes be more efficient than a regular integer with a lock as protection.
If an application is only using a single thread, the regular integer is preferred.
References: AtomicInteger class in Java
mathurritika
Java-AtomicInteger
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
LinkedList in Java
Collections in Java
Multithreading in Java
|
[
{
"code": null,
"e": 24266,
"s": 24238,
"text": "\n18 Sep, 2020"
},
{
"code": null,
"e": 24546,
"s": 24266,
"text": "Lock-Free Algorithms is one of the mechanisms in which thread-safe access to shared data is possible without the use of Synchronization primitives like mutexes. Multi-threaded applications have shared resources that may be passed among different threads used in the application. "
},
{
"code": null,
"e": 24959,
"s": 24546,
"text": "This poses the threat of race conditions and data races among the threads. In order to handle this situation, various techniques are used. One of the most common ways is to use synchronization and locks(also called monitors) which ensures thread safety. However, If excessive synchronization is used, the application performance would be hugely impacted along with the application getting more and more complex. "
},
{
"code": null,
"e": 25344,
"s": 24959,
"text": "We need to write applications that are thread-safe but at the same time, they should give us high performance and the benefit of concurrent execution. So, in order to minimize the usage of synchronization and reduce the complexity of locks, Java has a whole set of classes in the java.util.the concurrent package which provides many advanced operations that are lock-free and atomic. "
},
{
"code": null,
"e": 25549,
"s": 25344,
"text": "A large set of operations, in an application, can be performed without the need to synchronize most of the code. We need to understand what applies best in a situation and use the right tool for the job. "
},
{
"code": null,
"e": 25767,
"s": 25549,
"text": "We will see an example where first we display how synchronized locking is used in multi-threaded applications to achieve concurrency, and then we will see a solution providing a lock-free solution of the same problem."
},
{
"code": null,
"e": 25883,
"s": 25767,
"text": "The following example shows how synchronization and the locking mechanisms are used as a solution for concurrency. "
},
{
"code": null,
"e": 25888,
"s": 25883,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the // Synchronization of threads// using Locks import java.io.*; class GFG { public static void main(String[] args) throws InterruptedException { // Creating Obj for CountTrees Class CountTrees countTrees = new CountTrees(); // Creating Obj for IncreaseTrees Class IncreaseTrees increaseTreesThread = new IncreaseTrees(countTrees); // Creating Obj for IncreaseConcrete Class IncreaseConcrete increaseConcreteThread = new IncreaseConcrete(countTrees); // Starting both Thread increaseTreesThread // And increaseConcreteThread by using start method. increaseTreesThread.start(); increaseConcreteThread.start(); // Join method Enable threads wait to complete increaseTreesThread.join(); increaseConcreteThread.join(); // To print the no. of trees by getting current // value by using countTrees Obj. System.out.println(\"Number of trees in your area ::\" + countTrees.getNumOfTrees()); }} // Implementation of IncreaseTrees using Threadclass IncreaseTrees extends Thread { private CountTrees countTrees; IncreaseTrees(CountTrees countTrees) { this.countTrees = countTrees; } @Override public void run() { System.out.println(\"Planting trees in progress...\"); countTrees.plantTrees(); }} // Implementation of IncreaseConcrete using Threadclass IncreaseConcrete extends Thread { private CountTrees countTrees; IncreaseConcrete(CountTrees countTrees) { this.countTrees = countTrees; } @Override public void run() { System.out.println(\"Concretization in progress...\"); countTrees.concretizing(); }} // Synchronizing the shared resourcesclass CountTrees { private int trees = 10000; public synchronized void plantTrees() { for (int i = 0; i < 10000; i++) trees++; } public synchronized void concretizing() { for (int i = 0; i < 10000; i++) trees--; } public synchronized int getNumOfTrees() { return this.trees; }}",
"e": 28127,
"s": 25888,
"text": null
},
{
"code": null,
"e": 28135,
"s": 28127,
"text": "Output:"
},
{
"code": null,
"e": 28234,
"s": 28135,
"text": "Planting trees in progress...\nConcretization in progress...\nNumber of trees in your area:: 10000\n\n"
},
{
"code": null,
"e": 28511,
"s": 28234,
"text": "Now to convert the above example into a simple lock-free sample, we use the AtomicInteger class of Java which is part of the Concurrent package java.util.concurrent.atomic.AtomicInteger. It is a very useful class which can be easily used in concurrent applications as below : "
},
{
"code": null,
"e": 28516,
"s": 28511,
"text": "Java"
},
{
"code": "// Java program to demonstrate to achieve concurrency// with the help of AtomicInteger class which is used// in application like atomically incremented the counter // Lock Free program for achieving concurrencyimport java.io.*; // Java provides wrapper class to achieve atomic // operations without the use of synchronization // like java.util.concurrent.atomic.AtomicIntegerimport java.util.concurrent.atomic.AtomicInteger; class GFG { public static void main(String[] args) throws InterruptedException { // Creating Obj for CountTrees Class CountTrees countTrees = new CountTrees(); // Creating Obj for IncreaseTrees Class IncreaseTrees increaseTreesThread = new IncreaseTrees(countTrees); // Creating Obj for IncreaseConcrete Class IncreaseConcrete increaseConcreteThread = new IncreaseConcrete(countTrees); // Starting both Thread increaseTreesThread // and increaseConcreteThread by using // start method. increaseTreesThread.start(); increaseConcreteThread.start(); // join method Enable threads wait to complete increaseTreesThread.join(); increaseConcreteThread.join(); // To print the no. of trees by getting current // value by using countTrees Obj. System.out.println(\"Number of trees in your area ::\" + countTrees.getNumOfTrees()); }} // Implementation of IncreaseTrees classclass IncreaseTrees extends Thread { private CountTrees countTrees; IncreaseTrees(CountTrees countTrees) { this.countTrees = countTrees; } @Override public void run() { System.out.println(\"Planting trees in process...\"); countTrees.plantTrees(); }} class IncreaseConcrete extends Thread { private CountTrees countTrees; IncreaseConcrete(CountTrees countTrees) { this.countTrees = countTrees; } @Override public void run() { System.out.println(\"Concretization in progress...\"); countTrees.concretizing(); }} // Implementation of CountTrees Classclass CountTrees { // In java AtomicInteger Class provides operations on // underlying int value that can be read and // written atomically. private AtomicInteger trees = new AtomicInteger(10000); // Implementation of plantTrees method public void plantTrees() { // AtomicInteger class obj trees // atomically incremented the value. for (int i = 0; i < 10000; i++) trees.incrementAndGet(); } // Implementation of concretizing method public void concretizing() { // AtomicInteger class obj trees // decremented the value. for (int i = 0; i < 10000; i++) trees.decrementAndGet(); } public int getNumOfTrees() { // AtomicInteger class obj // trees Gets the current // value. return trees.get(); }}",
"e": 31484,
"s": 28516,
"text": null
},
{
"code": null,
"e": 31493,
"s": 31484,
"text": "Output: "
},
{
"code": null,
"e": 31590,
"s": 31493,
"text": "Concretization in progress...\nPlanting trees in process...\nNumber of trees in your area::10000\n\n"
},
{
"code": null,
"e": 31618,
"s": 31590,
"text": "Summary and Key Takeaways :"
},
{
"code": null,
"e": 31797,
"s": 31618,
"text": "The AtomicInteger class is a great tool that can be used in simple applications like concurrent counting and building simple readable code without the complexity of using a lock."
},
{
"code": null,
"e": 31947,
"s": 31797,
"text": "AtomicInteger should be used only when atomic operations are needed. Also, the race condition can still exist between two separate atomic operations."
},
{
"code": null,
"e": 32067,
"s": 31947,
"text": "The AtomicInteger class is on par and can sometimes be more efficient than a regular integer with a lock as protection."
},
{
"code": null,
"e": 32150,
"s": 32067,
"text": "If an application is only using a single thread, the regular integer is preferred."
},
{
"code": null,
"e": 32190,
"s": 32150,
"text": "References: AtomicInteger class in Java"
},
{
"code": null,
"e": 32203,
"s": 32190,
"text": "mathurritika"
},
{
"code": null,
"e": 32222,
"s": 32203,
"text": "Java-AtomicInteger"
},
{
"code": null,
"e": 32227,
"s": 32222,
"text": "Java"
},
{
"code": null,
"e": 32232,
"s": 32227,
"text": "Java"
},
{
"code": null,
"e": 32330,
"s": 32232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32362,
"s": 32330,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32381,
"s": 32362,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32399,
"s": 32381,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 32431,
"s": 32399,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32455,
"s": 32431,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 32475,
"s": 32455,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 32487,
"s": 32475,
"text": "Set in Java"
},
{
"code": null,
"e": 32506,
"s": 32487,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 32526,
"s": 32506,
"text": "Collections in Java"
}
] |
Loan Default Prediction with Berka Dataset | by Zhou (Joe) Xu | Towards Data Science
|
· Introduction· About the Dataset· Import Dataset into the Database· Connect Python to MySQL Database· Feature Extraction· Feature Transformation· Modeling· Conclusion and Future Directions· About Me
Note: If you are interested in the details beyond this post, the Berka Dataset, all the code, and notebooks can be found on my GitHub Page.
This post is just a hands-on practice building a loan default prediction model. If you are interested in this topic and want to see some more in-depth work that I accomplished for a client, using optimization to turn their loss into profit using such loan default prediction models, please see my other article here: Loan Default Prediction for Profit Maximization.
For banks, it is always an interesting and challenging problem to predict how likely a client is going to default the loan when they only have a handful of information. In the modern era, the data science teams in the banks build predictive models using machine learning. The datasets used by them are most likely to be proprietary and are usually collected internally through their daily businesses. In other words, there are not many real-world datasets that we can use if we want to work on such financial projects. Fortunately, there is an exception: the Berka Dataset.
The Berka Dataset, or the PKDD’99 Financial Dataset, is a collection of real anonymized financial information from a Czech bank, used for PKDD’99 Discovery Challenge. The dataset can be accessed from my GitHub page.
In the dataset, 8 raw files include 8 tables:
account (4500 objects in the file ACCOUNT.ASC) — each record describes static characteristics of an account.
client (5369 objects in the file CLIENT.ASC) — each record describes characteristics of a client.
disposition (5369 objects in the file DISP.ASC) — each record relates together a client with an account i.e. this relation describes the rights of clients to operate accounts.
permanent order (6471 objects in the file ORDER.ASC) — each record describes characteristics of a payment order.
transaction (1056320 objects in the file TRANS.ASC) — each record describes one transaction on an account.
loan (682 objects in the file LOAN.ASC) — each record describes a loan granted for a given account.
credit card (892 objects in the file CARD.ASC) — each record describes a credit card issued to an account.
demographic data (77 objects in the file DISTRICT.ASC) — each record describes demographic characteristics of a district.
Each account has both static characteristics (e.g. date of creation, address of the branch) given in relation “account” and dynamic characteristics (e.g. payments debited or credited, balances) given in the relations “permanent order” and “transaction”.
Relation “client” describes the characteristics of persons who can manipulate the accounts.
One client can have more accounts, more clients can manipulate with a single account; clients and accounts are related together in relation “disposition”.
Relations “loan” and “credit card” describe some services which the bank offers to its clients.
More than one credit card can be issued to an account.
At most one loan can be granted for an account.
Relation “demographic data” gives some publicly available information about the districts (e.g. the unemployment rate); additional information about the clients can be deduced from this.
This is an optional step since the raw files contain only delimiter-separated values, so it can be directly imported into data frames using pandas.
Here I wrote SQL queries to import the raw data files into MySQL database for simple and fast data manipulations (eg. select, join and aggregation functions) on the data.
Above is a code snippet showing how to create the bank database and import the Account table. It includes three steps:
Create and use database
Create a table
Load data into the table
There should not be any troubles in the first two steps if you are familiar with MySQL and the database systems. For the “Load data” step, you need to make sure that you have enabled the LOCAL_INFILE in MySQL. Detailed instruction can be found from this thread.
By repeating step 2 and step 3 on each table, all the data can be imported into the database.
Again, if you choose to import the data directly into Python using Pandas, this step is optional. But if you have created the database and become familiar with the dataset through some SQL data manipulations, the next step is to transfer the prepared tables into Python and perform data analysis there. One way is to use the MySQL Connector for Python to execute SQL queries in Python and make Pandas DataFrames using the results. Here is my approach:
After modifying the database info such as host, database, user, password, we can initiate a connection instance, execute the query and convert it into Pandas DataFrame:
Even though this is an optional step, it is advantageous in terms of speed, convenience, and good for experimentation purposes compared to directly import the files into Pandas DataFrames. Unlike other ML projects where we are only given with acsv file (1 table), this dataset is quite complicated and there is a lot of useful information hidden between the connections of tables, so this is another reason why I want to introduce the way of loading data into the database first.
Now the data is in MySQL server and we have connected it Python so that we can smoothly access the data in data frames. The next steps are to extract features from the table, transform the variables, load them into one array, and train a machine learning model.
Since predicting the loan default is a binary classification problem, we first need to know how many instances in each class. By looking at the status variable in the Loan table, there are 4 distinct values: A, B, C, and D.
A: Contract finished, no problems.
B: Contract finished, loan not paid.
C: Running contract, okay so far.
D: Running contract, client in debt.
According to the definitions from the dataset description, we can make them into binary classes: good (A or C) and bad (B or D). There are 606 loans that fall into the “good” class and 76 of them are in the “bad” class.
With the two distinct classes defined, we can look into the variables and plot the histograms to see if they correspond to different distributions.
The loan amount shown below is a good example to see the difference between the two classes. Even though both are right-skewed, it still shows an interesting pattern that loans with a higher amount tend to default.
When extracting features, they don’t have to be the existing variables provided in the tables. Instead, we can always be creative and come up with some out-of-the-box solutions on creating our own features. For example, when joining the Loan table and the Account table, we can get both the date of loan issuance and the date of account creation. We may wonder if the time gap between creating the account and applying for the loan plays a role, so a simple subtraction would give us a new variable consists of days between the two such activities on the same account. The histograms are shown below, where a clear trend can be seen that people who apply for the loan right after creating the bank account tend to default.
By repeating the process of experimenting with existing features and created features, I finally prepared a table that consists of 18 feature columns and 1 label column. The selected features are:
amount: Loan amount
duration: Loan duration
payments: Loan payments
days_between: Days between account creation and loan issuance
frequency: Frequency of issuance of statements
average_order_amount: Average amount of the permanent orders made by the account
average_trans_amount: Average amount of the transactions made by the account
average_trans_balance: Average balance amount after transactions made by the account
n_trans: Transaction number of account
card_type: Type of credit card associated with the account
n_inhabitants: Number of inhabitants in the district of account
average_salary: Average salary in the district of account
average_unemployment: Average unemployment rate in the district of account
entrepreneur_rate: Number of entrepreneurs per 1000 inhabitants in the district of account
average_crime_rate: Average crime rate in the district of account
owner_gender: Account owner’s gender
owner_age: Account owner’s age
same_district: A boolean that represents if the owner has the same district information as the account
After the features are extracted and put into a big table, it is necessary to transform the data so that they can be fed into the machine learning model in an organic way. In our case, we have two types of features. One is numerical, such as amount, duration, and n_trans. The other one is categorical, such as card_type and owners_gender.
Our dataset is pretty clean and there is any missing value, so we can skip the imputation and directly jumpy into scaling for the numerical values. The are several options of scalers from scikit-learn , such as StandardScaler , MinMaxScaler and RobustScaler . Here, I used MinMaxScaler to rescale the numerical values between 0 and 1. On the other hand, the typical strategy of dealing with categorical variables is to use OneHotEncoder to transform the features into binary 0 and 1 values.
The code below is a representation of the feature transformation steps:
The first thing in training a machine learning model is to split the train and test sets. It is tricky in our dataset because it is not balanced: there are almost 10 times more good loans than bad loans. A stratified split is a good option here because it preserves the ratio between classes in both train and test sets.
There are many good machine learning models for binary classification tasks. Here, the Random Forest model is used in this project for its decent performance and quick-prototyping capability. An initial RandomForrestClassifier model is fit and three distinct measures are used to represent the model performance: Accuracy, F1 Score, and ROC AUC.
It is noticeable that Accuracy is not sufficient for this unbalanced dataset. If we finetune the model purely by accuracy, then it would favor toward predicting the loan as “good loan”. F1 score is the harmonic mean between precision and recall, and ROC AUC is the area under the ROC curve. These two are better metrics for evaluating the model performance for unbalanced data.
The code below shows how to apply 5-fold stratified cross-validation on the training set, and calculate the average of each score:
Acc: 0.8973F1: 0.1620ROC AUC: 0.7253
It is clearly seen that the accuracy is high, almost 0.9, but the F1 score is very low because of low recall. There is room for the model to be finetuned and strive for better performance, and one of the methods is Grid Search. By assigning different values to the hyperparameters of theRandomForestClassifier such as n_estimators max_depth min_samples_split and min_samples_leaf , it will iterate through the combinations of hyperparameters and output the one with the best performance on the score that we are interested in. A code snippet is shown below:
Refitting the model with the best parameters, we can take a look at the model performance one the whole train set and the test set:
Performance on Train Set:Acc: 0.9706F1: 0.8478ROC AUC: 0.9952Performance on Test Set:Acc: 0.8927F1: 0.2667ROC AUC: 0.6957
The performance on the train set is great: more than 2/3 of the bad loans and all of the good loans are correctly classified, and all of the three performance measures are above 0.84. On the other hand, when the model is used on the test set, the result is not quite satisfying: most of the bad loans are labeled as “good” and the F1 score is only 0.267. There is evidence that overfitting is involved, so more effort should be put into such iterative processes in order to get better model performance.
With the model built, we can now rank the features based on their importance. The top 5 features that have the most prediction powers are:
Average Transaction Balance
Average Transaction Amount
Loan Amount
Average Salary
Days between account creation and loan application
There is not to much surprise here, since for many of these, we have already seen the unusual behaviors that could be related to the loan default, such as the loan amount and days between account creation and loan application.
In this post, I introduced the whole pipeline of an end-to-end machine learning model in a banking application, loan default prediction, with real-world banking dataset Berka. I described the Berka dataset and the relationships between each table. Steps and codes were demonstrated on how to import the dataset into MySQL database and then connect to Python and convert processed records into Pandas DataFrame. Features were extracted and transformed into an array, ready for feeding into machine learning models. As the last step, I fit a Random Forest model using the data, evaluated the model performance, and generated the list of top 5 features that play roles in predicting loan default.
This machine learning pipeline is just a gentle touch of the one application that could be used with the Berka dataset. It could go deeper since there is more useful information hidden in the intricate relationship among tables; it could also go wider since it can be extended to other applications such as credit card and client’s transaction behaviors. But if just focusing on this loan default prediction, there could be three directions to dive further in the future:
Extract more features: Due to the time limit, it is not possible to conduct a thorough study and have a deep understanding of the dataset. There are still many features in the dataset that are unused and a lot of the information has not been fully digested with knowledge in the banking industry.Try other models: Only the Random Forest model is used, but there are many good ones out there, such as Logistic Regression, XGBoost, SVM, or even neural networks. The models can also be improved further by finer tunings on hyperparameters or using ensemble methods such as bagging, boosting, and stacking.Deal with the unbalanced data: It is important to notice this fact that the default loans are only about 10% of the total loans, thus during the training process, the model will favor predicting more negatives than positive results. We have already used the F1 score and ROC AUC instead of just accuracy. However, the performance is still not as good as it could be. In order to solve this problem, other methods such as collecting or resampling more data can be used in the future.
Extract more features: Due to the time limit, it is not possible to conduct a thorough study and have a deep understanding of the dataset. There are still many features in the dataset that are unused and a lot of the information has not been fully digested with knowledge in the banking industry.
Try other models: Only the Random Forest model is used, but there are many good ones out there, such as Logistic Regression, XGBoost, SVM, or even neural networks. The models can also be improved further by finer tunings on hyperparameters or using ensemble methods such as bagging, boosting, and stacking.
Deal with the unbalanced data: It is important to notice this fact that the default loans are only about 10% of the total loans, thus during the training process, the model will favor predicting more negatives than positive results. We have already used the F1 score and ROC AUC instead of just accuracy. However, the performance is still not as good as it could be. In order to solve this problem, other methods such as collecting or resampling more data can be used in the future.
Again, This post is just a hands-on practice building a loan default prediction model from scratch. If you are interested in this topic and want to see some more in-depth work that I accomplished for a client, using optimization to turn their loss into profit using such loan default prediction models, please see my other article here: Loan Default Prediction for Profit Maximization.
Thank you for reading! If you like this article, please follow my channel (really appreciate it 🙏). I will keep writing to share my ideas and projects about data science. Feel free to contact me if you have any questions.
I am a data scientist at Sanofi. I embrace technology and learn new skills every day. You are welcome to reach me from Medium Blog, LinkedIn, or GitHub. My opinions are my own and not the views of my employer.
Please see my other articles:
Loan Default Prediction for Profit Maximization
Time Series Pattern Recognition with Air Quality Sensor Data
Build REST API for Machine Learning Models using Python and Flask-RESTful
Understanding Sigmoid, Logistic, Softmax Functions, and Cross-Entropy Loss (Log Loss) in Classification Problems
|
[
{
"code": null,
"e": 247,
"s": 47,
"text": "· Introduction· About the Dataset· Import Dataset into the Database· Connect Python to MySQL Database· Feature Extraction· Feature Transformation· Modeling· Conclusion and Future Directions· About Me"
},
{
"code": null,
"e": 387,
"s": 247,
"text": "Note: If you are interested in the details beyond this post, the Berka Dataset, all the code, and notebooks can be found on my GitHub Page."
},
{
"code": null,
"e": 753,
"s": 387,
"text": "This post is just a hands-on practice building a loan default prediction model. If you are interested in this topic and want to see some more in-depth work that I accomplished for a client, using optimization to turn their loss into profit using such loan default prediction models, please see my other article here: Loan Default Prediction for Profit Maximization."
},
{
"code": null,
"e": 1327,
"s": 753,
"text": "For banks, it is always an interesting and challenging problem to predict how likely a client is going to default the loan when they only have a handful of information. In the modern era, the data science teams in the banks build predictive models using machine learning. The datasets used by them are most likely to be proprietary and are usually collected internally through their daily businesses. In other words, there are not many real-world datasets that we can use if we want to work on such financial projects. Fortunately, there is an exception: the Berka Dataset."
},
{
"code": null,
"e": 1543,
"s": 1327,
"text": "The Berka Dataset, or the PKDD’99 Financial Dataset, is a collection of real anonymized financial information from a Czech bank, used for PKDD’99 Discovery Challenge. The dataset can be accessed from my GitHub page."
},
{
"code": null,
"e": 1589,
"s": 1543,
"text": "In the dataset, 8 raw files include 8 tables:"
},
{
"code": null,
"e": 1698,
"s": 1589,
"text": "account (4500 objects in the file ACCOUNT.ASC) — each record describes static characteristics of an account."
},
{
"code": null,
"e": 1796,
"s": 1698,
"text": "client (5369 objects in the file CLIENT.ASC) — each record describes characteristics of a client."
},
{
"code": null,
"e": 1972,
"s": 1796,
"text": "disposition (5369 objects in the file DISP.ASC) — each record relates together a client with an account i.e. this relation describes the rights of clients to operate accounts."
},
{
"code": null,
"e": 2085,
"s": 1972,
"text": "permanent order (6471 objects in the file ORDER.ASC) — each record describes characteristics of a payment order."
},
{
"code": null,
"e": 2192,
"s": 2085,
"text": "transaction (1056320 objects in the file TRANS.ASC) — each record describes one transaction on an account."
},
{
"code": null,
"e": 2292,
"s": 2192,
"text": "loan (682 objects in the file LOAN.ASC) — each record describes a loan granted for a given account."
},
{
"code": null,
"e": 2399,
"s": 2292,
"text": "credit card (892 objects in the file CARD.ASC) — each record describes a credit card issued to an account."
},
{
"code": null,
"e": 2521,
"s": 2399,
"text": "demographic data (77 objects in the file DISTRICT.ASC) — each record describes demographic characteristics of a district."
},
{
"code": null,
"e": 2775,
"s": 2521,
"text": "Each account has both static characteristics (e.g. date of creation, address of the branch) given in relation “account” and dynamic characteristics (e.g. payments debited or credited, balances) given in the relations “permanent order” and “transaction”."
},
{
"code": null,
"e": 2867,
"s": 2775,
"text": "Relation “client” describes the characteristics of persons who can manipulate the accounts."
},
{
"code": null,
"e": 3022,
"s": 2867,
"text": "One client can have more accounts, more clients can manipulate with a single account; clients and accounts are related together in relation “disposition”."
},
{
"code": null,
"e": 3118,
"s": 3022,
"text": "Relations “loan” and “credit card” describe some services which the bank offers to its clients."
},
{
"code": null,
"e": 3173,
"s": 3118,
"text": "More than one credit card can be issued to an account."
},
{
"code": null,
"e": 3221,
"s": 3173,
"text": "At most one loan can be granted for an account."
},
{
"code": null,
"e": 3408,
"s": 3221,
"text": "Relation “demographic data” gives some publicly available information about the districts (e.g. the unemployment rate); additional information about the clients can be deduced from this."
},
{
"code": null,
"e": 3556,
"s": 3408,
"text": "This is an optional step since the raw files contain only delimiter-separated values, so it can be directly imported into data frames using pandas."
},
{
"code": null,
"e": 3727,
"s": 3556,
"text": "Here I wrote SQL queries to import the raw data files into MySQL database for simple and fast data manipulations (eg. select, join and aggregation functions) on the data."
},
{
"code": null,
"e": 3846,
"s": 3727,
"text": "Above is a code snippet showing how to create the bank database and import the Account table. It includes three steps:"
},
{
"code": null,
"e": 3870,
"s": 3846,
"text": "Create and use database"
},
{
"code": null,
"e": 3885,
"s": 3870,
"text": "Create a table"
},
{
"code": null,
"e": 3910,
"s": 3885,
"text": "Load data into the table"
},
{
"code": null,
"e": 4172,
"s": 3910,
"text": "There should not be any troubles in the first two steps if you are familiar with MySQL and the database systems. For the “Load data” step, you need to make sure that you have enabled the LOCAL_INFILE in MySQL. Detailed instruction can be found from this thread."
},
{
"code": null,
"e": 4266,
"s": 4172,
"text": "By repeating step 2 and step 3 on each table, all the data can be imported into the database."
},
{
"code": null,
"e": 4718,
"s": 4266,
"text": "Again, if you choose to import the data directly into Python using Pandas, this step is optional. But if you have created the database and become familiar with the dataset through some SQL data manipulations, the next step is to transfer the prepared tables into Python and perform data analysis there. One way is to use the MySQL Connector for Python to execute SQL queries in Python and make Pandas DataFrames using the results. Here is my approach:"
},
{
"code": null,
"e": 4887,
"s": 4718,
"text": "After modifying the database info such as host, database, user, password, we can initiate a connection instance, execute the query and convert it into Pandas DataFrame:"
},
{
"code": null,
"e": 5367,
"s": 4887,
"text": "Even though this is an optional step, it is advantageous in terms of speed, convenience, and good for experimentation purposes compared to directly import the files into Pandas DataFrames. Unlike other ML projects where we are only given with acsv file (1 table), this dataset is quite complicated and there is a lot of useful information hidden between the connections of tables, so this is another reason why I want to introduce the way of loading data into the database first."
},
{
"code": null,
"e": 5629,
"s": 5367,
"text": "Now the data is in MySQL server and we have connected it Python so that we can smoothly access the data in data frames. The next steps are to extract features from the table, transform the variables, load them into one array, and train a machine learning model."
},
{
"code": null,
"e": 5853,
"s": 5629,
"text": "Since predicting the loan default is a binary classification problem, we first need to know how many instances in each class. By looking at the status variable in the Loan table, there are 4 distinct values: A, B, C, and D."
},
{
"code": null,
"e": 5888,
"s": 5853,
"text": "A: Contract finished, no problems."
},
{
"code": null,
"e": 5925,
"s": 5888,
"text": "B: Contract finished, loan not paid."
},
{
"code": null,
"e": 5959,
"s": 5925,
"text": "C: Running contract, okay so far."
},
{
"code": null,
"e": 5996,
"s": 5959,
"text": "D: Running contract, client in debt."
},
{
"code": null,
"e": 6216,
"s": 5996,
"text": "According to the definitions from the dataset description, we can make them into binary classes: good (A or C) and bad (B or D). There are 606 loans that fall into the “good” class and 76 of them are in the “bad” class."
},
{
"code": null,
"e": 6364,
"s": 6216,
"text": "With the two distinct classes defined, we can look into the variables and plot the histograms to see if they correspond to different distributions."
},
{
"code": null,
"e": 6579,
"s": 6364,
"text": "The loan amount shown below is a good example to see the difference between the two classes. Even though both are right-skewed, it still shows an interesting pattern that loans with a higher amount tend to default."
},
{
"code": null,
"e": 7302,
"s": 6579,
"text": "When extracting features, they don’t have to be the existing variables provided in the tables. Instead, we can always be creative and come up with some out-of-the-box solutions on creating our own features. For example, when joining the Loan table and the Account table, we can get both the date of loan issuance and the date of account creation. We may wonder if the time gap between creating the account and applying for the loan plays a role, so a simple subtraction would give us a new variable consists of days between the two such activities on the same account. The histograms are shown below, where a clear trend can be seen that people who apply for the loan right after creating the bank account tend to default."
},
{
"code": null,
"e": 7499,
"s": 7302,
"text": "By repeating the process of experimenting with existing features and created features, I finally prepared a table that consists of 18 feature columns and 1 label column. The selected features are:"
},
{
"code": null,
"e": 7519,
"s": 7499,
"text": "amount: Loan amount"
},
{
"code": null,
"e": 7543,
"s": 7519,
"text": "duration: Loan duration"
},
{
"code": null,
"e": 7567,
"s": 7543,
"text": "payments: Loan payments"
},
{
"code": null,
"e": 7629,
"s": 7567,
"text": "days_between: Days between account creation and loan issuance"
},
{
"code": null,
"e": 7676,
"s": 7629,
"text": "frequency: Frequency of issuance of statements"
},
{
"code": null,
"e": 7757,
"s": 7676,
"text": "average_order_amount: Average amount of the permanent orders made by the account"
},
{
"code": null,
"e": 7834,
"s": 7757,
"text": "average_trans_amount: Average amount of the transactions made by the account"
},
{
"code": null,
"e": 7919,
"s": 7834,
"text": "average_trans_balance: Average balance amount after transactions made by the account"
},
{
"code": null,
"e": 7958,
"s": 7919,
"text": "n_trans: Transaction number of account"
},
{
"code": null,
"e": 8017,
"s": 7958,
"text": "card_type: Type of credit card associated with the account"
},
{
"code": null,
"e": 8081,
"s": 8017,
"text": "n_inhabitants: Number of inhabitants in the district of account"
},
{
"code": null,
"e": 8139,
"s": 8081,
"text": "average_salary: Average salary in the district of account"
},
{
"code": null,
"e": 8214,
"s": 8139,
"text": "average_unemployment: Average unemployment rate in the district of account"
},
{
"code": null,
"e": 8305,
"s": 8214,
"text": "entrepreneur_rate: Number of entrepreneurs per 1000 inhabitants in the district of account"
},
{
"code": null,
"e": 8371,
"s": 8305,
"text": "average_crime_rate: Average crime rate in the district of account"
},
{
"code": null,
"e": 8408,
"s": 8371,
"text": "owner_gender: Account owner’s gender"
},
{
"code": null,
"e": 8439,
"s": 8408,
"text": "owner_age: Account owner’s age"
},
{
"code": null,
"e": 8542,
"s": 8439,
"text": "same_district: A boolean that represents if the owner has the same district information as the account"
},
{
"code": null,
"e": 8882,
"s": 8542,
"text": "After the features are extracted and put into a big table, it is necessary to transform the data so that they can be fed into the machine learning model in an organic way. In our case, we have two types of features. One is numerical, such as amount, duration, and n_trans. The other one is categorical, such as card_type and owners_gender."
},
{
"code": null,
"e": 9373,
"s": 8882,
"text": "Our dataset is pretty clean and there is any missing value, so we can skip the imputation and directly jumpy into scaling for the numerical values. The are several options of scalers from scikit-learn , such as StandardScaler , MinMaxScaler and RobustScaler . Here, I used MinMaxScaler to rescale the numerical values between 0 and 1. On the other hand, the typical strategy of dealing with categorical variables is to use OneHotEncoder to transform the features into binary 0 and 1 values."
},
{
"code": null,
"e": 9445,
"s": 9373,
"text": "The code below is a representation of the feature transformation steps:"
},
{
"code": null,
"e": 9766,
"s": 9445,
"text": "The first thing in training a machine learning model is to split the train and test sets. It is tricky in our dataset because it is not balanced: there are almost 10 times more good loans than bad loans. A stratified split is a good option here because it preserves the ratio between classes in both train and test sets."
},
{
"code": null,
"e": 10112,
"s": 9766,
"text": "There are many good machine learning models for binary classification tasks. Here, the Random Forest model is used in this project for its decent performance and quick-prototyping capability. An initial RandomForrestClassifier model is fit and three distinct measures are used to represent the model performance: Accuracy, F1 Score, and ROC AUC."
},
{
"code": null,
"e": 10490,
"s": 10112,
"text": "It is noticeable that Accuracy is not sufficient for this unbalanced dataset. If we finetune the model purely by accuracy, then it would favor toward predicting the loan as “good loan”. F1 score is the harmonic mean between precision and recall, and ROC AUC is the area under the ROC curve. These two are better metrics for evaluating the model performance for unbalanced data."
},
{
"code": null,
"e": 10621,
"s": 10490,
"text": "The code below shows how to apply 5-fold stratified cross-validation on the training set, and calculate the average of each score:"
},
{
"code": null,
"e": 10658,
"s": 10621,
"text": "Acc: 0.8973F1: 0.1620ROC AUC: 0.7253"
},
{
"code": null,
"e": 11216,
"s": 10658,
"text": "It is clearly seen that the accuracy is high, almost 0.9, but the F1 score is very low because of low recall. There is room for the model to be finetuned and strive for better performance, and one of the methods is Grid Search. By assigning different values to the hyperparameters of theRandomForestClassifier such as n_estimators max_depth min_samples_split and min_samples_leaf , it will iterate through the combinations of hyperparameters and output the one with the best performance on the score that we are interested in. A code snippet is shown below:"
},
{
"code": null,
"e": 11348,
"s": 11216,
"text": "Refitting the model with the best parameters, we can take a look at the model performance one the whole train set and the test set:"
},
{
"code": null,
"e": 11470,
"s": 11348,
"text": "Performance on Train Set:Acc: 0.9706F1: 0.8478ROC AUC: 0.9952Performance on Test Set:Acc: 0.8927F1: 0.2667ROC AUC: 0.6957"
},
{
"code": null,
"e": 11974,
"s": 11470,
"text": "The performance on the train set is great: more than 2/3 of the bad loans and all of the good loans are correctly classified, and all of the three performance measures are above 0.84. On the other hand, when the model is used on the test set, the result is not quite satisfying: most of the bad loans are labeled as “good” and the F1 score is only 0.267. There is evidence that overfitting is involved, so more effort should be put into such iterative processes in order to get better model performance."
},
{
"code": null,
"e": 12113,
"s": 11974,
"text": "With the model built, we can now rank the features based on their importance. The top 5 features that have the most prediction powers are:"
},
{
"code": null,
"e": 12141,
"s": 12113,
"text": "Average Transaction Balance"
},
{
"code": null,
"e": 12168,
"s": 12141,
"text": "Average Transaction Amount"
},
{
"code": null,
"e": 12180,
"s": 12168,
"text": "Loan Amount"
},
{
"code": null,
"e": 12195,
"s": 12180,
"text": "Average Salary"
},
{
"code": null,
"e": 12246,
"s": 12195,
"text": "Days between account creation and loan application"
},
{
"code": null,
"e": 12473,
"s": 12246,
"text": "There is not to much surprise here, since for many of these, we have already seen the unusual behaviors that could be related to the loan default, such as the loan amount and days between account creation and loan application."
},
{
"code": null,
"e": 13167,
"s": 12473,
"text": "In this post, I introduced the whole pipeline of an end-to-end machine learning model in a banking application, loan default prediction, with real-world banking dataset Berka. I described the Berka dataset and the relationships between each table. Steps and codes were demonstrated on how to import the dataset into MySQL database and then connect to Python and convert processed records into Pandas DataFrame. Features were extracted and transformed into an array, ready for feeding into machine learning models. As the last step, I fit a Random Forest model using the data, evaluated the model performance, and generated the list of top 5 features that play roles in predicting loan default."
},
{
"code": null,
"e": 13639,
"s": 13167,
"text": "This machine learning pipeline is just a gentle touch of the one application that could be used with the Berka dataset. It could go deeper since there is more useful information hidden in the intricate relationship among tables; it could also go wider since it can be extended to other applications such as credit card and client’s transaction behaviors. But if just focusing on this loan default prediction, there could be three directions to dive further in the future:"
},
{
"code": null,
"e": 14724,
"s": 13639,
"text": "Extract more features: Due to the time limit, it is not possible to conduct a thorough study and have a deep understanding of the dataset. There are still many features in the dataset that are unused and a lot of the information has not been fully digested with knowledge in the banking industry.Try other models: Only the Random Forest model is used, but there are many good ones out there, such as Logistic Regression, XGBoost, SVM, or even neural networks. The models can also be improved further by finer tunings on hyperparameters or using ensemble methods such as bagging, boosting, and stacking.Deal with the unbalanced data: It is important to notice this fact that the default loans are only about 10% of the total loans, thus during the training process, the model will favor predicting more negatives than positive results. We have already used the F1 score and ROC AUC instead of just accuracy. However, the performance is still not as good as it could be. In order to solve this problem, other methods such as collecting or resampling more data can be used in the future."
},
{
"code": null,
"e": 15021,
"s": 14724,
"text": "Extract more features: Due to the time limit, it is not possible to conduct a thorough study and have a deep understanding of the dataset. There are still many features in the dataset that are unused and a lot of the information has not been fully digested with knowledge in the banking industry."
},
{
"code": null,
"e": 15328,
"s": 15021,
"text": "Try other models: Only the Random Forest model is used, but there are many good ones out there, such as Logistic Regression, XGBoost, SVM, or even neural networks. The models can also be improved further by finer tunings on hyperparameters or using ensemble methods such as bagging, boosting, and stacking."
},
{
"code": null,
"e": 15811,
"s": 15328,
"text": "Deal with the unbalanced data: It is important to notice this fact that the default loans are only about 10% of the total loans, thus during the training process, the model will favor predicting more negatives than positive results. We have already used the F1 score and ROC AUC instead of just accuracy. However, the performance is still not as good as it could be. In order to solve this problem, other methods such as collecting or resampling more data can be used in the future."
},
{
"code": null,
"e": 16197,
"s": 15811,
"text": "Again, This post is just a hands-on practice building a loan default prediction model from scratch. If you are interested in this topic and want to see some more in-depth work that I accomplished for a client, using optimization to turn their loss into profit using such loan default prediction models, please see my other article here: Loan Default Prediction for Profit Maximization."
},
{
"code": null,
"e": 16419,
"s": 16197,
"text": "Thank you for reading! If you like this article, please follow my channel (really appreciate it 🙏). I will keep writing to share my ideas and projects about data science. Feel free to contact me if you have any questions."
},
{
"code": null,
"e": 16629,
"s": 16419,
"text": "I am a data scientist at Sanofi. I embrace technology and learn new skills every day. You are welcome to reach me from Medium Blog, LinkedIn, or GitHub. My opinions are my own and not the views of my employer."
},
{
"code": null,
"e": 16659,
"s": 16629,
"text": "Please see my other articles:"
},
{
"code": null,
"e": 16707,
"s": 16659,
"text": "Loan Default Prediction for Profit Maximization"
},
{
"code": null,
"e": 16768,
"s": 16707,
"text": "Time Series Pattern Recognition with Air Quality Sensor Data"
},
{
"code": null,
"e": 16842,
"s": 16768,
"text": "Build REST API for Machine Learning Models using Python and Flask-RESTful"
}
] |
How to convert a 2D array into 1D array in C#?
|
Set a two-dimensional array and a one-dimensional array −
int[,] a = new int[2, 2] {{1,2}, {3,4} };
int[] b = new int[4];
To convert 2D to 1D array, set the two dimensional into one-dimensional we declared before −
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
b[k++] = a[i, j];
}
}
The following is the complete code to convert a two-dimensional array to one-dimensional array in C# −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program {
class twodmatrix {
static void Main(string[] args) {
int[, ] a = new int[2, 2] {
{
1,
2
},{
3,
4
}
};
int i, j;
int[] b = new int[4];
int k = 0;
Console.WriteLine("Two-Dimensional Array...");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i, j]);
}
}
Console.WriteLine("One-Dimensional Array...");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
b[k++] = a[i, j];
}
}
for (i = 0; i < 2 * 2; i++) {
Console.WriteLine("{0}\t", b[i]);
}
Console.ReadKey();
}
}
}
|
[
{
"code": null,
"e": 1120,
"s": 1062,
"text": "Set a two-dimensional array and a one-dimensional array −"
},
{
"code": null,
"e": 1184,
"s": 1120,
"text": "int[,] a = new int[2, 2] {{1,2}, {3,4} };\nint[] b = new int[4];"
},
{
"code": null,
"e": 1277,
"s": 1184,
"text": "To convert 2D to 1D array, set the two dimensional into one-dimensional we declared before −"
},
{
"code": null,
"e": 1363,
"s": 1277,
"text": "for (i = 0; i < 2; i++) {\n for (j = 0; j < 2; j++) {\n b[k++] = a[i, j];\n }\n}"
},
{
"code": null,
"e": 1466,
"s": 1363,
"text": "The following is the complete code to convert a two-dimensional array to one-dimensional array in C# −"
},
{
"code": null,
"e": 2404,
"s": 1466,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Program {\n class twodmatrix {\n\n static void Main(string[] args) {\n int[, ] a = new int[2, 2] {\n {\n 1,\n 2\n },{\n 3,\n 4\n }\n };\n\n int i, j;\n int[] b = new int[4];\n int k = 0;\n\n Console.WriteLine(\"Two-Dimensional Array...\");\n for (i = 0; i < 2; i++) {\n\n for (j = 0; j < 2; j++) {\n Console.WriteLine(\"a[{0},{1}] = {2}\", i, j, a[i, j]);\n }\n }\n\n Console.WriteLine(\"One-Dimensional Array...\");\n for (i = 0; i < 2; i++) {\n for (j = 0; j < 2; j++) {\n b[k++] = a[i, j];\n }\n } \n\n for (i = 0; i < 2 * 2; i++) {\n Console.WriteLine(\"{0}\\t\", b[i]);\n }\n Console.ReadKey();\n }\n }\n}"
}
] |
Pandas GroupBy - Count the occurrences of each combination - GeeksforGeeks
|
16 Jun, 2021
In this article, we will GroupBy two columns and count the occurrences of each combination in Pandas.
DataFrame.groupby() method is used to separate the DataFrame into groups. It will generate the number of similar data counts present in a particular column of the data frame.
Syntax: DataFrame.groupby(by=None, axis=0, level=None )
Parameters:
by: mapping, function, string, label, or iterable to group elements.
axis : group by along with the row (axis=0) or column (axis=1).
level: Integer. value to the group by a particular level or levels.
For understanding the concept, we will use a simple dataset given below:
Python3
# Import libraryimport pandas as pdimport numpy as np # initialise data of lists.Data = {'Products':['Box','Color','Pencil','Eraser','Color', 'Pencil','Eraser','Color','Color','Eraser','Eraser','Pencil'], 'States':['Jammu','Kolkata','Bihar','Gujrat','Kolkata', 'Bihar','Jammu','Bihar','Gujrat','Jammu','Kolkata','Bihar'], 'Sale':[14,24,31,12,13,7,9,31,18,16,18,14]} # Create DataFramedf = pd.DataFrame(Data, columns=['Products','States','Sale']) # Display the Outputdisplay(df)
Output:
Method 1: Using Pandas dataframe.size()
It returns a total number of elements, it is compared by multiplying rows and columns returned by the shape method.
Syntax: dataframe.size
Python3
new = df.groupby(['States','Products']).size()display(new)
Output:
Method 2: Using Pandas dataframe.count()
It is used to count the no. of non-NA/null observations across the given axis. It works with non-floating type data as well.
Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)
Parameters:
axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise
level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a DataFrame
numeric_only : Include only float, int, boolean data
Returns: count : Series (or DataFrame if level specified)
Python3
new = df.groupby(['States','Products'])['Sale'].count()display(new)
Output:
Method 3: Using Pandas reset_index()
It is a method to reset the index of a Data Frame.reset_index() method sets a list of integers ranging from 0 to length of data as an index.
Syntax: DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=”)
Parameters:
level: int, string or a list to select and remove passed column from index.
drop: Boolean value, Adds the replaced index column to the data if False.
inplace: Boolean value, make changes in the original data frame itself if True.
col_level: Select in which column level to insert the labels.
col_fill: Object, to determine how the other levels are named.
Return type: DataFrame
Python3
new = df.groupby(['States','Products'])['Sale'].agg('count').reset_index()display(new)
Output:
Method 4: Using pandas.pivot() function
It produces a pivot table based on 3 columns of the DataFrame. Uses unique values from index/columns and fills with values.
Syntax: pandas.pivot(index, columns, values)
Parameters:
index[ndarray] : Labels to use to make new frame’s index
columns[ndarray] : Labels to use to make new frame’s columns
values[ndarray] : Values to use for populating new frame’s values
Returns: Reshaped DataFrameException: ValueError raised if there are any duplicates.
Python3
new = df.groupby(['States','Products'],as_index = False ).count().pivot('States','Products').fillna(0)display(new)
Output:
akshaysingh98088
Picked
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n16 Jun, 2021"
},
{
"code": null,
"e": 24395,
"s": 24292,
"text": "In this article, we will GroupBy two columns and count the occurrences of each combination in Pandas. "
},
{
"code": null,
"e": 24570,
"s": 24395,
"text": "DataFrame.groupby() method is used to separate the DataFrame into groups. It will generate the number of similar data counts present in a particular column of the data frame."
},
{
"code": null,
"e": 24626,
"s": 24570,
"text": "Syntax: DataFrame.groupby(by=None, axis=0, level=None )"
},
{
"code": null,
"e": 24638,
"s": 24626,
"text": "Parameters:"
},
{
"code": null,
"e": 24707,
"s": 24638,
"text": "by: mapping, function, string, label, or iterable to group elements."
},
{
"code": null,
"e": 24771,
"s": 24707,
"text": "axis : group by along with the row (axis=0) or column (axis=1)."
},
{
"code": null,
"e": 24839,
"s": 24771,
"text": "level: Integer. value to the group by a particular level or levels."
},
{
"code": null,
"e": 24912,
"s": 24839,
"text": "For understanding the concept, we will use a simple dataset given below:"
},
{
"code": null,
"e": 24920,
"s": 24912,
"text": "Python3"
},
{
"code": "# Import libraryimport pandas as pdimport numpy as np # initialise data of lists.Data = {'Products':['Box','Color','Pencil','Eraser','Color', 'Pencil','Eraser','Color','Color','Eraser','Eraser','Pencil'], 'States':['Jammu','Kolkata','Bihar','Gujrat','Kolkata', 'Bihar','Jammu','Bihar','Gujrat','Jammu','Kolkata','Bihar'], 'Sale':[14,24,31,12,13,7,9,31,18,16,18,14]} # Create DataFramedf = pd.DataFrame(Data, columns=['Products','States','Sale']) # Display the Outputdisplay(df)",
"e": 25447,
"s": 24920,
"text": null
},
{
"code": null,
"e": 25455,
"s": 25447,
"text": "Output:"
},
{
"code": null,
"e": 25495,
"s": 25455,
"text": "Method 1: Using Pandas dataframe.size()"
},
{
"code": null,
"e": 25612,
"s": 25495,
"text": "It returns a total number of elements, it is compared by multiplying rows and columns returned by the shape method. "
},
{
"code": null,
"e": 25635,
"s": 25612,
"text": "Syntax: dataframe.size"
},
{
"code": null,
"e": 25643,
"s": 25635,
"text": "Python3"
},
{
"code": "new = df.groupby(['States','Products']).size()display(new)",
"e": 25702,
"s": 25643,
"text": null
},
{
"code": null,
"e": 25712,
"s": 25702,
"text": " Output: "
},
{
"code": null,
"e": 25754,
"s": 25712,
"text": " Method 2: Using Pandas dataframe.count()"
},
{
"code": null,
"e": 25880,
"s": 25754,
"text": "It is used to count the no. of non-NA/null observations across the given axis. It works with non-floating type data as well. "
},
{
"code": null,
"e": 25944,
"s": 25880,
"text": "Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)"
},
{
"code": null,
"e": 25956,
"s": 25944,
"text": "Parameters:"
},
{
"code": null,
"e": 26021,
"s": 25956,
"text": "axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise"
},
{
"code": null,
"e": 26133,
"s": 26021,
"text": "level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a DataFrame"
},
{
"code": null,
"e": 26186,
"s": 26133,
"text": "numeric_only : Include only float, int, boolean data"
},
{
"code": null,
"e": 26244,
"s": 26186,
"text": "Returns: count : Series (or DataFrame if level specified)"
},
{
"code": null,
"e": 26252,
"s": 26244,
"text": "Python3"
},
{
"code": "new = df.groupby(['States','Products'])['Sale'].count()display(new)",
"e": 26320,
"s": 26252,
"text": null
},
{
"code": null,
"e": 26328,
"s": 26320,
"text": "Output:"
},
{
"code": null,
"e": 26366,
"s": 26328,
"text": "Method 3: Using Pandas reset_index() "
},
{
"code": null,
"e": 26509,
"s": 26366,
"text": "It is a method to reset the index of a Data Frame.reset_index() method sets a list of integers ranging from 0 to length of data as an index. "
},
{
"code": null,
"e": 26603,
"s": 26509,
"text": "Syntax: DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=”)"
},
{
"code": null,
"e": 26615,
"s": 26603,
"text": "Parameters:"
},
{
"code": null,
"e": 26691,
"s": 26615,
"text": "level: int, string or a list to select and remove passed column from index."
},
{
"code": null,
"e": 26765,
"s": 26691,
"text": "drop: Boolean value, Adds the replaced index column to the data if False."
},
{
"code": null,
"e": 26845,
"s": 26765,
"text": "inplace: Boolean value, make changes in the original data frame itself if True."
},
{
"code": null,
"e": 26907,
"s": 26845,
"text": "col_level: Select in which column level to insert the labels."
},
{
"code": null,
"e": 26970,
"s": 26907,
"text": "col_fill: Object, to determine how the other levels are named."
},
{
"code": null,
"e": 26993,
"s": 26970,
"text": "Return type: DataFrame"
},
{
"code": null,
"e": 27001,
"s": 26993,
"text": "Python3"
},
{
"code": "new = df.groupby(['States','Products'])['Sale'].agg('count').reset_index()display(new)",
"e": 27088,
"s": 27001,
"text": null
},
{
"code": null,
"e": 27096,
"s": 27088,
"text": "Output:"
},
{
"code": null,
"e": 27136,
"s": 27096,
"text": "Method 4: Using pandas.pivot() function"
},
{
"code": null,
"e": 27260,
"s": 27136,
"text": "It produces a pivot table based on 3 columns of the DataFrame. Uses unique values from index/columns and fills with values."
},
{
"code": null,
"e": 27305,
"s": 27260,
"text": "Syntax: pandas.pivot(index, columns, values)"
},
{
"code": null,
"e": 27317,
"s": 27305,
"text": "Parameters:"
},
{
"code": null,
"e": 27374,
"s": 27317,
"text": "index[ndarray] : Labels to use to make new frame’s index"
},
{
"code": null,
"e": 27435,
"s": 27374,
"text": "columns[ndarray] : Labels to use to make new frame’s columns"
},
{
"code": null,
"e": 27501,
"s": 27435,
"text": "values[ndarray] : Values to use for populating new frame’s values"
},
{
"code": null,
"e": 27586,
"s": 27501,
"text": "Returns: Reshaped DataFrameException: ValueError raised if there are any duplicates."
},
{
"code": null,
"e": 27594,
"s": 27586,
"text": "Python3"
},
{
"code": "new = df.groupby(['States','Products'],as_index = False ).count().pivot('States','Products').fillna(0)display(new)",
"e": 27724,
"s": 27594,
"text": null
},
{
"code": null,
"e": 27732,
"s": 27724,
"text": "Output:"
},
{
"code": null,
"e": 27749,
"s": 27732,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 27756,
"s": 27749,
"text": "Picked"
},
{
"code": null,
"e": 27778,
"s": 27756,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 27792,
"s": 27778,
"text": "Python-pandas"
},
{
"code": null,
"e": 27799,
"s": 27792,
"text": "Python"
},
{
"code": null,
"e": 27897,
"s": 27799,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27929,
"s": 27897,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27985,
"s": 27929,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28027,
"s": 27985,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28069,
"s": 28027,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28124,
"s": 28069,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28146,
"s": 28124,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28185,
"s": 28146,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28216,
"s": 28185,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28245,
"s": 28216,
"text": "Create a directory in Python"
}
] |
Gulp - Combining Tasks
|
Task enables a modular approach to configure Gulp. We need to create task for each dependency, which we would add up as we find and install other plugins. The Gulp task will have following structure −
gulp.task('task-name', function() {
//do stuff here
});
Where “task-name” is a string name and “function()” performs your task. The “gulp.task” registers the function as a task within the name and specifies the dependencies on other tasks.
Let's take one plugin called minify-css to merge and minify all CSS scripts. It can be installed by using npm as shown in the following command −
npm install gulp-minify-css --save-dev
To work with “gulp-minify-css plugin”, you need to install another plugin called “gulp-autoprefixer” as shown in the following command −
npm install gulp-autoprefixer --save-dev
To concatenate the CSS files, install the gulp-concat as shown in the following command −
npm install gulp-concat --save-dev
After installation of plugins, you need to write dependencies in your configuration file as follows −
var autoprefix = require('gulp-autoprefixer');
var minifyCSS = require('gulp-minify-css');
var concat = require('gulp-concat');
We need to create task for each dependency, which we would add up as we install the plugins. The Gulp task will have following structure −
gulp.task('styles', function() {
gulp.src(['src/styles/*.css'])
.pipe(concat('styles.css'))
.pipe(autoprefix('last 2 versions'))
.pipe(minifyCSS())
.pipe(gulp.dest('build/styles/'));
});
The ‘concat’ plugin concatenates the CSS files and ‘autoprefix’ plugin indicates the current and the previous versions of all browsers. It minifies all CSS scripts from src folder and copies to the build folder by calling ‘dest’ method with an argument, which represents the target directory.
To run the task, use the following command in your project directory −
gulp styles
Similarly, we will use another plugin called ‘gulp-imagemin’ to compress the image file, which can be installed using the following command −
npm install gulp-imagemin --save-dev
You can add dependencies to your configuration file using the following command −
var imagemin = require('gulp-imagemin');
You can create the task for above defined dependency as shown in the following code.
gulp.task('imagemin', function() {
var img_src = 'src/images/**/*', img_dest = 'build/images';
gulp.src(img_src)
.pipe(changed(img_dest))
.pipe(imagemin())
.pipe(gulp.dest(img_dest));
});
The images are located in “src/images/**/*” which are saved in the img_srcobject. It is piped to other functions created by the ‘imagemin’ constructor. It compresses the images from src folder and copies to the build folder by calling ‘dest’ method with an argument, which represents the target directory.
To run the task, use the following command in your project directory −
gulp imagemin
You can run multiple tasks at a time by creating default task in the configuration file as shown in the following code −
gulp.task('default', ['imagemin', 'styles'], function() {
});
Gulp file is set up and ready to execute. Run the following command in your project directory to run the above combined tasks −
gulp
On running the task using the above command, you will get the following result in the command prompt −
C:\work>gulp
[16:08:51] Using gulpfile C:\work\gulpfile.js
[16:08:51] Starting 'imagemin'...
[16:08:51] Finished 'imagemin' after 20 ms
[16:08:51] Starting 'styles'...
[16:08:51] Finished 'styles' after 13 ms
[16:08:51] Starting 'default'...
[16:08:51] Finished 'default' after 6.13 ms
[16:08:51] gulp-imagemin: Minified 0 images
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2017,
"s": 1816,
"text": "Task enables a modular approach to configure Gulp. We need to create task for each dependency, which we would add up as we find and install other plugins. The Gulp task will have following structure −"
},
{
"code": null,
"e": 2077,
"s": 2017,
"text": "gulp.task('task-name', function() {\n //do stuff here\n});\n"
},
{
"code": null,
"e": 2261,
"s": 2077,
"text": "Where “task-name” is a string name and “function()” performs your task. The “gulp.task” registers the function as a task within the name and specifies the dependencies on other tasks."
},
{
"code": null,
"e": 2407,
"s": 2261,
"text": "Let's take one plugin called minify-css to merge and minify all CSS scripts. It can be installed by using npm as shown in the following command −"
},
{
"code": null,
"e": 2446,
"s": 2407,
"text": "npm install gulp-minify-css --save-dev"
},
{
"code": null,
"e": 2583,
"s": 2446,
"text": "To work with “gulp-minify-css plugin”, you need to install another plugin called “gulp-autoprefixer” as shown in the following command −"
},
{
"code": null,
"e": 2624,
"s": 2583,
"text": "npm install gulp-autoprefixer --save-dev"
},
{
"code": null,
"e": 2714,
"s": 2624,
"text": "To concatenate the CSS files, install the gulp-concat as shown in the following command −"
},
{
"code": null,
"e": 2749,
"s": 2714,
"text": "npm install gulp-concat --save-dev"
},
{
"code": null,
"e": 2851,
"s": 2749,
"text": "After installation of plugins, you need to write dependencies in your configuration file as follows −"
},
{
"code": null,
"e": 2980,
"s": 2851,
"text": "var autoprefix = require('gulp-autoprefixer');\nvar minifyCSS = require('gulp-minify-css');\nvar concat = require('gulp-concat');\n"
},
{
"code": null,
"e": 3119,
"s": 2980,
"text": "We need to create task for each dependency, which we would add up as we install the plugins. The Gulp task will have following structure −"
},
{
"code": null,
"e": 3321,
"s": 3119,
"text": "gulp.task('styles', function() {\n gulp.src(['src/styles/*.css'])\n .pipe(concat('styles.css'))\n .pipe(autoprefix('last 2 versions'))\n .pipe(minifyCSS())\n .pipe(gulp.dest('build/styles/'));\n});"
},
{
"code": null,
"e": 3614,
"s": 3321,
"text": "The ‘concat’ plugin concatenates the CSS files and ‘autoprefix’ plugin indicates the current and the previous versions of all browsers. It minifies all CSS scripts from src folder and copies to the build folder by calling ‘dest’ method with an argument, which represents the target directory."
},
{
"code": null,
"e": 3685,
"s": 3614,
"text": "To run the task, use the following command in your project directory −"
},
{
"code": null,
"e": 3698,
"s": 3685,
"text": "gulp styles\n"
},
{
"code": null,
"e": 3840,
"s": 3698,
"text": "Similarly, we will use another plugin called ‘gulp-imagemin’ to compress the image file, which can be installed using the following command −"
},
{
"code": null,
"e": 3878,
"s": 3840,
"text": "npm install gulp-imagemin --save-dev\n"
},
{
"code": null,
"e": 3960,
"s": 3878,
"text": "You can add dependencies to your configuration file using the following command −"
},
{
"code": null,
"e": 4002,
"s": 3960,
"text": "var imagemin = require('gulp-imagemin');\n"
},
{
"code": null,
"e": 4087,
"s": 4002,
"text": "You can create the task for above defined dependency as shown in the following code."
},
{
"code": null,
"e": 4294,
"s": 4087,
"text": "gulp.task('imagemin', function() {\n var img_src = 'src/images/**/*', img_dest = 'build/images';\n \n gulp.src(img_src)\n .pipe(changed(img_dest))\n .pipe(imagemin())\n .pipe(gulp.dest(img_dest));\n});"
},
{
"code": null,
"e": 4600,
"s": 4294,
"text": "The images are located in “src/images/**/*” which are saved in the img_srcobject. It is piped to other functions created by the ‘imagemin’ constructor. It compresses the images from src folder and copies to the build folder by calling ‘dest’ method with an argument, which represents the target directory."
},
{
"code": null,
"e": 4671,
"s": 4600,
"text": "To run the task, use the following command in your project directory −"
},
{
"code": null,
"e": 4686,
"s": 4671,
"text": "gulp imagemin\n"
},
{
"code": null,
"e": 4807,
"s": 4686,
"text": "You can run multiple tasks at a time by creating default task in the configuration file as shown in the following code −"
},
{
"code": null,
"e": 4871,
"s": 4807,
"text": "gulp.task('default', ['imagemin', 'styles'], function() {\n\n});\n"
},
{
"code": null,
"e": 4999,
"s": 4871,
"text": "Gulp file is set up and ready to execute. Run the following command in your project directory to run the above combined tasks −"
},
{
"code": null,
"e": 5005,
"s": 4999,
"text": "gulp\n"
},
{
"code": null,
"e": 5108,
"s": 5005,
"text": "On running the task using the above command, you will get the following result in the command prompt −"
},
{
"code": null,
"e": 5438,
"s": 5108,
"text": "C:\\work>gulp\n[16:08:51] Using gulpfile C:\\work\\gulpfile.js\n[16:08:51] Starting 'imagemin'...\n[16:08:51] Finished 'imagemin' after 20 ms\n[16:08:51] Starting 'styles'...\n[16:08:51] Finished 'styles' after 13 ms\n[16:08:51] Starting 'default'...\n[16:08:51] Finished 'default' after 6.13 ms\n[16:08:51] gulp-imagemin: Minified 0 images"
},
{
"code": null,
"e": 5445,
"s": 5438,
"text": " Print"
},
{
"code": null,
"e": 5456,
"s": 5445,
"text": " Add Notes"
}
] |
Expression-Bodied Members in C# - GeeksforGeeks
|
24 Sep, 2021
Expression-bodied members provide a minimal and concise syntax to define properties and methods. It helps to eliminate boilerplate code and helps writing code that is more readable. The expression-bodied syntax can be used when a member’s body consists only of one expression. It uses the =>(fat arrow) operator to define the body of the method or property and allows getting rid of curly braces and the return keyword. The feature was first introduced in C# 6.
In C#, a method is a collection of statements that perform a given task and return the result to the caller. Often times, methods end up containing only a single statement. For example, consider the following code:
int GetRectangleArea(int length, int breadth)
{
return length * breadth;
}
The above method only consists of a single return statement. Using expression-bodied syntax, the above method can be rewritten as follows:
int GetRectangleArea(int length, int breadth) => length * breadth;
Notice, the absence of the curly braces and the return statement. Instead of curly braces, the => operator has been used. The expression that follows after the return statement is written right after the => operator.
Syntax
[access-modifier] [qualifiers] return-type MethodName([parameters]) => expression;
Example
The following example defines a Boolean method called IsEven() that returns true if the number passed to it is even, otherwise, the method returns false. The IsEven() method uses expression-bodied syntax.
C#
// C# program to illustrate expression bodied methodusing System; class GFG{ // Returns true if number is even// else returns falsepublic static bool IsEven(int number) => number % 2 == 0; // Driver codepublic static void Main(){ int n = 10; if (IsEven(n)) { Console.WriteLine("{0} is even", n); } else { Console.WriteLine("{0} is odd", n); }}}
10 is even
Void methods are those methods that do not contain a return statement and consist only of a single statement can also use expression-bodied syntax. For instance, the following method:
void PrintName(string name)
{
Console.WriteLine($"The name is {name}");
}
can be written with expression-bodied syntax as follows:
void PrintName(string name) => Console.WriteLine($"The name is {name}");
Property accessors also can have only one statement. With expression-bodied properties, such property definitions can be simplified.
1. Read-only Properties
Read-only properties are properties that only have a get accessor, like the following:
public int Name
{
get
{
return "Geeks For Geeks";
}
}
Using expression-bodied syntax, the property can be defined as follows:
public int Name => "Geeks For Geeks";
Syntax
[access-modifier] [qualifier] type PropertyName => expression;
Example
The following example defines a class called Square with a constructor that accepts the length of the side of the square. Once the side is set in the constructor, it cannot be modified because the public Side property is read-only. Also, the side field is private and cannot be accessed from outside the class.
C#
// C# program to illustrate expression bodied propertiesusing System; public class Square { private int side; public Square(int side) { this.side = side; } public int Side => side;} class GFG{ // Driver codepublic static void Main(){ var square = new Square(4); Console.WriteLine($"Side is {square.Side}");}}
Side is 4
2. Non-Read only Properties
Since C# 7, non-read-only properties can also have expression-bodied get and set accessors. In the following Person class, the Name property defines both get and set accessors each with only one statement:
public class Person
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
This can be simplified by using expression-bodied accessors:
public class Person
{
private string name;
public string Name
{
get => name;
set => name = value;
}
}
Syntax
[access-modifier] [qualifiers] [type] PropertyName
{
get => expression;
set => expression;
}
Example
The code below defines a Square class like the above example but here, the Side property also has a set accessor. Also, an object initializer has been used instead of a constructor to provide the initial value for the Side property:
C#
// C# program to illustrate expression bodied propertiesusing System; public class Square { private int side; public int Side { get => side; set => side = value; }} class GFG{ // Driver code public static void Main(){ var square = new Square{Side = 4}; Console.WriteLine($"Side is {square.Side}"); square.Side = 10; Console.WriteLine($"Side is now {square.Side}");}}
Side is 4
Side is now 10
The expression-bodied syntax has also been extended to be used with constructors and destructors / Finalizers. If either of these methods contains only a single statement, they can be defined as expression-bodied.
Syntax
Constructors
[access-modifier] ClassName([parameters]) => expression;
Destructors/Finalizers
~ClassName() => expression;
Example
In the example that follows, the Square class defines a constructor and destructor each of which contains an expression-bodied definition:
C#
// C# program to illustrate expression-bodied // constructors and destructorsusing System; public class Square { private int side; public Square(int side) => this.side = side; ~Square() => Console.WriteLine("Square's Destructor"); public int Side => side;} class GFG{ // Driver codepublic static void Main(){ var square = new Square(4); Console.WriteLine($"Side is {square.Side}");}}
Side is 4
Square's Destructor
Similar to properties, indexers accessors can also be expression-bodied. Indexer definitions follow the same conventions as properties which implies that read-only indexers can be defined without specifying the accessor and read and write accessors require the name of the accessor.
Syntax
Read-only indexers
[access-modifer] [qualifiers] return-type this[ [parameters] ] => expression;
Read and write indexers
[access-modifier] [qualifiers] return-type this [ [parameters] ]
{
get => expression;
set => expression;
}
Example
The following class ProgrammingLangs defines a string array language of programming languages and also defines an indexer that forwards the indexes to the languages array and returns the element(language) at that index. The indexer is read-only, therefore the languages in the array cannot be modified outside the class.
C#
// C# program to illustrate expression-bodied indexersusing System; public class ProgrammingLangs{ private string[] languages = { "C#", "C", "C++", "Python", "Java" }; public string this[int idx] => languages[idx];} class GFG{ // Driver codepublic static void Main(){ var langs = new ProgrammingLangs(); Console.WriteLine(langs[0]); Console.WriteLine(langs[2]); Console.WriteLine(langs[3]);}}
C#
C++
Python
Just like how ordinary methods with a single statement can be expression-bodied, operator method definitions can also be expression-bodied if their body consists of a single statement.
Syntax
[access-modifier] static operator [operator-symbol] ([parameters]) => expression;
Example
The following example implements a class Complex that represents the real and imaginary part of a complex number and also defines the binary + operator to allow the addition of two Complex objects. The operator+ function is expression-bodied.
C#
// C# program to illustrate expression-bodied operator functionsusing System; public struct Complex{ public int Real{get; set;} public int Imaginary{get; set;} public Complex(int real, int imaginary) { Real = real; Imaginary = imaginary; } // Expression-bodied operator method public static Complex operator + ( Complex c1, Complex c2) => new Complex(c1.Real + c1.Real, c1.Imaginary + c2.Imaginary); public override string ToString() => $"({Real}) + ({Imaginary}i)";} class GFG{ // Driver code public static void Main(){ var a = new Complex(3, 2); var b = new Complex(1, 2); var result = a + b; Console.WriteLine($"{a} + {b} = {result}");}}
Output:
(3) + (2i) + (1) + (2i) = (6) + (4i)
Blogathon-2021
Blogathon
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
How to Create a Table With Multiple Foreign Keys in SQL?
SQL Query to Convert Datetime to Date
How to pass data into table from a form using React Components
Difference between Abstract Class and Interface in C#
C# | IsNullOrEmpty() Method
C# | How to check whether a List contains a specified element
String.Split() Method in C# with Examples
C# | Arrays of Strings
|
[
{
"code": null,
"e": 24812,
"s": 24784,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 25274,
"s": 24812,
"text": "Expression-bodied members provide a minimal and concise syntax to define properties and methods. It helps to eliminate boilerplate code and helps writing code that is more readable. The expression-bodied syntax can be used when a member’s body consists only of one expression. It uses the =>(fat arrow) operator to define the body of the method or property and allows getting rid of curly braces and the return keyword. The feature was first introduced in C# 6."
},
{
"code": null,
"e": 25489,
"s": 25274,
"text": "In C#, a method is a collection of statements that perform a given task and return the result to the caller. Often times, methods end up containing only a single statement. For example, consider the following code:"
},
{
"code": null,
"e": 25570,
"s": 25489,
"text": "int GetRectangleArea(int length, int breadth) \n{\n return length * breadth;\n} "
},
{
"code": null,
"e": 25709,
"s": 25570,
"text": "The above method only consists of a single return statement. Using expression-bodied syntax, the above method can be rewritten as follows:"
},
{
"code": null,
"e": 25776,
"s": 25709,
"text": "int GetRectangleArea(int length, int breadth) => length * breadth;"
},
{
"code": null,
"e": 25993,
"s": 25776,
"text": "Notice, the absence of the curly braces and the return statement. Instead of curly braces, the => operator has been used. The expression that follows after the return statement is written right after the => operator."
},
{
"code": null,
"e": 26000,
"s": 25993,
"text": "Syntax"
},
{
"code": null,
"e": 26083,
"s": 26000,
"text": "[access-modifier] [qualifiers] return-type MethodName([parameters]) => expression;"
},
{
"code": null,
"e": 26091,
"s": 26083,
"text": "Example"
},
{
"code": null,
"e": 26296,
"s": 26091,
"text": "The following example defines a Boolean method called IsEven() that returns true if the number passed to it is even, otherwise, the method returns false. The IsEven() method uses expression-bodied syntax."
},
{
"code": null,
"e": 26299,
"s": 26296,
"text": "C#"
},
{
"code": "// C# program to illustrate expression bodied methodusing System; class GFG{ // Returns true if number is even// else returns falsepublic static bool IsEven(int number) => number % 2 == 0; // Driver codepublic static void Main(){ int n = 10; if (IsEven(n)) { Console.WriteLine(\"{0} is even\", n); } else { Console.WriteLine(\"{0} is odd\", n); }}}",
"e": 26695,
"s": 26299,
"text": null
},
{
"code": null,
"e": 26706,
"s": 26695,
"text": "10 is even"
},
{
"code": null,
"e": 26890,
"s": 26706,
"text": "Void methods are those methods that do not contain a return statement and consist only of a single statement can also use expression-bodied syntax. For instance, the following method:"
},
{
"code": null,
"e": 26968,
"s": 26890,
"text": "void PrintName(string name)\n{\n Console.WriteLine($\"The name is {name}\");\n}"
},
{
"code": null,
"e": 27025,
"s": 26968,
"text": "can be written with expression-bodied syntax as follows:"
},
{
"code": null,
"e": 27099,
"s": 27025,
"text": "void PrintName(string name) => Console.WriteLine($\"The name is {name}\"); "
},
{
"code": null,
"e": 27232,
"s": 27099,
"text": "Property accessors also can have only one statement. With expression-bodied properties, such property definitions can be simplified."
},
{
"code": null,
"e": 27256,
"s": 27232,
"text": "1. Read-only Properties"
},
{
"code": null,
"e": 27343,
"s": 27256,
"text": "Read-only properties are properties that only have a get accessor, like the following:"
},
{
"code": null,
"e": 27422,
"s": 27343,
"text": "public int Name \n{ \n get \n {\n return \"Geeks For Geeks\";\n }\n} "
},
{
"code": null,
"e": 27494,
"s": 27422,
"text": "Using expression-bodied syntax, the property can be defined as follows:"
},
{
"code": null,
"e": 27532,
"s": 27494,
"text": "public int Name => \"Geeks For Geeks\";"
},
{
"code": null,
"e": 27539,
"s": 27532,
"text": "Syntax"
},
{
"code": null,
"e": 27602,
"s": 27539,
"text": "[access-modifier] [qualifier] type PropertyName => expression;"
},
{
"code": null,
"e": 27610,
"s": 27602,
"text": "Example"
},
{
"code": null,
"e": 27921,
"s": 27610,
"text": "The following example defines a class called Square with a constructor that accepts the length of the side of the square. Once the side is set in the constructor, it cannot be modified because the public Side property is read-only. Also, the side field is private and cannot be accessed from outside the class."
},
{
"code": null,
"e": 27924,
"s": 27921,
"text": "C#"
},
{
"code": "// C# program to illustrate expression bodied propertiesusing System; public class Square { private int side; public Square(int side) { this.side = side; } public int Side => side;} class GFG{ // Driver codepublic static void Main(){ var square = new Square(4); Console.WriteLine($\"Side is {square.Side}\");}}",
"e": 28275,
"s": 27924,
"text": null
},
{
"code": null,
"e": 28285,
"s": 28275,
"text": "Side is 4"
},
{
"code": null,
"e": 28313,
"s": 28285,
"text": "2. Non-Read only Properties"
},
{
"code": null,
"e": 28519,
"s": 28313,
"text": "Since C# 7, non-read-only properties can also have expression-bodied get and set accessors. In the following Person class, the Name property defines both get and set accessors each with only one statement:"
},
{
"code": null,
"e": 28724,
"s": 28519,
"text": "public class Person\n{\n private string name;\n \n public string Name\n {\n get \n {\n return name;\n }\n set \n {\n name = value;\n }\n }\n}"
},
{
"code": null,
"e": 28785,
"s": 28724,
"text": "This can be simplified by using expression-bodied accessors:"
},
{
"code": null,
"e": 28924,
"s": 28785,
"text": "public class Person\n{\n private string name;\n \n public string Name\n {\n get => name;\n set => name = value;\n }\n}"
},
{
"code": null,
"e": 28931,
"s": 28924,
"text": "Syntax"
},
{
"code": null,
"e": 28982,
"s": 28931,
"text": "[access-modifier] [qualifiers] [type] PropertyName"
},
{
"code": null,
"e": 28984,
"s": 28982,
"text": "{"
},
{
"code": null,
"e": 29007,
"s": 28984,
"text": " get => expression;"
},
{
"code": null,
"e": 29030,
"s": 29007,
"text": " set => expression;"
},
{
"code": null,
"e": 29032,
"s": 29030,
"text": "}"
},
{
"code": null,
"e": 29040,
"s": 29032,
"text": "Example"
},
{
"code": null,
"e": 29273,
"s": 29040,
"text": "The code below defines a Square class like the above example but here, the Side property also has a set accessor. Also, an object initializer has been used instead of a constructor to provide the initial value for the Side property:"
},
{
"code": null,
"e": 29276,
"s": 29273,
"text": "C#"
},
{
"code": "// C# program to illustrate expression bodied propertiesusing System; public class Square { private int side; public int Side { get => side; set => side = value; }} class GFG{ // Driver code public static void Main(){ var square = new Square{Side = 4}; Console.WriteLine($\"Side is {square.Side}\"); square.Side = 10; Console.WriteLine($\"Side is now {square.Side}\");}}",
"e": 29694,
"s": 29276,
"text": null
},
{
"code": null,
"e": 29719,
"s": 29694,
"text": "Side is 4\nSide is now 10"
},
{
"code": null,
"e": 29934,
"s": 29719,
"text": "The expression-bodied syntax has also been extended to be used with constructors and destructors / Finalizers. If either of these methods contains only a single statement, they can be defined as expression-bodied. "
},
{
"code": null,
"e": 29941,
"s": 29934,
"text": "Syntax"
},
{
"code": null,
"e": 29954,
"s": 29941,
"text": "Constructors"
},
{
"code": null,
"e": 30011,
"s": 29954,
"text": "[access-modifier] ClassName([parameters]) => expression;"
},
{
"code": null,
"e": 30034,
"s": 30011,
"text": "Destructors/Finalizers"
},
{
"code": null,
"e": 30062,
"s": 30034,
"text": "~ClassName() => expression;"
},
{
"code": null,
"e": 30070,
"s": 30062,
"text": "Example"
},
{
"code": null,
"e": 30209,
"s": 30070,
"text": "In the example that follows, the Square class defines a constructor and destructor each of which contains an expression-bodied definition:"
},
{
"code": null,
"e": 30212,
"s": 30209,
"text": "C#"
},
{
"code": "// C# program to illustrate expression-bodied // constructors and destructorsusing System; public class Square { private int side; public Square(int side) => this.side = side; ~Square() => Console.WriteLine(\"Square's Destructor\"); public int Side => side;} class GFG{ // Driver codepublic static void Main(){ var square = new Square(4); Console.WriteLine($\"Side is {square.Side}\");}}",
"e": 30631,
"s": 30212,
"text": null
},
{
"code": null,
"e": 30661,
"s": 30631,
"text": "Side is 4\nSquare's Destructor"
},
{
"code": null,
"e": 30944,
"s": 30661,
"text": "Similar to properties, indexers accessors can also be expression-bodied. Indexer definitions follow the same conventions as properties which implies that read-only indexers can be defined without specifying the accessor and read and write accessors require the name of the accessor."
},
{
"code": null,
"e": 30951,
"s": 30944,
"text": "Syntax"
},
{
"code": null,
"e": 30970,
"s": 30951,
"text": "Read-only indexers"
},
{
"code": null,
"e": 31048,
"s": 30970,
"text": "[access-modifer] [qualifiers] return-type this[ [parameters] ] => expression;"
},
{
"code": null,
"e": 31072,
"s": 31048,
"text": "Read and write indexers"
},
{
"code": null,
"e": 31137,
"s": 31072,
"text": "[access-modifier] [qualifiers] return-type this [ [parameters] ]"
},
{
"code": null,
"e": 31139,
"s": 31137,
"text": "{"
},
{
"code": null,
"e": 31162,
"s": 31139,
"text": " get => expression;"
},
{
"code": null,
"e": 31185,
"s": 31162,
"text": " set => expression;"
},
{
"code": null,
"e": 31187,
"s": 31185,
"text": "}"
},
{
"code": null,
"e": 31195,
"s": 31187,
"text": "Example"
},
{
"code": null,
"e": 31516,
"s": 31195,
"text": "The following class ProgrammingLangs defines a string array language of programming languages and also defines an indexer that forwards the indexes to the languages array and returns the element(language) at that index. The indexer is read-only, therefore the languages in the array cannot be modified outside the class."
},
{
"code": null,
"e": 31519,
"s": 31516,
"text": "C#"
},
{
"code": "// C# program to illustrate expression-bodied indexersusing System; public class ProgrammingLangs{ private string[] languages = { \"C#\", \"C\", \"C++\", \"Python\", \"Java\" }; public string this[int idx] => languages[idx];} class GFG{ // Driver codepublic static void Main(){ var langs = new ProgrammingLangs(); Console.WriteLine(langs[0]); Console.WriteLine(langs[2]); Console.WriteLine(langs[3]);}}",
"e": 31983,
"s": 31519,
"text": null
},
{
"code": null,
"e": 31997,
"s": 31983,
"text": "C#\nC++\nPython"
},
{
"code": null,
"e": 32182,
"s": 31997,
"text": "Just like how ordinary methods with a single statement can be expression-bodied, operator method definitions can also be expression-bodied if their body consists of a single statement."
},
{
"code": null,
"e": 32189,
"s": 32182,
"text": "Syntax"
},
{
"code": null,
"e": 32271,
"s": 32189,
"text": "[access-modifier] static operator [operator-symbol] ([parameters]) => expression;"
},
{
"code": null,
"e": 32279,
"s": 32271,
"text": "Example"
},
{
"code": null,
"e": 32522,
"s": 32279,
"text": "The following example implements a class Complex that represents the real and imaginary part of a complex number and also defines the binary + operator to allow the addition of two Complex objects. The operator+ function is expression-bodied."
},
{
"code": null,
"e": 32525,
"s": 32522,
"text": "C#"
},
{
"code": "// C# program to illustrate expression-bodied operator functionsusing System; public struct Complex{ public int Real{get; set;} public int Imaginary{get; set;} public Complex(int real, int imaginary) { Real = real; Imaginary = imaginary; } // Expression-bodied operator method public static Complex operator + ( Complex c1, Complex c2) => new Complex(c1.Real + c1.Real, c1.Imaginary + c2.Imaginary); public override string ToString() => $\"({Real}) + ({Imaginary}i)\";} class GFG{ // Driver code public static void Main(){ var a = new Complex(3, 2); var b = new Complex(1, 2); var result = a + b; Console.WriteLine($\"{a} + {b} = {result}\");}}",
"e": 33273,
"s": 32525,
"text": null
},
{
"code": null,
"e": 33281,
"s": 33273,
"text": "Output:"
},
{
"code": null,
"e": 33318,
"s": 33281,
"text": "(3) + (2i) + (1) + (2i) = (6) + (4i)"
},
{
"code": null,
"e": 33333,
"s": 33318,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 33343,
"s": 33333,
"text": "Blogathon"
},
{
"code": null,
"e": 33346,
"s": 33343,
"text": "C#"
},
{
"code": null,
"e": 33444,
"s": 33346,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33453,
"s": 33444,
"text": "Comments"
},
{
"code": null,
"e": 33466,
"s": 33453,
"text": "Old Comments"
},
{
"code": null,
"e": 33507,
"s": 33466,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 33542,
"s": 33507,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 33599,
"s": 33542,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 33637,
"s": 33599,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 33700,
"s": 33637,
"text": "How to pass data into table from a form using React Components"
},
{
"code": null,
"e": 33754,
"s": 33700,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 33782,
"s": 33754,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 33844,
"s": 33782,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 33886,
"s": 33844,
"text": "String.Split() Method in C# with Examples"
}
] |
PHP Expressions
|
Almost everything in a PHP script is an expression. Anything that has a value is an expression. In a typical assignment statement ($x=100), a literal value, a function or operands processed by operators is an expression, anything that appears to the right of assignment operator (=)
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression
These operators are called increment and decrement operators respectively. They are unary operators, needing just one operand and can be used in prefix or postfix manner, although with different effect on value of expression
Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator decrements by 1). However, when used in assignment expression, prefix makesincremnt/decrement first and then followed by assignment. In case of postfix, assignment is done before increment/decrement
Uses postfix ++ operator
Live Demo
<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>
This produces following result
x = 11 y = 10
Whereas following example uses prefix increment operator in assignment
Live Demo
<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
echo "x = $x y = $y";
?>
This produces following result
x = 11 y = 11
Ternary operator has three operands. First one is a logical expression. If it is TRU, second operand expression is evaluated otherwise third one is evaluated
Live Demo
<?php
$marks=60;
$result= $marks<50 ? "fail" : "pass";
echo $result;
?>
Following result will be displayed
pass
|
[
{
"code": null,
"e": 1345,
"s": 1062,
"text": "Almost everything in a PHP script is an expression. Anything that has a value is an expression. In a typical assignment statement ($x=100), a literal value, a function or operands processed by operators is an expression, anything that appears to the right of assignment operator (=)"
},
{
"code": null,
"e": 1538,
"s": 1345,
"text": "$x=100; //100 is an expression\n$a=$b+$c; //b+$c is an expression\n$c=add($a,$b); //add($a,$b) is an expresson\n$val=sqrt(100); //sqrt(100) is an expression\n$var=$x!=$y; //$x!=$y is an expression"
},
{
"code": null,
"e": 1763,
"s": 1538,
"text": "These operators are called increment and decrement operators respectively. They are unary operators, needing just one operand and can be used in prefix or postfix manner, although with different effect on value of expression"
},
{
"code": null,
"e": 2052,
"s": 1763,
"text": "Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator decrements by 1). However, when used in assignment expression, prefix makesincremnt/decrement first and then followed by assignment. In case of postfix, assignment is done before increment/decrement"
},
{
"code": null,
"e": 2077,
"s": 2052,
"text": "Uses postfix ++ operator"
},
{
"code": null,
"e": 2088,
"s": 2077,
"text": " Live Demo"
},
{
"code": null,
"e": 2177,
"s": 2088,
"text": "<?php\n$x=10;\n$y=$x++; //equivalent to $y=$x followed by $x=$x+1\necho \"x = $x y = $y\";\n?>"
},
{
"code": null,
"e": 2208,
"s": 2177,
"text": "This produces following result"
},
{
"code": null,
"e": 2222,
"s": 2208,
"text": "x = 11 y = 10"
},
{
"code": null,
"e": 2293,
"s": 2222,
"text": "Whereas following example uses prefix increment operator in assignment"
},
{
"code": null,
"e": 2304,
"s": 2293,
"text": " Live Demo"
},
{
"code": null,
"e": 2394,
"s": 2304,
"text": "<?php\n$x=10;\n$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x\necho \"x = $x y = $y\";\n?>"
},
{
"code": null,
"e": 2425,
"s": 2394,
"text": "This produces following result"
},
{
"code": null,
"e": 2439,
"s": 2425,
"text": "x = 11 y = 11"
},
{
"code": null,
"e": 2597,
"s": 2439,
"text": "Ternary operator has three operands. First one is a logical expression. If it is TRU, second operand expression is evaluated otherwise third one is evaluated"
},
{
"code": null,
"e": 2608,
"s": 2597,
"text": " Live Demo"
},
{
"code": null,
"e": 2680,
"s": 2608,
"text": "<?php\n$marks=60;\n$result= $marks<50 ? \"fail\" : \"pass\";\necho $result;\n?>"
},
{
"code": null,
"e": 2715,
"s": 2680,
"text": "Following result will be displayed"
},
{
"code": null,
"e": 2720,
"s": 2715,
"text": "pass"
}
] |
Selenium Webdriver - Action Class
|
Selenium can perform mouse movements, key press, hovering on an element, drag and drop actions, and so on with the help of the ActionsChains class. We have to create an instance of the ActionChains class which shall hold all actions in a queue.
Then the method - perform is invoked which actually performs the tasks in the order in which they are queued. We have to add the statement from selenium.webdriver import ActionChains to work with the ActionChains class.
The syntax for ActionChains class is as follows −
#Method 1 - chained pattern
e =driver.find_element_by_css_selector(".txt")
a = ActionChains(driver)
a.move_to_element(e).click().perform()
#Method 2 - queued actions one after another
e =driver.find_element_by_css_selector(".txt")
a = ActionChains(driver)
a.move_to_element(e)
a.click() a.perform()
In both the above methods, the actions are performed in sequence in which they are called, one by one.
The methods of ActionChains class are listed below −
click − It is used to click a webelement.
click − It is used to click a webelement.
click_and_hold − It is used to hold down the left mouse button on a webelement.
click_and_hold − It is used to hold down the left mouse button on a webelement.
double_click − It is used to double click a webelement.
double_click − It is used to double click a webelement.
context_click − It is used to right click a webelement.
context_click − It is used to right click a webelement.
drag_and_drop_by_offset − It is used to first perform pressing the left mouse on the source element, navigating to the target offset and finally releasing the mouse.
drag_and_drop_by_offset − It is used to first perform pressing the left mouse on the source element, navigating to the target offset and finally releasing the mouse.
drag_and_drop − It is used to first perform pressing the left mouse on the source element, navigating to the target element and finally releasing the mouse.
drag_and_drop − It is used to first perform pressing the left mouse on the source element, navigating to the target element and finally releasing the mouse.
key_up − It is used to release a modifier key.
key_up − It is used to release a modifier key.
key_down − It is used for a keypress without releasing it.
key_down − It is used for a keypress without releasing it.
move_to_element − It is used to move the mouse to the middle of a webelement.
move_to_element − It is used to move the mouse to the middle of a webelement.
move_by_offset − It is used to move the mouse to an offset from the present mouse position.
move_by_offset − It is used to move the mouse to an offset from the present mouse position.
Perform − It is used to execute the queued actions.
Perform − It is used to execute the queued actions.
move_to_element_by_offset − It is used to move the mouse by an offset of a particular webelement. The offsets are measured from the left-upper corner of the webelement.
move_to_element_by_offset − It is used to move the mouse by an offset of a particular webelement. The offsets are measured from the left-upper corner of the webelement.
Release − It is used to release a held mouse button on a webelement.
Release − It is used to release a held mouse button on a webelement.
Pause − It is used to stop every input for a particular duration in seconds.
Pause − It is used to stop every input for a particular duration in seconds.
send_keys − It is used to send keys to the present active element.
send_keys − It is used to send keys to the present active element.
reset_actions − It is used to delete all actions that are held locally and in remote.
reset_actions − It is used to delete all actions that are held locally and in remote.
Let us click on the link - Privacy Policy using the ActionChains methods −
The code implementation for ActionChains class is as follows −
from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(5)
#url launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element
s = driver.find_element_by_link_text("Privacy Policy")
#instance of ActionChains
a= ActionChains(driver)
#move to element
a.move_to_element(s)
#click
a.click().perform()
#get page title
print('Page title: ' + driver.title)
#driver quit
driver.close()
The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application(obtained from the driver.title method) - About Privacy Policy at Tutorials Point - Tutorialspoint gets printed in the console.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2448,
"s": 2203,
"text": "Selenium can perform mouse movements, key press, hovering on an element, drag and drop actions, and so on with the help of the ActionsChains class. We have to create an instance of the ActionChains class which shall hold all actions in a queue."
},
{
"code": null,
"e": 2668,
"s": 2448,
"text": "Then the method - perform is invoked which actually performs the tasks in the order in which they are queued. We have to add the statement from selenium.webdriver import ActionChains to work with the ActionChains class."
},
{
"code": null,
"e": 2718,
"s": 2668,
"text": "The syntax for ActionChains class is as follows −"
},
{
"code": null,
"e": 2746,
"s": 2718,
"text": "#Method 1 - chained pattern"
},
{
"code": null,
"e": 2860,
"s": 2746,
"text": "e =driver.find_element_by_css_selector(\".txt\") \na = ActionChains(driver) \na.move_to_element(e).click().perform()\n"
},
{
"code": null,
"e": 2905,
"s": 2860,
"text": "#Method 2 - queued actions one after another"
},
{
"code": null,
"e": 3024,
"s": 2905,
"text": "e =driver.find_element_by_css_selector(\".txt\") \na = ActionChains(driver) \na.move_to_element(e) \na.click() a.perform()\n"
},
{
"code": null,
"e": 3127,
"s": 3024,
"text": "In both the above methods, the actions are performed in sequence in which they are called, one by one."
},
{
"code": null,
"e": 3180,
"s": 3127,
"text": "The methods of ActionChains class are listed below −"
},
{
"code": null,
"e": 3222,
"s": 3180,
"text": "click − It is used to click a webelement."
},
{
"code": null,
"e": 3264,
"s": 3222,
"text": "click − It is used to click a webelement."
},
{
"code": null,
"e": 3344,
"s": 3264,
"text": "click_and_hold − It is used to hold down the left mouse button on a webelement."
},
{
"code": null,
"e": 3424,
"s": 3344,
"text": "click_and_hold − It is used to hold down the left mouse button on a webelement."
},
{
"code": null,
"e": 3480,
"s": 3424,
"text": "double_click − It is used to double click a webelement."
},
{
"code": null,
"e": 3536,
"s": 3480,
"text": "double_click − It is used to double click a webelement."
},
{
"code": null,
"e": 3592,
"s": 3536,
"text": "context_click − It is used to right click a webelement."
},
{
"code": null,
"e": 3648,
"s": 3592,
"text": "context_click − It is used to right click a webelement."
},
{
"code": null,
"e": 3814,
"s": 3648,
"text": "drag_and_drop_by_offset − It is used to first perform pressing the left mouse on the source element, navigating to the target offset and finally releasing the mouse."
},
{
"code": null,
"e": 3980,
"s": 3814,
"text": "drag_and_drop_by_offset − It is used to first perform pressing the left mouse on the source element, navigating to the target offset and finally releasing the mouse."
},
{
"code": null,
"e": 4137,
"s": 3980,
"text": "drag_and_drop − It is used to first perform pressing the left mouse on the source element, navigating to the target element and finally releasing the mouse."
},
{
"code": null,
"e": 4294,
"s": 4137,
"text": "drag_and_drop − It is used to first perform pressing the left mouse on the source element, navigating to the target element and finally releasing the mouse."
},
{
"code": null,
"e": 4341,
"s": 4294,
"text": "key_up − It is used to release a modifier key."
},
{
"code": null,
"e": 4388,
"s": 4341,
"text": "key_up − It is used to release a modifier key."
},
{
"code": null,
"e": 4447,
"s": 4388,
"text": "key_down − It is used for a keypress without releasing it."
},
{
"code": null,
"e": 4506,
"s": 4447,
"text": "key_down − It is used for a keypress without releasing it."
},
{
"code": null,
"e": 4584,
"s": 4506,
"text": "move_to_element − It is used to move the mouse to the middle of a webelement."
},
{
"code": null,
"e": 4662,
"s": 4584,
"text": "move_to_element − It is used to move the mouse to the middle of a webelement."
},
{
"code": null,
"e": 4754,
"s": 4662,
"text": "move_by_offset − It is used to move the mouse to an offset from the present mouse position."
},
{
"code": null,
"e": 4846,
"s": 4754,
"text": "move_by_offset − It is used to move the mouse to an offset from the present mouse position."
},
{
"code": null,
"e": 4898,
"s": 4846,
"text": "Perform − It is used to execute the queued actions."
},
{
"code": null,
"e": 4950,
"s": 4898,
"text": "Perform − It is used to execute the queued actions."
},
{
"code": null,
"e": 5119,
"s": 4950,
"text": "move_to_element_by_offset − It is used to move the mouse by an offset of a particular webelement. The offsets are measured from the left-upper corner of the webelement."
},
{
"code": null,
"e": 5288,
"s": 5119,
"text": "move_to_element_by_offset − It is used to move the mouse by an offset of a particular webelement. The offsets are measured from the left-upper corner of the webelement."
},
{
"code": null,
"e": 5357,
"s": 5288,
"text": "Release − It is used to release a held mouse button on a webelement."
},
{
"code": null,
"e": 5426,
"s": 5357,
"text": "Release − It is used to release a held mouse button on a webelement."
},
{
"code": null,
"e": 5503,
"s": 5426,
"text": "Pause − It is used to stop every input for a particular duration in seconds."
},
{
"code": null,
"e": 5580,
"s": 5503,
"text": "Pause − It is used to stop every input for a particular duration in seconds."
},
{
"code": null,
"e": 5647,
"s": 5580,
"text": "send_keys − It is used to send keys to the present active element."
},
{
"code": null,
"e": 5714,
"s": 5647,
"text": "send_keys − It is used to send keys to the present active element."
},
{
"code": null,
"e": 5800,
"s": 5714,
"text": "reset_actions − It is used to delete all actions that are held locally and in remote."
},
{
"code": null,
"e": 5886,
"s": 5800,
"text": "reset_actions − It is used to delete all actions that are held locally and in remote."
},
{
"code": null,
"e": 5961,
"s": 5886,
"text": "Let us click on the link - Privacy Policy using the ActionChains methods −"
},
{
"code": null,
"e": 6024,
"s": 5961,
"text": "The code implementation for ActionChains class is as follows −"
},
{
"code": null,
"e": 6564,
"s": 6024,
"text": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify element\ns = driver.find_element_by_link_text(\"Privacy Policy\")\n#instance of ActionChains\na= ActionChains(driver)\n#move to element\na.move_to_element(s)\n#click\na.click().perform()\n#get page title\nprint('Page title: ' + driver.title)\n#driver quit\ndriver.close()"
},
{
"code": null,
"e": 6845,
"s": 6564,
"text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application(obtained from the driver.title method) - About Privacy Policy at Tutorials Point - Tutorialspoint gets printed in the console."
},
{
"code": null,
"e": 6880,
"s": 6845,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6892,
"s": 6880,
"text": " Aditya Dua"
},
{
"code": null,
"e": 6928,
"s": 6892,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 6942,
"s": 6928,
"text": " Arun Motoori"
},
{
"code": null,
"e": 6979,
"s": 6942,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 7001,
"s": 6979,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7034,
"s": 7001,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7048,
"s": 7034,
"text": " Arun Motoori"
},
{
"code": null,
"e": 7083,
"s": 7048,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 7097,
"s": 7083,
"text": " Arun Motoori"
},
{
"code": null,
"e": 7134,
"s": 7097,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 7148,
"s": 7134,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7155,
"s": 7148,
"text": " Print"
},
{
"code": null,
"e": 7166,
"s": 7155,
"text": " Add Notes"
}
] |
MATLAB - if...elseif...elseif...else...end Statements
|
An if statement can be followed by one (or more) optional elseif... and an else statement, which is very useful to test various conditions.
When using if... elseif...else statements, there are few points to keep in mind −
An if can have zero or one else's and it must come after any elseif's.
An if can have zero or one else's and it must come after any elseif's.
An if can have zero to many elseif's and they must come before the else.
An if can have zero to many elseif's and they must come before the else.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
if <expression 1>
% Executes when the expression 1 is true
<statement(s)>
elseif <expression 2>
% Executes when the boolean expression 2 is true
<statement(s)>
Elseif <expression 3>
% Executes when the boolean expression 3 is true
<statement(s)>
else
% executes when the none of the above condition is true
<statement(s)>
end
Create a script file and type the following code in it −
a = 100;
%check the boolean condition
if a == 10
% if condition is true then print the following
fprintf('Value of a is 10\n' );
elseif( a == 20 )
% if else if condition is true
fprintf('Value of a is 20\n' );
elseif a == 30
% if else if condition is true
fprintf('Value of a is 30\n' );
else
% if none of the conditions is true '
fprintf('None of the values are matching\n');
fprintf('Exact value of a is: %d\n', a );
end
When the above code is compiled and executed, it produces the following result −
None of the values are matching
Exact value of a is: 100
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2281,
"s": 2141,
"text": "An if statement can be followed by one (or more) optional elseif... and an else statement, which is very useful to test various conditions."
},
{
"code": null,
"e": 2363,
"s": 2281,
"text": "When using if... elseif...else statements, there are few points to keep in mind −"
},
{
"code": null,
"e": 2434,
"s": 2363,
"text": "An if can have zero or one else's and it must come after any elseif's."
},
{
"code": null,
"e": 2505,
"s": 2434,
"text": "An if can have zero or one else's and it must come after any elseif's."
},
{
"code": null,
"e": 2578,
"s": 2505,
"text": "An if can have zero to many elseif's and they must come before the else."
},
{
"code": null,
"e": 2651,
"s": 2578,
"text": "An if can have zero to many elseif's and they must come before the else."
},
{
"code": null,
"e": 2734,
"s": 2651,
"text": "Once an else if succeeds, none of the remaining elseif's or else's will be tested."
},
{
"code": null,
"e": 2817,
"s": 2734,
"text": "Once an else if succeeds, none of the remaining elseif's or else's will be tested."
},
{
"code": null,
"e": 3176,
"s": 2817,
"text": "if <expression 1>\n % Executes when the expression 1 is true \n <statement(s)>\n\nelseif <expression 2>\n % Executes when the boolean expression 2 is true\n <statement(s)>\n\nElseif <expression 3>\n % Executes when the boolean expression 3 is true \n <statement(s)>\n\nelse \n % executes when the none of the above condition is true \n <statement(s)>\nend\n"
},
{
"code": null,
"e": 3233,
"s": 3176,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 3729,
"s": 3233,
"text": "a = 100;\n%check the boolean condition \n if a == 10 \n % if condition is true then print the following \n fprintf('Value of a is 10\\n' );\n elseif( a == 20 )\n % if else if condition is true \n fprintf('Value of a is 20\\n' );\n elseif a == 30 \n % if else if condition is true \n fprintf('Value of a is 30\\n' );\n else\n % if none of the conditions is true '\n fprintf('None of the values are matching\\n');\n fprintf('Exact value of a is: %d\\n', a );\n end"
},
{
"code": null,
"e": 3810,
"s": 3729,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3868,
"s": 3810,
"text": "None of the values are matching\nExact value of a is: 100\n"
},
{
"code": null,
"e": 3901,
"s": 3868,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3914,
"s": 3901,
"text": " Nouman Azam"
},
{
"code": null,
"e": 3949,
"s": 3914,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3962,
"s": 3949,
"text": " Nouman Azam"
},
{
"code": null,
"e": 3995,
"s": 3962,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4004,
"s": 3995,
"text": " Sanjeev"
},
{
"code": null,
"e": 4037,
"s": 4004,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4053,
"s": 4037,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4086,
"s": 4053,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4102,
"s": 4086,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4135,
"s": 4102,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4152,
"s": 4135,
"text": " Phinite Academy"
},
{
"code": null,
"e": 4159,
"s": 4152,
"text": " Print"
},
{
"code": null,
"e": 4170,
"s": 4159,
"text": " Add Notes"
}
] |
Continuous Uniform Distribution in R - GeeksforGeeks
|
06 Jun, 2021
The continuous uniform distribution is also referred to as the probability distribution of any random number selection from the continuous interval defined between intervals a and b. A uniform distribution holds the same probability for the entire interval. Thus, its plot is a rectangle, and therefore it is often referred to as Rectangular distribution. Here we will discuss various functions and cases in which these functions should be used to get a required probability.
For uniform distribution, we first need a randomly created sequence ranging between two numbers. The runif() function in R programming language is used to generate a sequence of random following the uniform distribution.
Syntax:
runif(n, min = 0, max = 1)
Parameter:
n= number of random samples
min=minimum value(by default 0)
max=maximum value(by default 1)
Example:
R
print("Random 15 numbers between 1 and 3")runif(15, min=1, max=3)
Output
[1] “Random 15 numbers between 1 and 3”
[1] 1.534 1.772 1.027 1.765 2.739 1.681 1.964 2.199 1.987 1.372 2.655 2.337 2.588 1.216 2.447
By a quantile, we mean the fraction (or percent) of points below the given value. qunif() method is used to calculate the corresponding quantile for any probability (p) for a given uniform distribution. To use this simply the function had to be called with the required parameters.
Syntax:
qunif(p, min = 0, max = 1)
Parameter :
p – The vector of probabilities
min , max – The limits for calculation of quantile function
Example 1:
R
min <- 0max <- 40 print ("Quantile Function Value") # calculating the quantile function valuequnif(0.2, min = min, max = max)
Output
[1] “Quantile Function Value”
[1] 8
The x values can be specified in the form of a sequence of vectors using the seq() method in R. The corresponding y positions can be calculated.
Example 2:
R
min <- 0max <- 1 # Specify x-values for qunif functionxpos <- seq(min, max , by = 0.02) # supplying corresponding y coordinationsypos <- qunif(xpos, min = 10, max = 100) # plotting the graph plot(ypos)
Output
dunif() method in R programming language is used to generate density function. It calculates the uniform density function in R language in the specified interval (a, b).
Syntax:
dunif(x, min = 0, max = 1, log = FALSE)
Parameter:
x: input sequence
min, max= range of values
log: indicator, of whether to display the output values as probabilities.
The result produced will be for each value of the interval. Hence, a sequence will be generated.
Example 1:
R
# generating a sequence of valuesx <- 5:10print ("dunif value") # calculating density functiondunif(x, min = 1, max = 20)
Output
[1] “dunif value”
[1] 0.05263158 0.05263158 0.05263158 0.05263158 0.05263158 0.05263158
All values are equal and this is the reason why it is called uniform distribution. Let us plot it for a better picture.
Example 2:
R
min <- 0max <- 100 # Specify x-values for qunif functionxpos <- seq(min, max , by = 0.5) # supplying corresponding y coordinationsypos <- dunif(xpos, min = 10, max = 80) # plotting the graph plot(ypos , type="o")
Output
The punif() method in R is used to calculate the uniform cumulative distribution function, this is, the probability of a variable X taking a value lower than x (that is, x <= X). If we need to compute a value x > X, we can calculate 1 – punif(x).
Syntax:
punif(q, min = 0, max = 1, lower.tail = TRUE)
All the independent probabilities that satisfy the comparison condition will be added.
Example:
R
min <- 0 max <- 60 # calculating punif valuepunif (15 , min =min , max = max)
Output
[1] 0.25
Example:
R
min <- 0 max <- 60 # calculating punif valuepunif (15 , min =min , max = max, lower.tail=FALSE)
Output
[1] 0.75
Picked
R-Statistics
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 Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 25719,
"s": 25242,
"text": "The continuous uniform distribution is also referred to as the probability distribution of any random number selection from the continuous interval defined between intervals a and b. A uniform distribution holds the same probability for the entire interval. Thus, its plot is a rectangle, and therefore it is often referred to as Rectangular distribution. Here we will discuss various functions and cases in which these functions should be used to get a required probability."
},
{
"code": null,
"e": 25942,
"s": 25719,
"text": "For uniform distribution, we first need a randomly created sequence ranging between two numbers. The runif() function in R programming language is used to generate a sequence of random following the uniform distribution. "
},
{
"code": null,
"e": 25950,
"s": 25942,
"text": "Syntax:"
},
{
"code": null,
"e": 25978,
"s": 25950,
"text": "runif(n, min = 0, max = 1) "
},
{
"code": null,
"e": 25989,
"s": 25978,
"text": "Parameter:"
},
{
"code": null,
"e": 26017,
"s": 25989,
"text": "n= number of random samples"
},
{
"code": null,
"e": 26049,
"s": 26017,
"text": "min=minimum value(by default 0)"
},
{
"code": null,
"e": 26081,
"s": 26049,
"text": "max=maximum value(by default 1)"
},
{
"code": null,
"e": 26090,
"s": 26081,
"text": "Example:"
},
{
"code": null,
"e": 26092,
"s": 26090,
"text": "R"
},
{
"code": "print(\"Random 15 numbers between 1 and 3\")runif(15, min=1, max=3) ",
"e": 26159,
"s": 26092,
"text": null
},
{
"code": null,
"e": 26166,
"s": 26159,
"text": "Output"
},
{
"code": null,
"e": 26207,
"s": 26166,
"text": "[1] “Random 15 numbers between 1 and 3” "
},
{
"code": null,
"e": 26301,
"s": 26207,
"text": "[1] 1.534 1.772 1.027 1.765 2.739 1.681 1.964 2.199 1.987 1.372 2.655 2.337 2.588 1.216 2.447"
},
{
"code": null,
"e": 26583,
"s": 26301,
"text": "By a quantile, we mean the fraction (or percent) of points below the given value. qunif() method is used to calculate the corresponding quantile for any probability (p) for a given uniform distribution. To use this simply the function had to be called with the required parameters."
},
{
"code": null,
"e": 26591,
"s": 26583,
"text": "Syntax:"
},
{
"code": null,
"e": 26619,
"s": 26591,
"text": "qunif(p, min = 0, max = 1)"
},
{
"code": null,
"e": 26632,
"s": 26619,
"text": "Parameter : "
},
{
"code": null,
"e": 26664,
"s": 26632,
"text": "p – The vector of probabilities"
},
{
"code": null,
"e": 26724,
"s": 26664,
"text": "min , max – The limits for calculation of quantile function"
},
{
"code": null,
"e": 26735,
"s": 26724,
"text": "Example 1:"
},
{
"code": null,
"e": 26737,
"s": 26735,
"text": "R"
},
{
"code": "min <- 0max <- 40 print (\"Quantile Function Value\") # calculating the quantile function valuequnif(0.2, min = min, max = max)",
"e": 26865,
"s": 26737,
"text": null
},
{
"code": null,
"e": 26872,
"s": 26865,
"text": "Output"
},
{
"code": null,
"e": 26903,
"s": 26872,
"text": "[1] “Quantile Function Value” "
},
{
"code": null,
"e": 26909,
"s": 26903,
"text": "[1] 8"
},
{
"code": null,
"e": 27055,
"s": 26909,
"text": "The x values can be specified in the form of a sequence of vectors using the seq() method in R. The corresponding y positions can be calculated. "
},
{
"code": null,
"e": 27066,
"s": 27055,
"text": "Example 2:"
},
{
"code": null,
"e": 27068,
"s": 27066,
"text": "R"
},
{
"code": "min <- 0max <- 1 # Specify x-values for qunif functionxpos <- seq(min, max , by = 0.02) # supplying corresponding y coordinationsypos <- qunif(xpos, min = 10, max = 100) # plotting the graph plot(ypos) ",
"e": 27303,
"s": 27068,
"text": null
},
{
"code": null,
"e": 27310,
"s": 27303,
"text": "Output"
},
{
"code": null,
"e": 27481,
"s": 27310,
"text": "dunif() method in R programming language is used to generate density function. It calculates the uniform density function in R language in the specified interval (a, b). "
},
{
"code": null,
"e": 27489,
"s": 27481,
"text": "Syntax:"
},
{
"code": null,
"e": 27532,
"s": 27489,
"text": "dunif(x, min = 0, max = 1, log = FALSE)"
},
{
"code": null,
"e": 27543,
"s": 27532,
"text": "Parameter:"
},
{
"code": null,
"e": 27561,
"s": 27543,
"text": "x: input sequence"
},
{
"code": null,
"e": 27587,
"s": 27561,
"text": "min, max= range of values"
},
{
"code": null,
"e": 27661,
"s": 27587,
"text": "log: indicator, of whether to display the output values as probabilities."
},
{
"code": null,
"e": 27758,
"s": 27661,
"text": "The result produced will be for each value of the interval. Hence, a sequence will be generated."
},
{
"code": null,
"e": 27769,
"s": 27758,
"text": "Example 1:"
},
{
"code": null,
"e": 27771,
"s": 27769,
"text": "R"
},
{
"code": "# generating a sequence of valuesx <- 5:10print (\"dunif value\") # calculating density functiondunif(x, min = 1, max = 20)",
"e": 27894,
"s": 27771,
"text": null
},
{
"code": null,
"e": 27901,
"s": 27894,
"text": "Output"
},
{
"code": null,
"e": 27920,
"s": 27901,
"text": "[1] “dunif value” "
},
{
"code": null,
"e": 27990,
"s": 27920,
"text": "[1] 0.05263158 0.05263158 0.05263158 0.05263158 0.05263158 0.05263158"
},
{
"code": null,
"e": 28110,
"s": 27990,
"text": "All values are equal and this is the reason why it is called uniform distribution. Let us plot it for a better picture."
},
{
"code": null,
"e": 28122,
"s": 28110,
"text": "Example 2: "
},
{
"code": null,
"e": 28124,
"s": 28122,
"text": "R"
},
{
"code": "min <- 0max <- 100 # Specify x-values for qunif functionxpos <- seq(min, max , by = 0.5) # supplying corresponding y coordinationsypos <- dunif(xpos, min = 10, max = 80) # plotting the graph plot(ypos , type=\"o\") ",
"e": 28371,
"s": 28124,
"text": null
},
{
"code": null,
"e": 28378,
"s": 28371,
"text": "Output"
},
{
"code": null,
"e": 28625,
"s": 28378,
"text": "The punif() method in R is used to calculate the uniform cumulative distribution function, this is, the probability of a variable X taking a value lower than x (that is, x <= X). If we need to compute a value x > X, we can calculate 1 – punif(x)."
},
{
"code": null,
"e": 28633,
"s": 28625,
"text": "Syntax:"
},
{
"code": null,
"e": 28683,
"s": 28633,
"text": "punif(q, min = 0, max = 1, lower.tail = TRUE)"
},
{
"code": null,
"e": 28770,
"s": 28683,
"text": "All the independent probabilities that satisfy the comparison condition will be added."
},
{
"code": null,
"e": 28779,
"s": 28770,
"text": "Example:"
},
{
"code": null,
"e": 28781,
"s": 28779,
"text": "R"
},
{
"code": "min <- 0 max <- 60 # calculating punif valuepunif (15 , min =min , max = max)",
"e": 28860,
"s": 28781,
"text": null
},
{
"code": null,
"e": 28867,
"s": 28860,
"text": "Output"
},
{
"code": null,
"e": 28876,
"s": 28867,
"text": "[1] 0.25"
},
{
"code": null,
"e": 28885,
"s": 28876,
"text": "Example:"
},
{
"code": null,
"e": 28887,
"s": 28885,
"text": "R"
},
{
"code": "min <- 0 max <- 60 # calculating punif valuepunif (15 , min =min , max = max, lower.tail=FALSE)",
"e": 28984,
"s": 28887,
"text": null
},
{
"code": null,
"e": 28991,
"s": 28984,
"text": "Output"
},
{
"code": null,
"e": 29000,
"s": 28991,
"text": "[1] 0.75"
},
{
"code": null,
"e": 29007,
"s": 29000,
"text": "Picked"
},
{
"code": null,
"e": 29020,
"s": 29007,
"text": "R-Statistics"
},
{
"code": null,
"e": 29031,
"s": 29020,
"text": "R Language"
},
{
"code": null,
"e": 29129,
"s": 29031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29181,
"s": 29129,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29219,
"s": 29181,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29254,
"s": 29219,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29312,
"s": 29254,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29361,
"s": 29312,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29398,
"s": 29361,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29448,
"s": 29398,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29491,
"s": 29448,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29517,
"s": 29491,
"text": "Time Series Analysis in R"
}
] |
Pyspark – Aggregation on multiple columns
|
19 Dec, 2021
In this article, we will discuss how to perform aggregation on multiple columns in Pyspark using Python. We can do this by using Groupby() function
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.show()
Output:
In PySpark, groupBy() is used to collect the identical data into groups on the PySpark DataFrame and perform aggregate functions on the grouped data
count(): This will return the count of rows for each group.
dataframe.groupBy(‘column_name_group’).count()
mean(): This will return the mean of values for each group.
dataframe.groupBy(‘column_name_group’).mean(‘column_name’)
max(): This will return the maximum of values for each group.
dataframe.groupBy(‘column_name_group’).max(‘column_name’)
min(): This will return the minimum of values for each group.
dataframe.groupBy(‘column_name_group’).min(‘column_name’)
sum(): This will return the total values for each group.
dataframe.groupBy(‘column_name_group’).sum(‘column_name’)
avg(): This will return the average for values for each group.
dataframe.groupBy(‘column_name_group’).avg(‘column_name’).show()
We can groupBy and aggregate on multiple columns at a time by using the following syntax:
dataframe.groupBy(‘column_name_group1′,’column_name_group2′,............,’column_name_group n’).aggregate_operation(‘column_name’)
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT and NAME with mean()dataframe.groupBy('DEPT', 'NAME').mean('FEE').show()
Output:
Example 2: Aggregation on all columns
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT,ID and NAME with mean()dataframe.groupBy('DEPT', 'ID', 'NAME').mean('FEE').show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 176,
"s": 28,
"text": "In this article, we will discuss how to perform aggregation on multiple columns in Pyspark using Python. We can do this by using Groupby() function"
},
{
"code": null,
"e": 184,
"s": 176,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.show()",
"e": 932,
"s": 184,
"text": null
},
{
"code": null,
"e": 940,
"s": 932,
"text": "Output:"
},
{
"code": null,
"e": 1089,
"s": 940,
"text": "In PySpark, groupBy() is used to collect the identical data into groups on the PySpark DataFrame and perform aggregate functions on the grouped data"
},
{
"code": null,
"e": 1149,
"s": 1089,
"text": "count(): This will return the count of rows for each group."
},
{
"code": null,
"e": 1196,
"s": 1149,
"text": "dataframe.groupBy(‘column_name_group’).count()"
},
{
"code": null,
"e": 1256,
"s": 1196,
"text": "mean(): This will return the mean of values for each group."
},
{
"code": null,
"e": 1315,
"s": 1256,
"text": "dataframe.groupBy(‘column_name_group’).mean(‘column_name’)"
},
{
"code": null,
"e": 1377,
"s": 1315,
"text": "max(): This will return the maximum of values for each group."
},
{
"code": null,
"e": 1435,
"s": 1377,
"text": "dataframe.groupBy(‘column_name_group’).max(‘column_name’)"
},
{
"code": null,
"e": 1497,
"s": 1435,
"text": "min(): This will return the minimum of values for each group."
},
{
"code": null,
"e": 1555,
"s": 1497,
"text": "dataframe.groupBy(‘column_name_group’).min(‘column_name’)"
},
{
"code": null,
"e": 1612,
"s": 1555,
"text": "sum(): This will return the total values for each group."
},
{
"code": null,
"e": 1670,
"s": 1612,
"text": "dataframe.groupBy(‘column_name_group’).sum(‘column_name’)"
},
{
"code": null,
"e": 1733,
"s": 1670,
"text": "avg(): This will return the average for values for each group."
},
{
"code": null,
"e": 1798,
"s": 1733,
"text": "dataframe.groupBy(‘column_name_group’).avg(‘column_name’).show()"
},
{
"code": null,
"e": 1890,
"s": 1798,
"text": "We can groupBy and aggregate on multiple columns at a time by using the following syntax:"
},
{
"code": null,
"e": 2021,
"s": 1890,
"text": "dataframe.groupBy(‘column_name_group1′,’column_name_group2′,............,’column_name_group n’).aggregate_operation(‘column_name’)"
},
{
"code": null,
"e": 2029,
"s": 2021,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT and NAME with mean()dataframe.groupBy('DEPT', 'NAME').mean('FEE').show()",
"e": 2844,
"s": 2029,
"text": null
},
{
"code": null,
"e": 2852,
"s": 2844,
"text": "Output:"
},
{
"code": null,
"e": 2890,
"s": 2852,
"text": "Example 2: Aggregation on all columns"
},
{
"code": null,
"e": 2898,
"s": 2890,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT,ID and NAME with mean()dataframe.groupBy('DEPT', 'ID', 'NAME').mean('FEE').show()",
"e": 3722,
"s": 2898,
"text": null
},
{
"code": null,
"e": 3730,
"s": 3722,
"text": "Output:"
},
{
"code": null,
"e": 3737,
"s": 3730,
"text": "Picked"
},
{
"code": null,
"e": 3752,
"s": 3737,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 3759,
"s": 3752,
"text": "Python"
},
{
"code": null,
"e": 3857,
"s": 3759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3875,
"s": 3857,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3917,
"s": 3875,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3939,
"s": 3917,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3974,
"s": 3939,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4000,
"s": 3974,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4032,
"s": 4000,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4061,
"s": 4032,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4088,
"s": 4061,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4118,
"s": 4088,
"text": "Iterate over a list in Python"
}
] |
How to Filter and save the data as new files in Excel with Python Pandas?
|
03 Jul, 2020
Prerequisistes: Python Pandas
Pandas is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users.
In this article, we are trying to filter the data of an excel sheet and save the filtered data as a new Excel file.
Note: You can click on this filename to download this sheet datasets.xlsx
Excel Sheet used:
In this excel sheet we are having three categories in Species column-
SetosaVersicolorVirginica
Setosa
Versicolor
Virginica
Now our aim is to filter these data by species category and to save this filtered data in different sheets with filename =species.subcategory name i.e. after the execution of the code we will going to get three files of following names-
Setosa.xlsxVersicolor.xlsxVirginica.xlsx
Setosa.xlsx
Versicolor.xlsx
Virginica.xlsx
Below is the implementation.
# Python code to filter and save the # data with different file namesimport pandas data = pandas.read_excel("datasets.xlsx") speciesdata = data["Species"].unique() for i in speciesdata: a = data[data["Species"].str.contains(i)] a.to_excel(i+".xlsx")
Output:
Explanation:
First, we have imported the Pandas library.
Then we have loaded the data.xlsx excel file in the data object.
To fetch the unique values from that species column we have used unique() function. To check the unique values in the Species column we have called the unique() in speciesdata object.
Then we will going to iterate the speciesdata object as we will going to store the Species column unique values(i.e. Setosa, Versicolor, Virginica) one by one.
In object “a” we are filtering out the data that matches the Species.speciesdata i.e. in each iteration object a will going to store three different types of data i.e. data of Setosa type then data of Versicolor type and at last the data of Virginica type.
Now to save the filtered data one by one in excel file we have used to_excel function, where, the file will going to be saved by the speciesdata name.
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 84,
"s": 54,
"text": "Prerequisistes: Python Pandas"
},
{
"code": null,
"e": 224,
"s": 84,
"text": "Pandas is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users."
},
{
"code": null,
"e": 340,
"s": 224,
"text": "In this article, we are trying to filter the data of an excel sheet and save the filtered data as a new Excel file."
},
{
"code": null,
"e": 414,
"s": 340,
"text": "Note: You can click on this filename to download this sheet datasets.xlsx"
},
{
"code": null,
"e": 432,
"s": 414,
"text": "Excel Sheet used:"
},
{
"code": null,
"e": 502,
"s": 432,
"text": "In this excel sheet we are having three categories in Species column-"
},
{
"code": null,
"e": 528,
"s": 502,
"text": "SetosaVersicolorVirginica"
},
{
"code": null,
"e": 535,
"s": 528,
"text": "Setosa"
},
{
"code": null,
"e": 546,
"s": 535,
"text": "Versicolor"
},
{
"code": null,
"e": 556,
"s": 546,
"text": "Virginica"
},
{
"code": null,
"e": 793,
"s": 556,
"text": "Now our aim is to filter these data by species category and to save this filtered data in different sheets with filename =species.subcategory name i.e. after the execution of the code we will going to get three files of following names-"
},
{
"code": null,
"e": 834,
"s": 793,
"text": "Setosa.xlsxVersicolor.xlsxVirginica.xlsx"
},
{
"code": null,
"e": 846,
"s": 834,
"text": "Setosa.xlsx"
},
{
"code": null,
"e": 862,
"s": 846,
"text": "Versicolor.xlsx"
},
{
"code": null,
"e": 877,
"s": 862,
"text": "Virginica.xlsx"
},
{
"code": null,
"e": 906,
"s": 877,
"text": "Below is the implementation."
},
{
"code": "# Python code to filter and save the # data with different file namesimport pandas data = pandas.read_excel(\"datasets.xlsx\") speciesdata = data[\"Species\"].unique() for i in speciesdata: a = data[data[\"Species\"].str.contains(i)] a.to_excel(i+\".xlsx\")",
"e": 1167,
"s": 906,
"text": null
},
{
"code": null,
"e": 1175,
"s": 1167,
"text": "Output:"
},
{
"code": null,
"e": 1188,
"s": 1175,
"text": "Explanation:"
},
{
"code": null,
"e": 1232,
"s": 1188,
"text": "First, we have imported the Pandas library."
},
{
"code": null,
"e": 1297,
"s": 1232,
"text": "Then we have loaded the data.xlsx excel file in the data object."
},
{
"code": null,
"e": 1481,
"s": 1297,
"text": "To fetch the unique values from that species column we have used unique() function. To check the unique values in the Species column we have called the unique() in speciesdata object."
},
{
"code": null,
"e": 1641,
"s": 1481,
"text": "Then we will going to iterate the speciesdata object as we will going to store the Species column unique values(i.e. Setosa, Versicolor, Virginica) one by one."
},
{
"code": null,
"e": 1898,
"s": 1641,
"text": "In object “a” we are filtering out the data that matches the Species.speciesdata i.e. in each iteration object a will going to store three different types of data i.e. data of Setosa type then data of Versicolor type and at last the data of Virginica type."
},
{
"code": null,
"e": 2049,
"s": 1898,
"text": "Now to save the filtered data one by one in excel file we have used to_excel function, where, the file will going to be saved by the speciesdata name."
},
{
"code": null,
"e": 2063,
"s": 2049,
"text": "Python-pandas"
},
{
"code": null,
"e": 2070,
"s": 2063,
"text": "Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.