title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
C library function - fprintf() | The C library function int fprintf(FILE *stream, const char *format, ...) sends formatted output to a stream.
Following is the declaration for fprintf() function.
int fprintf(FILE *stream, const char *format, ...)
stream − This is the pointer to a FILE object that identifies the stream.
stream − This is the pointer to a FILE object that identifies the stream.
format − This is the C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is %[flags][width][.precision][length]specifier, which is explained below −
format − This is the C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is %[flags][width][.precision][length]specifier, which is explained below −
c
Character
d or i
Signed decimal integer
e
Scientific notation (mantissa/exponent) using e character
E
Scientific notation (mantissa/exponent) using E character
f
Decimal floating point
g
Uses the shorter of %e or %f
G
Uses the shorter of %E or %f
o
Signed octal
s
String of characters
u
Unsigned decimal integer
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (capital letters)
p
Pointer address
n
Nothing printed
%
Character
-
Left-justifies within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign.
(space)
If no sign is written, a blank space is inserted before the value.
#
Used with o, x or X specifiers. The value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow then no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed.
0
Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.number
For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after the decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
h
The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).
l
The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.
L
The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).
additional arguments − Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value.
additional arguments − Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value.
If successful, the total number of characters written is returned otherwise, a negative number is returned.
The following example shows the usage of fprintf() function.
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * fp;
fp = fopen ("file.txt", "w+");
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012);
fclose(fp);
return(0);
}
Let us compile and run the above program that will create a file file.txt with the following content −
We are in 2012
Now let's see the content of the above file using the following program −
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1) {
c = fgetc(fp);
if( feof(fp) ) {
break;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Let us compile and run above program to produce the following result.
We are in 2012
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2117,
"s": 2007,
"text": "The C library function int fprintf(FILE *stream, const char *format, ...) sends formatted output to a stream."
},
{
"code": null,
"e": 2170,
"s": 2117,
"text": "Following is the declaration for fprintf() function."
},
{
"code": null,
"e": 2221,
"s": 2170,
"text": "int fprintf(FILE *stream, const char *format, ...)"
},
{
"code": null,
"e": 2295,
"s": 2221,
"text": "stream − This is the pointer to a FILE object that identifies the stream."
},
{
"code": null,
"e": 2369,
"s": 2295,
"text": "stream − This is the pointer to a FILE object that identifies the stream."
},
{
"code": null,
"e": 2702,
"s": 2369,
"text": "format − This is the C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is %[flags][width][.precision][length]specifier, which is explained below −"
},
{
"code": null,
"e": 3035,
"s": 2702,
"text": "format − This is the C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is %[flags][width][.precision][length]specifier, which is explained below −"
},
{
"code": null,
"e": 3037,
"s": 3035,
"text": "c"
},
{
"code": null,
"e": 3047,
"s": 3037,
"text": "Character"
},
{
"code": null,
"e": 3054,
"s": 3047,
"text": "d or i"
},
{
"code": null,
"e": 3077,
"s": 3054,
"text": "Signed decimal integer"
},
{
"code": null,
"e": 3079,
"s": 3077,
"text": "e"
},
{
"code": null,
"e": 3137,
"s": 3079,
"text": "Scientific notation (mantissa/exponent) using e character"
},
{
"code": null,
"e": 3139,
"s": 3137,
"text": "E"
},
{
"code": null,
"e": 3197,
"s": 3139,
"text": "Scientific notation (mantissa/exponent) using E character"
},
{
"code": null,
"e": 3199,
"s": 3197,
"text": "f"
},
{
"code": null,
"e": 3222,
"s": 3199,
"text": "Decimal floating point"
},
{
"code": null,
"e": 3224,
"s": 3222,
"text": "g"
},
{
"code": null,
"e": 3253,
"s": 3224,
"text": "Uses the shorter of %e or %f"
},
{
"code": null,
"e": 3255,
"s": 3253,
"text": "G"
},
{
"code": null,
"e": 3284,
"s": 3255,
"text": "Uses the shorter of %E or %f"
},
{
"code": null,
"e": 3286,
"s": 3284,
"text": "o"
},
{
"code": null,
"e": 3299,
"s": 3286,
"text": "Signed octal"
},
{
"code": null,
"e": 3301,
"s": 3299,
"text": "s"
},
{
"code": null,
"e": 3322,
"s": 3301,
"text": "String of characters"
},
{
"code": null,
"e": 3324,
"s": 3322,
"text": "u"
},
{
"code": null,
"e": 3349,
"s": 3324,
"text": "Unsigned decimal integer"
},
{
"code": null,
"e": 3351,
"s": 3349,
"text": "x"
},
{
"code": null,
"e": 3380,
"s": 3351,
"text": "Unsigned hexadecimal integer"
},
{
"code": null,
"e": 3382,
"s": 3380,
"text": "X"
},
{
"code": null,
"e": 3429,
"s": 3382,
"text": "Unsigned hexadecimal integer (capital letters)"
},
{
"code": null,
"e": 3431,
"s": 3429,
"text": "p"
},
{
"code": null,
"e": 3447,
"s": 3431,
"text": "Pointer address"
},
{
"code": null,
"e": 3449,
"s": 3447,
"text": "n"
},
{
"code": null,
"e": 3465,
"s": 3449,
"text": "Nothing printed"
},
{
"code": null,
"e": 3467,
"s": 3465,
"text": "%"
},
{
"code": null,
"e": 3477,
"s": 3467,
"text": "Character"
},
{
"code": null,
"e": 3479,
"s": 3477,
"text": "-"
},
{
"code": null,
"e": 3586,
"s": 3479,
"text": "Left-justifies within the given field width; Right justification is the default (see width sub-specifier)."
},
{
"code": null,
"e": 3588,
"s": 3586,
"text": "+"
},
{
"code": null,
"e": 3743,
"s": 3588,
"text": "Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign."
},
{
"code": null,
"e": 3751,
"s": 3743,
"text": "(space)"
},
{
"code": null,
"e": 3818,
"s": 3751,
"text": "If no sign is written, a blank space is inserted before the value."
},
{
"code": null,
"e": 3820,
"s": 3818,
"text": "#"
},
{
"code": null,
"e": 4203,
"s": 3820,
"text": "Used with o, x or X specifiers. The value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow then no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed."
},
{
"code": null,
"e": 4205,
"s": 4203,
"text": "0"
},
{
"code": null,
"e": 4315,
"s": 4205,
"text": "Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier)."
},
{
"code": null,
"e": 4324,
"s": 4315,
"text": "(number)"
},
{
"code": null,
"e": 4521,
"s": 4324,
"text": "Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger."
},
{
"code": null,
"e": 4523,
"s": 4521,
"text": "*"
},
{
"code": null,
"e": 4665,
"s": 4523,
"text": "The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted."
},
{
"code": null,
"e": 4673,
"s": 4665,
"text": ".number"
},
{
"code": null,
"e": 5498,
"s": 4673,
"text": "For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after the decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed."
},
{
"code": null,
"e": 5501,
"s": 5498,
"text": ".*"
},
{
"code": null,
"e": 5647,
"s": 5501,
"text": "The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted."
},
{
"code": null,
"e": 5649,
"s": 5647,
"text": "h"
},
{
"code": null,
"e": 5773,
"s": 5649,
"text": "The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X)."
},
{
"code": null,
"e": 5775,
"s": 5773,
"text": "l"
},
{
"code": null,
"e": 5957,
"s": 5775,
"text": "The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s."
},
{
"code": null,
"e": 5959,
"s": 5957,
"text": "L"
},
{
"code": null,
"e": 6067,
"s": 5959,
"text": "The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G)."
},
{
"code": null,
"e": 6384,
"s": 6067,
"text": "additional arguments − Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value."
},
{
"code": null,
"e": 6701,
"s": 6384,
"text": "additional arguments − Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value."
},
{
"code": null,
"e": 6809,
"s": 6701,
"text": "If successful, the total number of characters written is returned otherwise, a negative number is returned."
},
{
"code": null,
"e": 6870,
"s": 6809,
"text": "The following example shows the usage of fprintf() function."
},
{
"code": null,
"e": 7068,
"s": 6870,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main () {\n FILE * fp;\n\n fp = fopen (\"file.txt\", \"w+\");\n fprintf(fp, \"%s %s %s %d\", \"We\", \"are\", \"in\", 2012);\n \n fclose(fp);\n \n return(0);\n}"
},
{
"code": null,
"e": 7171,
"s": 7068,
"text": "Let us compile and run the above program that will create a file file.txt with the following content −"
},
{
"code": null,
"e": 7187,
"s": 7171,
"text": "We are in 2012\n"
},
{
"code": null,
"e": 7261,
"s": 7187,
"text": "Now let's see the content of the above file using the following program −"
},
{
"code": null,
"e": 7491,
"s": 7261,
"text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int c;\n\n fp = fopen(\"file.txt\",\"r\");\n while(1) {\n c = fgetc(fp);\n if( feof(fp) ) {\n break;\n }\n printf(\"%c\", c);\n }\n fclose(fp);\n return(0);\n}"
},
{
"code": null,
"e": 7561,
"s": 7491,
"text": "Let us compile and run above program to produce the following result."
},
{
"code": null,
"e": 7577,
"s": 7561,
"text": "We are in 2012\n"
},
{
"code": null,
"e": 7610,
"s": 7577,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7625,
"s": 7610,
"text": " Nishant Malik"
},
{
"code": null,
"e": 7660,
"s": 7625,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7675,
"s": 7660,
"text": " Nishant Malik"
},
{
"code": null,
"e": 7710,
"s": 7675,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7724,
"s": 7710,
"text": " Asif Hussain"
},
{
"code": null,
"e": 7757,
"s": 7724,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7775,
"s": 7757,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 7810,
"s": 7775,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7829,
"s": 7810,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 7862,
"s": 7829,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7874,
"s": 7862,
"text": " Amit Diwan"
},
{
"code": null,
"e": 7881,
"s": 7874,
"text": " Print"
},
{
"code": null,
"e": 7892,
"s": 7881,
"text": " Add Notes"
}
] |
Natural Language Processing Using Stanford’s CoreNLP | by Lukas Frei | Towards Data Science | Analyzing text data using Stanford’s CoreNLP makes text data analysis easy and efficient. With just a few lines of code, CoreNLP allows for the extraction of all kinds of text properties, such as named-entity recognition or part-of-speech tagging. CoreNLP is written in Java and requires Java to be installed on your device but offers programming interfaces for several popular programming languages, including Python, which I will be using in this demonstration. Additionally, it supports four languages other than English: Arabic, Chinese, German, French, and Spanish.
First, we have to download CoreNLP. If you’re using a MacBook, open the terminal and enter the following line of code and hit enter:
wget https://nlp.stanford.edu/software/stanford-corenlp-full-2018-10-05.zip https://nlp.stanford.edu/software/stanford-english-corenlp-2018-10-05-models.jar
This will start the download of CoreNLP’s latest version (3.9.2 as of February 2019). You should see something like this on your screen:
Downloading CoreNLP will take a while depending on your internet connection. When the download is complete, all that’s left is unzipping the file with the following commands:
unzip stanford-corenlp-full-2018-10-05.zipmv stanford-english-corenlp-2018-10-05-models.jar stanford-corenlp-full-2018-10-05
The command mv A B moves file A to folder B or alternatively changes the filename from A to B.
In order to be able to use CoreNLP, you will have to start the server. Doing so is pretty easy as all you have to do is to move into the folder created in step I and use Java to run CoreNLP. Let’s look at the commands we need for that:
cd stanford-corenlp-full-2018-10-05java -mx6g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -timeout 5000
The cd command opens the folder we created. Then, to run the server, we use Java. The parameter -mx6g specifies the amount of memory that CoreNLP is allowed to use. In this case, it’s six gigabytes. The -timeout 5000 parameter specifies the timeout in milliseconds.
Now, you should see something like this:
The number I’ve highlighted is going to be important when using CoreNLP in Python.
The last thing needed before starting to analyze text is to install a Python API:
pip install pycorenlp
I’m going to use py-corenlp but there are other Python packages that you can check out here. If you should happen to be an avid user of NLTK, there is also an API for NLTK that lets you use CoreNLP. The full instructions can be found here.
After having finished installing CoreNLP, we can finally start analyzing text data in Python. First, let’s import py-corenlp and initialize CoreNLP. This is where the number I highlighted above comes into play:
from pycorenlp import StanfordCoreNLPnlp = StanfordCoreNLP('http://localhost:9000')
The syntax in NLTK is very similar:
from nltk.parse import CoreNLPParserresult = CoreNLPParser(url='http://localhost:9000')
The rest of this demonstration is going to focus on py-corenlp but you could also use NLTK as pointed out above. The main difference between the two is that in py-corenlp outputs a raw JSON file that you can then use to extract whatever you’re specifically interested in while NLTK provides you with functions that do so for you.
The only other function needed to conduct NLP using py-corenlp isnlp.annotate() . Inside the function, one can specify what kind of analysis CoreNLP should execute. In this demonstration, I will take a look at four different sentences with different sentiments. All of this can be done in one single line of code but for readability purposes, it’s better to stretch it over several lines.
text = "This movie was actually neither that funny, nor super witty. The movie was meh. I liked watching that movie. If I had a choice, I would not watch that movie again."result = nlp.annotate(text, properties={ 'annotators': 'sentiment, ner, pos', 'outputFormat': 'json', 'timeout': 1000, })
The annotators parameter specifies what kind of analyses CoreNLP is going to do. In this case, I’ve specified that I want CoreNLP to do sentiment analysis as well as named-entity recognition and part-of-speech tagging. The JSON output format will allow me to easily index into the results for further analysis.
Sentiment analysis with CoreNLP is very straightforward. After having run the code chunk above, no further computation is needed. Let’s look at the results for the four sentences defined above:
for s in result["sentences"]: print("{}: '{}': {} (Sentiment Value) {} (Sentiment)".format( s["index"], " ".join([t["word"] for t in s["tokens"]]), s["sentimentValue"], s["sentiment"]))
Running this for-loop outputs the results of the sentiment analysis:
0: 'This movie was actually neither that funny , nor super witty.': 1 (Sentiment Value) Negative (Sentiment)1: 'The movie was meh.': 2 (Sentiment Value) Neutral (Sentiment)2: 'I liked watching that movie.': 3 (Sentiment Value) Positive (Sentiment)3: 'If I had a choice , I would not watch that movie again.': 1 (Sentiment Value) Negative (Sentiment)
The scale for sentiment values ranges from zero to four. Zero means that the sentence is very negative while four means it’s extremely positive. As you can see, CoreNLP did a very good job. The first sentence is tricky since it includes positive words like ‘funny’ or ‘witty’, however, CoreNLP correctly realized that they are negated. The easier sentences were classified correctly too.
Another option when trying to understand these classifications is to take a look at the sentiment distribution that again ranges from zero to four. Let’s take a look at the sentiment distribution of sentence two:
As you can see, the distribution peaks around a sentiment value of two and can thus be classified as neutral.
Part-of-speech tagging, just like sentiment analysis does not require any additional computation. In a similar fashion to the code chunk above, all that’s needed to retrieve the desired information is a for-loop:
pos = []for word in result["sentences"][2]["tokens"]: pos.append('{} ({})'.format(word["word"], word["pos"])) " ".join(pos)
Running the code returns the following:
'I (PRP) liked (VBD) watching (VBG) that (IN) movie (NN) . (.)'
The abbreviations in parentheses represent the POS tags and follow the Penn Treebank POS tagset, which you can find here. To give you an intuition, PRP stands for personal pronoun, VBD for a verb in past tense, and NN for a noun.
Another possible use of CoreNLP is named-entity recognition. Let’s create a new sentence in order for named-entity recognition to make more sense:
“The earphones Jim bought for Jessica while strolling through the Apple store at the airport in Chicago, USA, were great.”
Again, all we need to do is define a for-loop:
pos = []for word in result["sentences"][1]['tokens']: pos.append('{} ({})'.format(word['word'], word['ner'])) " ".join(pos)
Running the code above gives us the following result:
'The (O) earphones (O) Jim (PERSON) bought (O) for (O) Jessica (PERSON) while (O) strolling (O) through (O) the (O) Apple (ORGANIZATION) store (O) at (O) the (O) airport (O) in (O) Chicago (CITY) , (O) USA (COUNTRY) , (O) was (O) meh (O) . (O)'
As we can see, CoreNLP has correctly identified that Jim and Jessica are people, Apple is an organization, Chicago is a city, and the United States is a country.
Before explaining how to shut down the server, I’d like to point out that CoreNLP provides many other functionalities (lemmatization, stemming, tokenization, etc.) that can all be accessed without having to run any additional computations. A complete list of all parameters for nlp.annotate() can be found here.
If you would like to shut down the server, navigate to the terminal window you used to start the server earlier and press Ctrl + C .
To summarize, CoreNLP’s efficiency is what makes it so convenient. You only have to specify what analysis you’re interested in once and avoid unnecessary computations that might slow you down when working with larger data sets. If you’d like to know more about the details of how CoreNLP works and what options there are, I’d recommend reading the documentation.
References:
[1] Manning, Christopher D., Mihai Surdeanu, John Bauer, Jenny Finkel, Steven J. Bethard, and David McClosky, The Stanford CoreNLP Natural Language Processing Toolkit (2014), Proceedings of the 52nd Annual Meeting of the Association for Computational Linguistics: System Demonstrations, pp. 55–60
[2] Taylor A., Marcus M., Santorini B., The Penn Treebank: An Overview (2003), Text, Speech and Language Technology, vol 20 | [
{
"code": null,
"e": 742,
"s": 171,
"text": "Analyzing text data using Stanford’s CoreNLP makes text data analysis easy and efficient. With just a few lines of code, CoreNLP allows for the extraction of all kinds of text properties, such as named-entity recognition or part-of-speech tagging. CoreNLP is written in Java and requires Java to be installed on your device but offers programming interfaces for several popular programming languages, including Python, which I will be using in this demonstration. Additionally, it supports four languages other than English: Arabic, Chinese, German, French, and Spanish."
},
{
"code": null,
"e": 875,
"s": 742,
"text": "First, we have to download CoreNLP. If you’re using a MacBook, open the terminal and enter the following line of code and hit enter:"
},
{
"code": null,
"e": 1032,
"s": 875,
"text": "wget https://nlp.stanford.edu/software/stanford-corenlp-full-2018-10-05.zip https://nlp.stanford.edu/software/stanford-english-corenlp-2018-10-05-models.jar"
},
{
"code": null,
"e": 1169,
"s": 1032,
"text": "This will start the download of CoreNLP’s latest version (3.9.2 as of February 2019). You should see something like this on your screen:"
},
{
"code": null,
"e": 1344,
"s": 1169,
"text": "Downloading CoreNLP will take a while depending on your internet connection. When the download is complete, all that’s left is unzipping the file with the following commands:"
},
{
"code": null,
"e": 1469,
"s": 1344,
"text": "unzip stanford-corenlp-full-2018-10-05.zipmv stanford-english-corenlp-2018-10-05-models.jar stanford-corenlp-full-2018-10-05"
},
{
"code": null,
"e": 1564,
"s": 1469,
"text": "The command mv A B moves file A to folder B or alternatively changes the filename from A to B."
},
{
"code": null,
"e": 1800,
"s": 1564,
"text": "In order to be able to use CoreNLP, you will have to start the server. Doing so is pretty easy as all you have to do is to move into the folder created in step I and use Java to run CoreNLP. Let’s look at the commands we need for that:"
},
{
"code": null,
"e": 1916,
"s": 1800,
"text": "cd stanford-corenlp-full-2018-10-05java -mx6g -cp \"*\" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -timeout 5000"
},
{
"code": null,
"e": 2182,
"s": 1916,
"text": "The cd command opens the folder we created. Then, to run the server, we use Java. The parameter -mx6g specifies the amount of memory that CoreNLP is allowed to use. In this case, it’s six gigabytes. The -timeout 5000 parameter specifies the timeout in milliseconds."
},
{
"code": null,
"e": 2223,
"s": 2182,
"text": "Now, you should see something like this:"
},
{
"code": null,
"e": 2306,
"s": 2223,
"text": "The number I’ve highlighted is going to be important when using CoreNLP in Python."
},
{
"code": null,
"e": 2388,
"s": 2306,
"text": "The last thing needed before starting to analyze text is to install a Python API:"
},
{
"code": null,
"e": 2410,
"s": 2388,
"text": "pip install pycorenlp"
},
{
"code": null,
"e": 2650,
"s": 2410,
"text": "I’m going to use py-corenlp but there are other Python packages that you can check out here. If you should happen to be an avid user of NLTK, there is also an API for NLTK that lets you use CoreNLP. The full instructions can be found here."
},
{
"code": null,
"e": 2861,
"s": 2650,
"text": "After having finished installing CoreNLP, we can finally start analyzing text data in Python. First, let’s import py-corenlp and initialize CoreNLP. This is where the number I highlighted above comes into play:"
},
{
"code": null,
"e": 2945,
"s": 2861,
"text": "from pycorenlp import StanfordCoreNLPnlp = StanfordCoreNLP('http://localhost:9000')"
},
{
"code": null,
"e": 2981,
"s": 2945,
"text": "The syntax in NLTK is very similar:"
},
{
"code": null,
"e": 3069,
"s": 2981,
"text": "from nltk.parse import CoreNLPParserresult = CoreNLPParser(url='http://localhost:9000')"
},
{
"code": null,
"e": 3399,
"s": 3069,
"text": "The rest of this demonstration is going to focus on py-corenlp but you could also use NLTK as pointed out above. The main difference between the two is that in py-corenlp outputs a raw JSON file that you can then use to extract whatever you’re specifically interested in while NLTK provides you with functions that do so for you."
},
{
"code": null,
"e": 3788,
"s": 3399,
"text": "The only other function needed to conduct NLP using py-corenlp isnlp.annotate() . Inside the function, one can specify what kind of analysis CoreNLP should execute. In this demonstration, I will take a look at four different sentences with different sentiments. All of this can be done in one single line of code but for readability purposes, it’s better to stretch it over several lines."
},
{
"code": null,
"e": 4184,
"s": 3788,
"text": "text = \"This movie was actually neither that funny, nor super witty. The movie was meh. I liked watching that movie. If I had a choice, I would not watch that movie again.\"result = nlp.annotate(text, properties={ 'annotators': 'sentiment, ner, pos', 'outputFormat': 'json', 'timeout': 1000, })"
},
{
"code": null,
"e": 4495,
"s": 4184,
"text": "The annotators parameter specifies what kind of analyses CoreNLP is going to do. In this case, I’ve specified that I want CoreNLP to do sentiment analysis as well as named-entity recognition and part-of-speech tagging. The JSON output format will allow me to easily index into the results for further analysis."
},
{
"code": null,
"e": 4689,
"s": 4495,
"text": "Sentiment analysis with CoreNLP is very straightforward. After having run the code chunk above, no further computation is needed. Let’s look at the results for the four sentences defined above:"
},
{
"code": null,
"e": 4899,
"s": 4689,
"text": "for s in result[\"sentences\"]: print(\"{}: '{}': {} (Sentiment Value) {} (Sentiment)\".format( s[\"index\"], \" \".join([t[\"word\"] for t in s[\"tokens\"]]), s[\"sentimentValue\"], s[\"sentiment\"]))"
},
{
"code": null,
"e": 4968,
"s": 4899,
"text": "Running this for-loop outputs the results of the sentiment analysis:"
},
{
"code": null,
"e": 5318,
"s": 4968,
"text": "0: 'This movie was actually neither that funny , nor super witty.': 1 (Sentiment Value) Negative (Sentiment)1: 'The movie was meh.': 2 (Sentiment Value) Neutral (Sentiment)2: 'I liked watching that movie.': 3 (Sentiment Value) Positive (Sentiment)3: 'If I had a choice , I would not watch that movie again.': 1 (Sentiment Value) Negative (Sentiment)"
},
{
"code": null,
"e": 5706,
"s": 5318,
"text": "The scale for sentiment values ranges from zero to four. Zero means that the sentence is very negative while four means it’s extremely positive. As you can see, CoreNLP did a very good job. The first sentence is tricky since it includes positive words like ‘funny’ or ‘witty’, however, CoreNLP correctly realized that they are negated. The easier sentences were classified correctly too."
},
{
"code": null,
"e": 5919,
"s": 5706,
"text": "Another option when trying to understand these classifications is to take a look at the sentiment distribution that again ranges from zero to four. Let’s take a look at the sentiment distribution of sentence two:"
},
{
"code": null,
"e": 6029,
"s": 5919,
"text": "As you can see, the distribution peaks around a sentiment value of two and can thus be classified as neutral."
},
{
"code": null,
"e": 6242,
"s": 6029,
"text": "Part-of-speech tagging, just like sentiment analysis does not require any additional computation. In a similar fashion to the code chunk above, all that’s needed to retrieve the desired information is a for-loop:"
},
{
"code": null,
"e": 6372,
"s": 6242,
"text": "pos = []for word in result[\"sentences\"][2][\"tokens\"]: pos.append('{} ({})'.format(word[\"word\"], word[\"pos\"])) \" \".join(pos)"
},
{
"code": null,
"e": 6412,
"s": 6372,
"text": "Running the code returns the following:"
},
{
"code": null,
"e": 6476,
"s": 6412,
"text": "'I (PRP) liked (VBD) watching (VBG) that (IN) movie (NN) . (.)'"
},
{
"code": null,
"e": 6706,
"s": 6476,
"text": "The abbreviations in parentheses represent the POS tags and follow the Penn Treebank POS tagset, which you can find here. To give you an intuition, PRP stands for personal pronoun, VBD for a verb in past tense, and NN for a noun."
},
{
"code": null,
"e": 6853,
"s": 6706,
"text": "Another possible use of CoreNLP is named-entity recognition. Let’s create a new sentence in order for named-entity recognition to make more sense:"
},
{
"code": null,
"e": 6976,
"s": 6853,
"text": "“The earphones Jim bought for Jessica while strolling through the Apple store at the airport in Chicago, USA, were great.”"
},
{
"code": null,
"e": 7023,
"s": 6976,
"text": "Again, all we need to do is define a for-loop:"
},
{
"code": null,
"e": 7153,
"s": 7023,
"text": "pos = []for word in result[\"sentences\"][1]['tokens']: pos.append('{} ({})'.format(word['word'], word['ner'])) \" \".join(pos)"
},
{
"code": null,
"e": 7207,
"s": 7153,
"text": "Running the code above gives us the following result:"
},
{
"code": null,
"e": 7452,
"s": 7207,
"text": "'The (O) earphones (O) Jim (PERSON) bought (O) for (O) Jessica (PERSON) while (O) strolling (O) through (O) the (O) Apple (ORGANIZATION) store (O) at (O) the (O) airport (O) in (O) Chicago (CITY) , (O) USA (COUNTRY) , (O) was (O) meh (O) . (O)'"
},
{
"code": null,
"e": 7614,
"s": 7452,
"text": "As we can see, CoreNLP has correctly identified that Jim and Jessica are people, Apple is an organization, Chicago is a city, and the United States is a country."
},
{
"code": null,
"e": 7926,
"s": 7614,
"text": "Before explaining how to shut down the server, I’d like to point out that CoreNLP provides many other functionalities (lemmatization, stemming, tokenization, etc.) that can all be accessed without having to run any additional computations. A complete list of all parameters for nlp.annotate() can be found here."
},
{
"code": null,
"e": 8059,
"s": 7926,
"text": "If you would like to shut down the server, navigate to the terminal window you used to start the server earlier and press Ctrl + C ."
},
{
"code": null,
"e": 8422,
"s": 8059,
"text": "To summarize, CoreNLP’s efficiency is what makes it so convenient. You only have to specify what analysis you’re interested in once and avoid unnecessary computations that might slow you down when working with larger data sets. If you’d like to know more about the details of how CoreNLP works and what options there are, I’d recommend reading the documentation."
},
{
"code": null,
"e": 8434,
"s": 8422,
"text": "References:"
},
{
"code": null,
"e": 8731,
"s": 8434,
"text": "[1] Manning, Christopher D., Mihai Surdeanu, John Bauer, Jenny Finkel, Steven J. Bethard, and David McClosky, The Stanford CoreNLP Natural Language Processing Toolkit (2014), Proceedings of the 52nd Annual Meeting of the Association for Computational Linguistics: System Demonstrations, pp. 55–60"
}
] |
HTML Styles | Style sheets describe how documents are presented on screens, in print, or perhaps how they are pronounced. W3C has actively promoted the use of style sheets on the Web since the Consortium was founded in 1994.
Cascading Style Sheets (CSS) is a style sheet mechanism that has been specifically developed to meet the needs of Web designers and users.
With CSS, you can specify a number of style properties for a given HTML element. Each property has a name and a value, separated by a colon (:). Each property declaration is separated by a semi-colon (;).
This will produce following result:
Using Style Sheet Rules
There are three ways of using a style sheet in an HTML document:
If you have to give same look and feel to many pages then it is a good idea to keep all the style sheet rules in a single style sheet file and include this file in all the HTML pages. You can incluse a style sheet file into HTML document using <link> element. Below is an example:
<head>
<link rel="stylesheet" type="text/css"
href="yourstyle.css">
</head>
If you want to apply Style Sheet rules to a single document only then you can include those rules into that document only. Below is an example:
<head>
<style type="text/css">
body{background-color: pink;}
p{color:blue; 20px;font-size:24px;}
</style>
</head>
To become more comfortable - Do Online Practice
You can apply style sheet rules directly to any HTML element. This should be done only when you are interested to make a particular change in any HTML element only. To use inline styles you use the style attribute in the relevant tag. Below is an example:
This will produce following result:
Using Style Sheet Rules
Advertisements
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2585,
"s": 2374,
"text": "Style sheets describe how documents are presented on screens, in print, or perhaps how they are pronounced. W3C has actively promoted the use of style sheets on the Web since the Consortium was founded in 1994."
},
{
"code": null,
"e": 2724,
"s": 2585,
"text": "Cascading Style Sheets (CSS) is a style sheet mechanism that has been specifically developed to meet the needs of Web designers and users."
},
{
"code": null,
"e": 2929,
"s": 2724,
"text": "With CSS, you can specify a number of style properties for a given HTML element. Each property has a name and a value, separated by a colon (:). Each property declaration is separated by a semi-colon (;)."
},
{
"code": null,
"e": 2965,
"s": 2929,
"text": "This will produce following result:"
},
{
"code": null,
"e": 2989,
"s": 2965,
"text": "Using Style Sheet Rules"
},
{
"code": null,
"e": 3054,
"s": 2989,
"text": "There are three ways of using a style sheet in an HTML document:"
},
{
"code": null,
"e": 3335,
"s": 3054,
"text": "If you have to give same look and feel to many pages then it is a good idea to keep all the style sheet rules in a single style sheet file and include this file in all the HTML pages. You can incluse a style sheet file into HTML document using <link> element. Below is an example:"
},
{
"code": null,
"e": 3412,
"s": 3335,
"text": "<head>\n<link rel=\"stylesheet\" type=\"text/css\"\nhref=\"yourstyle.css\">\n</head>\n"
},
{
"code": null,
"e": 3556,
"s": 3412,
"text": "If you want to apply Style Sheet rules to a single document only then you can include those rules into that document only. Below is an example:"
},
{
"code": null,
"e": 3671,
"s": 3556,
"text": "<head>\n<style type=\"text/css\">\nbody{background-color: pink;}\np{color:blue; 20px;font-size:24px;}\n</style>\n</head>\n"
},
{
"code": null,
"e": 3720,
"s": 3671,
"text": "To become more comfortable - Do Online Practice"
},
{
"code": null,
"e": 3976,
"s": 3720,
"text": "You can apply style sheet rules directly to any HTML element. This should be done only when you are interested to make a particular change in any HTML element only. To use inline styles you use the style attribute in the relevant tag. Below is an example:"
},
{
"code": null,
"e": 4012,
"s": 3976,
"text": "This will produce following result:"
},
{
"code": null,
"e": 4036,
"s": 4012,
"text": "Using Style Sheet Rules"
},
{
"code": null,
"e": 4053,
"s": 4036,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 4086,
"s": 4053,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4100,
"s": 4086,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4135,
"s": 4100,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4149,
"s": 4135,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4184,
"s": 4149,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4201,
"s": 4184,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4236,
"s": 4201,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4267,
"s": 4236,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4300,
"s": 4267,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4331,
"s": 4300,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4366,
"s": 4331,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4397,
"s": 4366,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4404,
"s": 4397,
"text": " Print"
},
{
"code": null,
"e": 4415,
"s": 4404,
"text": " Add Notes"
}
] |
How to find the inverse of a matrix in R? | The inverse of a matrix can be calculated in R with the help of solve function, most of the times people who don’t use R frequently mistakenly use inv function for this purpose but there is no function called inv in base R to find the inverse of a matrix.
Consider the below matrices and their inverses −
> M1<-1:4
> M1<-matrix(1:4,nrow=2)
> M1
[,1] [,2]
[1,] 1 3
[2,] 2 4
> solve(M1)
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
> M2<-matrix(1:4,nrow=2,byrow=TRUE)
> M2
[,1] [,2]
[1,] 1 2
[2,] 3 4
> solve(M2)
[,1] [,2]
[1,] -2.0 1.0
[2,] 1.5 -0.5
> M3<-matrix(c(12,14,16,18,20,22,24,26,28,30,32,34),nrow=3)
> M3
[,1] [,2] [,3] [,4]
[1,] 12 18 24 30
[2,] 14 20 26 32
[3,] 16 22 28 34
> solve(M3)
Error in solve.default(M3) : 'a' (3 x 4) must be square
Here, the function solve is giving an error because the inverse of a non-square matrix cannot be calculated.
> M4<-matrix(c(12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42),nrow=4)
> M4
[,1] [,2] [,3] [,4]
[1,] 12 20 28 36
[2,] 14 22 30 38
[3,] 16 24 32 40
[4,] 18 26 34 42
> solve(M4)
Error in solve.default(M4) :
Lapack routine dgesv: system is exactly singular: U[3,3] = 0
This output is showing an error because the inverse of the matrix M4 does not exists, although it is a square matrix but sometimes even the inverse of a square does not exist.
Let’s have a look at some matrices with higher dimensions that have their inverses −
> M5<-matrix(c(1,8,4,2,4,5,5,1,2,2,5,4,4,1,1,2),nrow=4)
> M5
[,1] [,2] [,3] [,4]
[1,] 1 4 2 4
[2,] 8 5 2 1
[3,] 4 5 5 1
[4,] 2 1 4 2
> solve(M5)
[,1] [,2] [,3] [,4]
[1,] -0.07086614 0.17322835 -0.1417323 0.1259843
[2,] 0.11023622 -0.04724409 0.2204724 -0.3070866
[3,] -0.09448819 -0.10236220 0.1443570 0.1679790
[4,] 0.20472441 0.05511811 -0.2572178 0.1916010
> M6<-matrix(c(2,3,5,4,7,4,5,6,5,2,1,4,5,6,6,2,5,5,4,5,4,7,5,7,3),ncol=5)
> M6
[,1] [,2] [,3] [,4] [,5]
[1,] 2 4 1 2 4
[2,] 3 5 4 5 7
[3,] 5 6 5 5 5
[4,] 4 5 6 4 7
[5,] 7 2 6 5 3
> solve(M6)
[,1] [,2] [,3] [,4] [,5]
[1,] 5.000000e-01 -0.24000000 -0.2200000 1.194481e-16 0.260000000
[2,] 1.457168e-16 -0.20000000 0.4000000 -8.500145e-17 -0.200000000
[3,] -4.285714e-01 -0.12571429 0.1942857 2.857143e-01 -0.125714286
[4,] -3.571429e-01 0.50857143 0.1685714 -4.285714e-01 0.008571429
[5,] 2.857143e-01 0.09714286 -0.4228571 1.428571e-01 0.097142857 | [
{
"code": null,
"e": 1318,
"s": 1062,
"text": "The inverse of a matrix can be calculated in R with the help of solve function, most of the times people who don’t use R frequently mistakenly use inv function for this purpose but there is no function called inv in base R to find the inverse of a matrix."
},
{
"code": null,
"e": 1367,
"s": 1318,
"text": "Consider the below matrices and their inverses −"
},
{
"code": null,
"e": 1844,
"s": 1367,
"text": "> M1<-1:4\n> M1<-matrix(1:4,nrow=2)\n> M1\n [,1] [,2]\n[1,] 1 3\n[2,] 2 4\n> solve(M1)\n [,1] [,2]\n[1,] -2 1.5\n[2,] 1 -0.5\n> M2<-matrix(1:4,nrow=2,byrow=TRUE)\n> M2\n [,1] [,2]\n[1,] 1 2\n[2,] 3 4\n> solve(M2)\n [,1] [,2]\n[1,] -2.0 1.0\n[2,] 1.5 -0.5\n> M3<-matrix(c(12,14,16,18,20,22,24,26,28,30,32,34),nrow=3)\n> M3\n [,1] [,2] [,3] [,4]\n[1,] 12 18 24 30\n[2,] 14 20 26 32\n[3,] 16 22 28 34\n> solve(M3)\nError in solve.default(M3) : 'a' (3 x 4) must be square"
},
{
"code": null,
"e": 1953,
"s": 1844,
"text": "Here, the function solve is giving an error because the inverse of a non-square matrix cannot be calculated."
},
{
"code": null,
"e": 2243,
"s": 1953,
"text": "> M4<-matrix(c(12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42),nrow=4)\n> M4\n [,1] [,2] [,3] [,4]\n[1,] 12 20 28 36\n[2,] 14 22 30 38\n[3,] 16 24 32 40\n[4,] 18 26 34 42\n> solve(M4)\nError in solve.default(M4) :\nLapack routine dgesv: system is exactly singular: U[3,3] = 0"
},
{
"code": null,
"e": 2419,
"s": 2243,
"text": "This output is showing an error because the inverse of the matrix M4 does not exists, although it is a square matrix but sometimes even the inverse of a square does not exist."
},
{
"code": null,
"e": 2504,
"s": 2419,
"text": "Let’s have a look at some matrices with higher dimensions that have their inverses −"
},
{
"code": null,
"e": 3598,
"s": 2504,
"text": "> M5<-matrix(c(1,8,4,2,4,5,5,1,2,2,5,4,4,1,1,2),nrow=4)\n> M5\n [,1] [,2] [,3] [,4]\n[1,] 1 4 2 4\n[2,] 8 5 2 1\n[3,] 4 5 5 1\n[4,] 2 1 4 2\n> solve(M5)\n [,1] [,2] [,3] [,4]\n[1,] -0.07086614 0.17322835 -0.1417323 0.1259843\n[2,] 0.11023622 -0.04724409 0.2204724 -0.3070866\n[3,] -0.09448819 -0.10236220 0.1443570 0.1679790\n[4,] 0.20472441 0.05511811 -0.2572178 0.1916010\n> M6<-matrix(c(2,3,5,4,7,4,5,6,5,2,1,4,5,6,6,2,5,5,4,5,4,7,5,7,3),ncol=5)\n> M6\n [,1] [,2] [,3] [,4] [,5]\n[1,] 2 4 1 2 4\n[2,] 3 5 4 5 7\n[3,] 5 6 5 5 5\n[4,] 4 5 6 4 7\n[5,] 7 2 6 5 3\n> solve(M6)\n [,1] [,2] [,3] [,4] [,5]\n[1,] 5.000000e-01 -0.24000000 -0.2200000 1.194481e-16 0.260000000\n[2,] 1.457168e-16 -0.20000000 0.4000000 -8.500145e-17 -0.200000000\n[3,] -4.285714e-01 -0.12571429 0.1942857 2.857143e-01 -0.125714286\n[4,] -3.571429e-01 0.50857143 0.1685714 -4.285714e-01 0.008571429\n[5,] 2.857143e-01 0.09714286 -0.4228571 1.428571e-01 0.097142857"
}
] |
Octree | Insertion and Searching - GeeksforGeeks | 25 Mar, 2022
Octree is a tree data structure in which each internal node can have at most 8 children. Like Binary tree which divides the space two segments, Octree divides the space into at most eight-part which is called as octanes. It is used to store the 3-D point which takes a large amount of space. if all the internal node of the Octree contains exactly 8 children is called full Octree. It is also useful for high-resolution graphics like 3D computer graphics.
The Octree can be formed form 3D volume by doing the following steps:
Divide the current 3D volume into eight boxesIf any box has more than one point then divide it further into boxesDo not divide the box which has one or zero points in itDo this process repeatedly util all the box contains one or zero point in it
Divide the current 3D volume into eight boxes
If any box has more than one point then divide it further into boxes
Do not divide the box which has one or zero points in it
Do this process repeatedly util all the box contains one or zero point in it
The above steps are shown in figure.
If S is the number of points in each dimension then the number of nodes that are formed in Octree is given by this formula .
To insert a node in Octree, first of all, we check if a node exists or not if a node exists then return otherwise we go recursively
First, we start with the root node and mark it as current
Then we find the child node in which we can store the point
If the node is empty the replace with the node we want to insert and make it a leaf node
If the node is the leaf node then make it an internal node and if it is an internal node then go to the child node. do this process recursively till an empty node is not found
The time complexity of this function is where N is the number of nodes
This function is used to search the point exist is the tree or not
Start with the root node and search recursively if the node with given point found then return true if an empty node or boundary point or empty point is encountered then return false
If an internal node is found go that node. The time complexity of this function is also O(Log N) where N is the number of nodes
Below is the implementation of the above approach
CPP14
// Implementation of Octree in c++#include <iostream>#include <vector>using namespace std; #define TopLeftFront 0#define TopRightFront 1#define BottomRightFront 2#define BottomLeftFront 3#define TopLeftBottom 4#define TopRightBottom 5#define BottomRightBack 6#define BottomLeftBack 7 // Structure of a pointstruct Point { int x; int y; int z; Point() : x(-1), y(-1), z(-1) { } Point(int a, int b, int c) : x(a), y(b), z(c) { }}; // Octree classclass Octree { // if point == NULL, node is internal node. // if point == (-1, -1, -1), node is empty. Point* point; // Represent the boundary of the cube Point *topLeftFront, *bottomRightBack; vector<Octree*> children; public: // Constructor Octree() { // To declare empty node point = new Point(); } // Constructor with three arguments Octree(int x, int y, int z) { // To declare point node point = new Point(x, y, z); } // Constructor with six arguments Octree(int x1, int y1, int z1, int x2, int y2, int z2) { // This use to construct Octree // with boundaries defined if (x2 < x1 || y2 < y1 || z2 < z1) { cout << "boundary points are not valid" << endl; return; } point = nullptr; topLeftFront = new Point(x1, y1, z1); bottomRightBack = new Point(x2, y2, z2); // Assigning null to the children children.assign(8, nullptr); for (int i = TopLeftFront; i <= BottomLeftBack; ++i) children[i] = new Octree(); } // Function to insert a point in the octree void insert(int x, int y, int z) { // If the point already exists in the octree if (find(x, y, z)) { cout << "Point already exist in the tree" << endl; return; } // If the point is out of bounds if (x < topLeftFront->x || x > bottomRightBack->x || y < topLeftFront->y || y > bottomRightBack->y || z < topLeftFront->z || z > bottomRightBack->z) { cout << "Point is out of bound" << endl; return; } // Binary search to insert the point int midx = (topLeftFront->x + bottomRightBack->x) / 2; int midy = (topLeftFront->y + bottomRightBack->y) / 2; int midz = (topLeftFront->z + bottomRightBack->z) / 2; int pos = -1; // Checking the octant of // the point if (x <= midx) { if (y <= midy) { if (z <= midz) pos = TopLeftFront; else pos = TopLeftBottom; } else { if (z <= midz) pos = BottomLeftFront; else pos = BottomLeftBack; } } else { if (y <= midy) { if (z <= midz) pos = TopRightFront; else pos = TopRightBottom; } else { if (z <= midz) pos = BottomRightFront; else pos = BottomRightBack; } } // If an internal node is encountered if (children[pos]->point == nullptr) { children[pos]->insert(x, y, z); return; } // If an empty node is encountered else if (children[pos]->point->x == -1) { delete children[pos]; children[pos] = new Octree(x, y, z); return; } else { int x_ = children[pos]->point->x, y_ = children[pos]->point->y, z_ = children[pos]->point->z; delete children[pos]; children[pos] = nullptr; if (pos == TopLeftFront) { children[pos] = new Octree(topLeftFront->x, topLeftFront->y, topLeftFront->z, midx, midy, midz); } else if (pos == TopRightFront) { children[pos] = new Octree(midx + 1, topLeftFront->y, topLeftFront->z, bottomRightBack->x, midy, midz); } else if (pos == BottomRightFront) { children[pos] = new Octree(midx + 1, midy + 1, topLeftFront->z, bottomRightBack->x, bottomRightBack->y, midz); } else if (pos == BottomLeftFront) { children[pos] = new Octree(topLeftFront->x, midy + 1, topLeftFront->z, midx, bottomRightBack->y, midz); } else if (pos == TopLeftBottom) { children[pos] = new Octree(topLeftFront->x, topLeftFront->y, midz + 1, midx, midy, bottomRightBack->z); } else if (pos == TopRightBottom) { children[pos] = new Octree(midx + 1, topLeftFront->y, midz + 1, bottomRightBack->x, midy, bottomRightBack->z); } else if (pos == BottomRightBack) { children[pos] = new Octree(midx + 1, midy + 1, midz + 1, bottomRightBack->x, bottomRightBack->y, bottomRightBack->z); } else if (pos == BottomLeftBack) { children[pos] = new Octree(topLeftFront->x, midy + 1, midz + 1, midx, bottomRightBack->y, bottomRightBack->z); } children[pos]->insert(x_, y_, z_); children[pos]->insert(x, y, z); } } // Function that returns true if the point // (x, y, z) exists in the octree bool find(int x, int y, int z) { // If point is out of bound if (x < topLeftFront->x || x > bottomRightBack->x || y < topLeftFront->y || y > bottomRightBack->y || z < topLeftFront->z || z > bottomRightBack->z) return 0; // Otherwise perform binary search // for each ordinate int midx = (topLeftFront->x + bottomRightBack->x) / 2; int midy = (topLeftFront->y + bottomRightBack->y) / 2; int midz = (topLeftFront->z + bottomRightBack->z) / 2; int pos = -1; // Deciding the position // where to move if (x <= midx) { if (y <= midy) { if (z <= midz) pos = TopLeftFront; else pos = TopLeftBottom; } else { if (z <= midz) pos = BottomLeftFront; else pos = BottomLeftBack; } } else { if (y <= midy) { if (z <= midz) pos = TopRightFront; else pos = TopRightBottom; } else { if (z <= midz) pos = BottomRightFront; else pos = BottomRightBack; } } // If an internal node is encountered if (children[pos]->point == nullptr) { return children[pos]->find(x, y, z); } // If an empty node is encountered else if (children[pos]->point->x == -1) { return 0; } else { // If node is found with // the given value if (x == children[pos]->point->x && y == children[pos]->point->y && z == children[pos]->point->z) return 1; } return 0; }}; // Driver codeint main(){ Octree tree(1, 1, 1, 5, 5, 5); tree.insert(1, 2, 3); tree.insert(1, 2, 3); tree.insert(6, 5, 5); cout << (tree.find(1, 2, 3) ? "Found\n" : "Not Found\n"); cout << (tree.find(3, 4, 4) ? "Found\n" : "Not Found\n"); tree.insert(3, 4, 4); cout << (tree.find(3, 4, 4) ? "Found\n" : "Not Found\n"); return 0;}
Point already exist in the tree
Point is out of bound
found
not found
found
It is used in 3D computer graphics gamesIt is also used to find nearest neighboring objects in 3D spaceIt is also used for color quantization
It is used in 3D computer graphics games
It is also used to find nearest neighboring objects in 3D space
It is also used for color quantization
surindertarika1234
sumitgumber28
Octree
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Segment Tree | Set 1 (Sum of given range)
Disjoint Set Data Structures
Insert Operation in B-Tree
How to design a tiny URL or URL shortener?
Design a Chess Game | [
{
"code": null,
"e": 24711,
"s": 24683,
"text": "\n25 Mar, 2022"
},
{
"code": null,
"e": 25167,
"s": 24711,
"text": "Octree is a tree data structure in which each internal node can have at most 8 children. Like Binary tree which divides the space two segments, Octree divides the space into at most eight-part which is called as octanes. It is used to store the 3-D point which takes a large amount of space. if all the internal node of the Octree contains exactly 8 children is called full Octree. It is also useful for high-resolution graphics like 3D computer graphics."
},
{
"code": null,
"e": 25239,
"s": 25167,
"text": "The Octree can be formed form 3D volume by doing the following steps: "
},
{
"code": null,
"e": 25485,
"s": 25239,
"text": "Divide the current 3D volume into eight boxesIf any box has more than one point then divide it further into boxesDo not divide the box which has one or zero points in itDo this process repeatedly util all the box contains one or zero point in it"
},
{
"code": null,
"e": 25531,
"s": 25485,
"text": "Divide the current 3D volume into eight boxes"
},
{
"code": null,
"e": 25600,
"s": 25531,
"text": "If any box has more than one point then divide it further into boxes"
},
{
"code": null,
"e": 25657,
"s": 25600,
"text": "Do not divide the box which has one or zero points in it"
},
{
"code": null,
"e": 25734,
"s": 25657,
"text": "Do this process repeatedly util all the box contains one or zero point in it"
},
{
"code": null,
"e": 25773,
"s": 25734,
"text": "The above steps are shown in figure. "
},
{
"code": null,
"e": 25900,
"s": 25773,
"text": "If S is the number of points in each dimension then the number of nodes that are formed in Octree is given by this formula . "
},
{
"code": null,
"e": 26034,
"s": 25902,
"text": "To insert a node in Octree, first of all, we check if a node exists or not if a node exists then return otherwise we go recursively"
},
{
"code": null,
"e": 26092,
"s": 26034,
"text": "First, we start with the root node and mark it as current"
},
{
"code": null,
"e": 26152,
"s": 26092,
"text": "Then we find the child node in which we can store the point"
},
{
"code": null,
"e": 26241,
"s": 26152,
"text": "If the node is empty the replace with the node we want to insert and make it a leaf node"
},
{
"code": null,
"e": 26417,
"s": 26241,
"text": "If the node is the leaf node then make it an internal node and if it is an internal node then go to the child node. do this process recursively till an empty node is not found"
},
{
"code": null,
"e": 26488,
"s": 26417,
"text": "The time complexity of this function is where N is the number of nodes"
},
{
"code": null,
"e": 26559,
"s": 26492,
"text": "This function is used to search the point exist is the tree or not"
},
{
"code": null,
"e": 26742,
"s": 26559,
"text": "Start with the root node and search recursively if the node with given point found then return true if an empty node or boundary point or empty point is encountered then return false"
},
{
"code": null,
"e": 26870,
"s": 26742,
"text": "If an internal node is found go that node. The time complexity of this function is also O(Log N) where N is the number of nodes"
},
{
"code": null,
"e": 26921,
"s": 26870,
"text": "Below is the implementation of the above approach "
},
{
"code": null,
"e": 26927,
"s": 26921,
"text": "CPP14"
},
{
"code": "// Implementation of Octree in c++#include <iostream>#include <vector>using namespace std; #define TopLeftFront 0#define TopRightFront 1#define BottomRightFront 2#define BottomLeftFront 3#define TopLeftBottom 4#define TopRightBottom 5#define BottomRightBack 6#define BottomLeftBack 7 // Structure of a pointstruct Point { int x; int y; int z; Point() : x(-1), y(-1), z(-1) { } Point(int a, int b, int c) : x(a), y(b), z(c) { }}; // Octree classclass Octree { // if point == NULL, node is internal node. // if point == (-1, -1, -1), node is empty. Point* point; // Represent the boundary of the cube Point *topLeftFront, *bottomRightBack; vector<Octree*> children; public: // Constructor Octree() { // To declare empty node point = new Point(); } // Constructor with three arguments Octree(int x, int y, int z) { // To declare point node point = new Point(x, y, z); } // Constructor with six arguments Octree(int x1, int y1, int z1, int x2, int y2, int z2) { // This use to construct Octree // with boundaries defined if (x2 < x1 || y2 < y1 || z2 < z1) { cout << \"boundary points are not valid\" << endl; return; } point = nullptr; topLeftFront = new Point(x1, y1, z1); bottomRightBack = new Point(x2, y2, z2); // Assigning null to the children children.assign(8, nullptr); for (int i = TopLeftFront; i <= BottomLeftBack; ++i) children[i] = new Octree(); } // Function to insert a point in the octree void insert(int x, int y, int z) { // If the point already exists in the octree if (find(x, y, z)) { cout << \"Point already exist in the tree\" << endl; return; } // If the point is out of bounds if (x < topLeftFront->x || x > bottomRightBack->x || y < topLeftFront->y || y > bottomRightBack->y || z < topLeftFront->z || z > bottomRightBack->z) { cout << \"Point is out of bound\" << endl; return; } // Binary search to insert the point int midx = (topLeftFront->x + bottomRightBack->x) / 2; int midy = (topLeftFront->y + bottomRightBack->y) / 2; int midz = (topLeftFront->z + bottomRightBack->z) / 2; int pos = -1; // Checking the octant of // the point if (x <= midx) { if (y <= midy) { if (z <= midz) pos = TopLeftFront; else pos = TopLeftBottom; } else { if (z <= midz) pos = BottomLeftFront; else pos = BottomLeftBack; } } else { if (y <= midy) { if (z <= midz) pos = TopRightFront; else pos = TopRightBottom; } else { if (z <= midz) pos = BottomRightFront; else pos = BottomRightBack; } } // If an internal node is encountered if (children[pos]->point == nullptr) { children[pos]->insert(x, y, z); return; } // If an empty node is encountered else if (children[pos]->point->x == -1) { delete children[pos]; children[pos] = new Octree(x, y, z); return; } else { int x_ = children[pos]->point->x, y_ = children[pos]->point->y, z_ = children[pos]->point->z; delete children[pos]; children[pos] = nullptr; if (pos == TopLeftFront) { children[pos] = new Octree(topLeftFront->x, topLeftFront->y, topLeftFront->z, midx, midy, midz); } else if (pos == TopRightFront) { children[pos] = new Octree(midx + 1, topLeftFront->y, topLeftFront->z, bottomRightBack->x, midy, midz); } else if (pos == BottomRightFront) { children[pos] = new Octree(midx + 1, midy + 1, topLeftFront->z, bottomRightBack->x, bottomRightBack->y, midz); } else if (pos == BottomLeftFront) { children[pos] = new Octree(topLeftFront->x, midy + 1, topLeftFront->z, midx, bottomRightBack->y, midz); } else if (pos == TopLeftBottom) { children[pos] = new Octree(topLeftFront->x, topLeftFront->y, midz + 1, midx, midy, bottomRightBack->z); } else if (pos == TopRightBottom) { children[pos] = new Octree(midx + 1, topLeftFront->y, midz + 1, bottomRightBack->x, midy, bottomRightBack->z); } else if (pos == BottomRightBack) { children[pos] = new Octree(midx + 1, midy + 1, midz + 1, bottomRightBack->x, bottomRightBack->y, bottomRightBack->z); } else if (pos == BottomLeftBack) { children[pos] = new Octree(topLeftFront->x, midy + 1, midz + 1, midx, bottomRightBack->y, bottomRightBack->z); } children[pos]->insert(x_, y_, z_); children[pos]->insert(x, y, z); } } // Function that returns true if the point // (x, y, z) exists in the octree bool find(int x, int y, int z) { // If point is out of bound if (x < topLeftFront->x || x > bottomRightBack->x || y < topLeftFront->y || y > bottomRightBack->y || z < topLeftFront->z || z > bottomRightBack->z) return 0; // Otherwise perform binary search // for each ordinate int midx = (topLeftFront->x + bottomRightBack->x) / 2; int midy = (topLeftFront->y + bottomRightBack->y) / 2; int midz = (topLeftFront->z + bottomRightBack->z) / 2; int pos = -1; // Deciding the position // where to move if (x <= midx) { if (y <= midy) { if (z <= midz) pos = TopLeftFront; else pos = TopLeftBottom; } else { if (z <= midz) pos = BottomLeftFront; else pos = BottomLeftBack; } } else { if (y <= midy) { if (z <= midz) pos = TopRightFront; else pos = TopRightBottom; } else { if (z <= midz) pos = BottomRightFront; else pos = BottomRightBack; } } // If an internal node is encountered if (children[pos]->point == nullptr) { return children[pos]->find(x, y, z); } // If an empty node is encountered else if (children[pos]->point->x == -1) { return 0; } else { // If node is found with // the given value if (x == children[pos]->point->x && y == children[pos]->point->y && z == children[pos]->point->z) return 1; } return 0; }}; // Driver codeint main(){ Octree tree(1, 1, 1, 5, 5, 5); tree.insert(1, 2, 3); tree.insert(1, 2, 3); tree.insert(6, 5, 5); cout << (tree.find(1, 2, 3) ? \"Found\\n\" : \"Not Found\\n\"); cout << (tree.find(3, 4, 4) ? \"Found\\n\" : \"Not Found\\n\"); tree.insert(3, 4, 4); cout << (tree.find(3, 4, 4) ? \"Found\\n\" : \"Not Found\\n\"); return 0;}",
"e": 36730,
"s": 26927,
"text": null
},
{
"code": null,
"e": 36806,
"s": 36730,
"text": "Point already exist in the tree\nPoint is out of bound\nfound\nnot found\nfound"
},
{
"code": null,
"e": 36950,
"s": 36808,
"text": "It is used in 3D computer graphics gamesIt is also used to find nearest neighboring objects in 3D spaceIt is also used for color quantization"
},
{
"code": null,
"e": 36991,
"s": 36950,
"text": "It is used in 3D computer graphics games"
},
{
"code": null,
"e": 37055,
"s": 36991,
"text": "It is also used to find nearest neighboring objects in 3D space"
},
{
"code": null,
"e": 37094,
"s": 37055,
"text": "It is also used for color quantization"
},
{
"code": null,
"e": 37113,
"s": 37094,
"text": "surindertarika1234"
},
{
"code": null,
"e": 37127,
"s": 37113,
"text": "sumitgumber28"
},
{
"code": null,
"e": 37134,
"s": 37127,
"text": "Octree"
},
{
"code": null,
"e": 37158,
"s": 37134,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 37256,
"s": 37158,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37265,
"s": 37256,
"text": "Comments"
},
{
"code": null,
"e": 37278,
"s": 37265,
"text": "Old Comments"
},
{
"code": null,
"e": 37312,
"s": 37278,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 37352,
"s": 37312,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 37380,
"s": 37352,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 37412,
"s": 37380,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 37454,
"s": 37412,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 37483,
"s": 37454,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 37510,
"s": 37483,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 37553,
"s": 37510,
"text": "How to design a tiny URL or URL shortener?"
}
] |
Why “1.5” in IQR Method of Outlier Detection? | by Shivam Chaudhary | Towards Data Science | If you can’t explain it to a six year old, you don’t understand it yourself.
The world still awaits the next Einstein, or perhaps it won’t ever get another person of the century. But I like to believe: in the universe and in a variation of the above quote...
The best way to learn is to teach.
The idea for this post came when I was once helping one of my juniors with an assignment on outlier detection. It wasn’t a very complicated one, just an application of IQR Method of Outlier Detection on a dataset. The tutorial took an exciting turn when he asked me:
“Why 1.5 times IQR? Why not 1 or 2 or any other number?”
Now this question won’t ring any bells for those who are not familier with IQR Method of Outlier Detection (explained below), but for those who know how simple this method is, I hope the question above would make you think about it. After all, isn’t that what good data scientists do? Question everything, believe nothing.
In the most general sense, an outlier is a data point which differs significantly from other observations. Now its meaning can be interpreted according to the statistical model under study, but for the sake of simplicity and not to divert too far from the main agenda of this post, we’d consider first order statistics and too on a very simple dataset, without any loss of generality.
To explain IQR Method easily, let’s start with a box plot.
A box plot tells us, more or less, about the distribution of the data. It gives a sense of how much the data is actually spread about, what’s its range, and about its skewness. As you might have noticed in the figure, that a box plot enables us to draw inference from it for an ordered data, i.e., it tells us about the various metrics of a data arranged in ascending order.
In the above figure,
minimum is the minimum value in the dataset,
and maximum is the maximum value in the dataset.
So the difference between the two tells us about the range of dataset.
The median is the median (or centre point), also called second quartile, of the data (resulting from the fact that the data is ordered).
Q1 is the first quartile of the data, i.e., to say 25% of the data lies between minimum and Q1.
Q3 is the third quartile of the data, i.e., to say 75% of the data lies between minimum and Q3.
The difference between Q3 and Q1 is called the Inter-Quartile Range or IQR.
IQR = Q3 - Q1
To detect the outliers using this method, we define a new range, let’s call it decision range, and any data point lying outside this range is considered as outlier and is accordingly dealt with. The range is as given below:
Lower Bound: (Q1 - 1.5 * IQR)Upper Bound: (Q3 + 1.5 * IQR)
Any data point less than the Lower Bound or more than the Upper Bound is considered as an outlier.
But the question was: Why only 1.5 times the IQR? Why not any other number?
Well, as you might have guessed, the number (here 1.5, hereinafter scale) clearly controls the sensitivity of the range and hence the decision rule. A bigger scale would make the outlier(s) to be considered as data point(s) while a smaller one would make some of the data point(s) to be perceived as outlier(s). And we’re quite sure, none of these cases is desirable.
But this is an abstract way of explaining the reason, it’s quite effective, but naive nonetheless. So to what should we turn our heads for hope?
Maths! Of course! (You saw that coming, right? 😐)
Things are gonna get a bit “math-y” from here on after. But I’ll try to keep it minimal.
You might be surprised if I tell you that this number, or scale, depends on the distribution followed by the data.
For example, let’s say our data follows, our beloved, Gaussian Distribution.
You all must have seen how a Gaussian Distribution looks like, right? If not, here it is (although I’m suspicious about you 👊).
There are certain observations which could be inferred from this figure:
About 68.26% of the whole data lies within one standard deviation (<σ) of the mean (μ), taking both sides into account, the pink region in the figure.
About 95.44% of the whole data lies within two standard deviations (2σ) of the mean (μ), taking both sides into account, the pink+blue region in the figure.
About 99.72% of the whole data lies within three standard deviations (<3σ) of the mean (μ), taking both sides into account, the pink+blue+green region in the figure.
And the rest 0.28% of the whole data lies outside three standard deviations (>3σ) of the mean (μ), taking both sides into account, the little red region in the figure. And this part of the data is considered as outliers.
The first and the third quartiles, Q1 and Q3, lies at -0.675σ and +0.675σ from the mean, respectively.
I could have shown you the calculations behind these inferences but that’s beyond the scope of this article. If you wish, you can check these at: cs.uni.edu/~campbell/stat/normfact.html
Lower Bound:= Q1 - 1 * IQR= Q1 - 1 * (Q3 - Q1)= -0.675σ - 1 * (0.675 - [-0.675])σ= -0.675σ - 1 * 1.35σ= -2.025σUpper Bound:= Q3 + 1 * IQR= Q3 + 1 * (Q3 - Q1)= 0.675σ + 1 * (0.675 - [-0.675])σ= 0.675σ + 1 * 1.35σ= 2.025σ
So, when scale is taken as 1, then according to IQR Method any data which lies beyond 2.025σ from the mean (μ), on either side, shall be considered as outlier. But as we know, upto 3σ, on either side of the μ ,the data is useful. So we cannot take scale = 1, because this makes the decision range too exclusive, means this results in too much outliers. In other words, the decision range gets so small (compared to 3σ) that it considers some data points as outliers, which is not desirable.
Lower Bound:= Q1 - 2 * IQR= Q1 - 2 * (Q3 - Q1)= -0.675σ - 2 * (0.675 - [-0.675])σ= -0.675σ - 2 * 1.35σ= -3.375σUpper Bound:= Q3 + 2 * IQR= Q3 + 2 * (Q3 - Q1)= 0.675σ + 2 * (0.675 - [-0.675])σ= 0.675σ + 2 * 1.35σ= 3.375σ
So, when scale is taken as 2, then according to IQR Method any data which lies beyond 3.375σ from the mean (μ), on either side, shall be considered as outlier. But as we know, upto 3σ, on either side of the μ ,the data is useful. So we cannot take scale = 2, because this makes the decision range too inclusive, means this results in too few outliers. In other words, the decision range gets so big (compared to 3σ) that it considers some outliers as data points, which is not desirable either.
Lower Bound:= Q1 - 1.5 * IQR= Q1 - 1.5 * (Q3 - Q1)= -0.675σ - 1.5 * (0.675 - [-0.675])σ= -0.675σ - 1.5 * 1.35σ= -2.7σUpper Bound:= Q3 + 1.5 * IQR= Q3 + 1.5 * (Q3 - Q1)= 0.675σ + 1.5 * (0.675 - [-0.675])σ= 0.675σ + 1.5 * 1.35σ= 2.7σ
When scale is taken as 1.5, then according to IQR Method any data which lies beyond 2.7σ from the mean (μ), on either side, shall be considered as outlier. And this decision range is the closest to what Gaussian Distribution tells us, i.e., 3σ. In other words, this makes the decision rule closest to what Gaussian Distribution considers for outlier detection, and this is exactly what we wanted.
*** Side Note ***
To get exactly 3σ, we need to take the scale = 1.7, but then 1.5 is more “symmetrical” than 1.7 and we’ve always been a little more inclined towards symmetry, aren’t we!?
Also, IQR Method of Outlier Detection is not the only and definitely not the best method for outlier detection, so a bit trade-off is legible and accepted.
See, how beautifully and elegantly it all unfolded using maths. I just love how things become clear and evidently takes shape when perceived through its mathematics. And this is one of the many reasons why maths is the language of our world (not sure about the universe though 😐).
So, I hope, now you know why do we take it 1.5 * IQR. But this scale depends on the distribution followed by the data. Say if my data seem to follow exponential distribution then this scale would change.
But again, every complication which arises because of mathematics is solved by mathematics itself.
Ever heard of Central Limit Theorem? Yep! The very same theorem why grants us the liberty to assume the distribution to be followed as Gaussian without any guilt. But I think I’d leave that for some other day. Until then, be curious!
Hope you found this article useful. Thanks! | [
{
"code": null,
"e": 249,
"s": 172,
"text": "If you can’t explain it to a six year old, you don’t understand it yourself."
},
{
"code": null,
"e": 431,
"s": 249,
"text": "The world still awaits the next Einstein, or perhaps it won’t ever get another person of the century. But I like to believe: in the universe and in a variation of the above quote..."
},
{
"code": null,
"e": 466,
"s": 431,
"text": "The best way to learn is to teach."
},
{
"code": null,
"e": 733,
"s": 466,
"text": "The idea for this post came when I was once helping one of my juniors with an assignment on outlier detection. It wasn’t a very complicated one, just an application of IQR Method of Outlier Detection on a dataset. The tutorial took an exciting turn when he asked me:"
},
{
"code": null,
"e": 790,
"s": 733,
"text": "“Why 1.5 times IQR? Why not 1 or 2 or any other number?”"
},
{
"code": null,
"e": 1113,
"s": 790,
"text": "Now this question won’t ring any bells for those who are not familier with IQR Method of Outlier Detection (explained below), but for those who know how simple this method is, I hope the question above would make you think about it. After all, isn’t that what good data scientists do? Question everything, believe nothing."
},
{
"code": null,
"e": 1498,
"s": 1113,
"text": "In the most general sense, an outlier is a data point which differs significantly from other observations. Now its meaning can be interpreted according to the statistical model under study, but for the sake of simplicity and not to divert too far from the main agenda of this post, we’d consider first order statistics and too on a very simple dataset, without any loss of generality."
},
{
"code": null,
"e": 1557,
"s": 1498,
"text": "To explain IQR Method easily, let’s start with a box plot."
},
{
"code": null,
"e": 1932,
"s": 1557,
"text": "A box plot tells us, more or less, about the distribution of the data. It gives a sense of how much the data is actually spread about, what’s its range, and about its skewness. As you might have noticed in the figure, that a box plot enables us to draw inference from it for an ordered data, i.e., it tells us about the various metrics of a data arranged in ascending order."
},
{
"code": null,
"e": 1953,
"s": 1932,
"text": "In the above figure,"
},
{
"code": null,
"e": 1998,
"s": 1953,
"text": "minimum is the minimum value in the dataset,"
},
{
"code": null,
"e": 2047,
"s": 1998,
"text": "and maximum is the maximum value in the dataset."
},
{
"code": null,
"e": 2118,
"s": 2047,
"text": "So the difference between the two tells us about the range of dataset."
},
{
"code": null,
"e": 2255,
"s": 2118,
"text": "The median is the median (or centre point), also called second quartile, of the data (resulting from the fact that the data is ordered)."
},
{
"code": null,
"e": 2351,
"s": 2255,
"text": "Q1 is the first quartile of the data, i.e., to say 25% of the data lies between minimum and Q1."
},
{
"code": null,
"e": 2447,
"s": 2351,
"text": "Q3 is the third quartile of the data, i.e., to say 75% of the data lies between minimum and Q3."
},
{
"code": null,
"e": 2523,
"s": 2447,
"text": "The difference between Q3 and Q1 is called the Inter-Quartile Range or IQR."
},
{
"code": null,
"e": 2537,
"s": 2523,
"text": "IQR = Q3 - Q1"
},
{
"code": null,
"e": 2761,
"s": 2537,
"text": "To detect the outliers using this method, we define a new range, let’s call it decision range, and any data point lying outside this range is considered as outlier and is accordingly dealt with. The range is as given below:"
},
{
"code": null,
"e": 2820,
"s": 2761,
"text": "Lower Bound: (Q1 - 1.5 * IQR)Upper Bound: (Q3 + 1.5 * IQR)"
},
{
"code": null,
"e": 2919,
"s": 2820,
"text": "Any data point less than the Lower Bound or more than the Upper Bound is considered as an outlier."
},
{
"code": null,
"e": 2995,
"s": 2919,
"text": "But the question was: Why only 1.5 times the IQR? Why not any other number?"
},
{
"code": null,
"e": 3363,
"s": 2995,
"text": "Well, as you might have guessed, the number (here 1.5, hereinafter scale) clearly controls the sensitivity of the range and hence the decision rule. A bigger scale would make the outlier(s) to be considered as data point(s) while a smaller one would make some of the data point(s) to be perceived as outlier(s). And we’re quite sure, none of these cases is desirable."
},
{
"code": null,
"e": 3508,
"s": 3363,
"text": "But this is an abstract way of explaining the reason, it’s quite effective, but naive nonetheless. So to what should we turn our heads for hope?"
},
{
"code": null,
"e": 3558,
"s": 3508,
"text": "Maths! Of course! (You saw that coming, right? 😐)"
},
{
"code": null,
"e": 3647,
"s": 3558,
"text": "Things are gonna get a bit “math-y” from here on after. But I’ll try to keep it minimal."
},
{
"code": null,
"e": 3762,
"s": 3647,
"text": "You might be surprised if I tell you that this number, or scale, depends on the distribution followed by the data."
},
{
"code": null,
"e": 3839,
"s": 3762,
"text": "For example, let’s say our data follows, our beloved, Gaussian Distribution."
},
{
"code": null,
"e": 3967,
"s": 3839,
"text": "You all must have seen how a Gaussian Distribution looks like, right? If not, here it is (although I’m suspicious about you 👊)."
},
{
"code": null,
"e": 4040,
"s": 3967,
"text": "There are certain observations which could be inferred from this figure:"
},
{
"code": null,
"e": 4191,
"s": 4040,
"text": "About 68.26% of the whole data lies within one standard deviation (<σ) of the mean (μ), taking both sides into account, the pink region in the figure."
},
{
"code": null,
"e": 4348,
"s": 4191,
"text": "About 95.44% of the whole data lies within two standard deviations (2σ) of the mean (μ), taking both sides into account, the pink+blue region in the figure."
},
{
"code": null,
"e": 4514,
"s": 4348,
"text": "About 99.72% of the whole data lies within three standard deviations (<3σ) of the mean (μ), taking both sides into account, the pink+blue+green region in the figure."
},
{
"code": null,
"e": 4735,
"s": 4514,
"text": "And the rest 0.28% of the whole data lies outside three standard deviations (>3σ) of the mean (μ), taking both sides into account, the little red region in the figure. And this part of the data is considered as outliers."
},
{
"code": null,
"e": 4838,
"s": 4735,
"text": "The first and the third quartiles, Q1 and Q3, lies at -0.675σ and +0.675σ from the mean, respectively."
},
{
"code": null,
"e": 5024,
"s": 4838,
"text": "I could have shown you the calculations behind these inferences but that’s beyond the scope of this article. If you wish, you can check these at: cs.uni.edu/~campbell/stat/normfact.html"
},
{
"code": null,
"e": 5244,
"s": 5024,
"text": "Lower Bound:= Q1 - 1 * IQR= Q1 - 1 * (Q3 - Q1)= -0.675σ - 1 * (0.675 - [-0.675])σ= -0.675σ - 1 * 1.35σ= -2.025σUpper Bound:= Q3 + 1 * IQR= Q3 + 1 * (Q3 - Q1)= 0.675σ + 1 * (0.675 - [-0.675])σ= 0.675σ + 1 * 1.35σ= 2.025σ"
},
{
"code": null,
"e": 5735,
"s": 5244,
"text": "So, when scale is taken as 1, then according to IQR Method any data which lies beyond 2.025σ from the mean (μ), on either side, shall be considered as outlier. But as we know, upto 3σ, on either side of the μ ,the data is useful. So we cannot take scale = 1, because this makes the decision range too exclusive, means this results in too much outliers. In other words, the decision range gets so small (compared to 3σ) that it considers some data points as outliers, which is not desirable."
},
{
"code": null,
"e": 5955,
"s": 5735,
"text": "Lower Bound:= Q1 - 2 * IQR= Q1 - 2 * (Q3 - Q1)= -0.675σ - 2 * (0.675 - [-0.675])σ= -0.675σ - 2 * 1.35σ= -3.375σUpper Bound:= Q3 + 2 * IQR= Q3 + 2 * (Q3 - Q1)= 0.675σ + 2 * (0.675 - [-0.675])σ= 0.675σ + 2 * 1.35σ= 3.375σ"
},
{
"code": null,
"e": 6450,
"s": 5955,
"text": "So, when scale is taken as 2, then according to IQR Method any data which lies beyond 3.375σ from the mean (μ), on either side, shall be considered as outlier. But as we know, upto 3σ, on either side of the μ ,the data is useful. So we cannot take scale = 2, because this makes the decision range too inclusive, means this results in too few outliers. In other words, the decision range gets so big (compared to 3σ) that it considers some outliers as data points, which is not desirable either."
},
{
"code": null,
"e": 6682,
"s": 6450,
"text": "Lower Bound:= Q1 - 1.5 * IQR= Q1 - 1.5 * (Q3 - Q1)= -0.675σ - 1.5 * (0.675 - [-0.675])σ= -0.675σ - 1.5 * 1.35σ= -2.7σUpper Bound:= Q3 + 1.5 * IQR= Q3 + 1.5 * (Q3 - Q1)= 0.675σ + 1.5 * (0.675 - [-0.675])σ= 0.675σ + 1.5 * 1.35σ= 2.7σ"
},
{
"code": null,
"e": 7079,
"s": 6682,
"text": "When scale is taken as 1.5, then according to IQR Method any data which lies beyond 2.7σ from the mean (μ), on either side, shall be considered as outlier. And this decision range is the closest to what Gaussian Distribution tells us, i.e., 3σ. In other words, this makes the decision rule closest to what Gaussian Distribution considers for outlier detection, and this is exactly what we wanted."
},
{
"code": null,
"e": 7097,
"s": 7079,
"text": "*** Side Note ***"
},
{
"code": null,
"e": 7268,
"s": 7097,
"text": "To get exactly 3σ, we need to take the scale = 1.7, but then 1.5 is more “symmetrical” than 1.7 and we’ve always been a little more inclined towards symmetry, aren’t we!?"
},
{
"code": null,
"e": 7424,
"s": 7268,
"text": "Also, IQR Method of Outlier Detection is not the only and definitely not the best method for outlier detection, so a bit trade-off is legible and accepted."
},
{
"code": null,
"e": 7705,
"s": 7424,
"text": "See, how beautifully and elegantly it all unfolded using maths. I just love how things become clear and evidently takes shape when perceived through its mathematics. And this is one of the many reasons why maths is the language of our world (not sure about the universe though 😐)."
},
{
"code": null,
"e": 7909,
"s": 7705,
"text": "So, I hope, now you know why do we take it 1.5 * IQR. But this scale depends on the distribution followed by the data. Say if my data seem to follow exponential distribution then this scale would change."
},
{
"code": null,
"e": 8008,
"s": 7909,
"text": "But again, every complication which arises because of mathematics is solved by mathematics itself."
},
{
"code": null,
"e": 8242,
"s": 8008,
"text": "Ever heard of Central Limit Theorem? Yep! The very same theorem why grants us the liberty to assume the distribution to be followed as Gaussian without any guilt. But I think I’d leave that for some other day. Until then, be curious!"
}
] |
Python Classes for Statistics with Pandas | by Sadrach Pierre, Ph.D. | Towards Data Science | In computer programming, a class is a blueprint for a user-defined data type. Classes are defined in terms of attributes (data) and methods (functions). These data structures are a great way to organize data and methods such that they are easy to reuse and extend in the future. In this post, we will define a python class that will allow us to generate simple summary statistics and perform some EDA on data.
Let’s get started!
For our purposes we will be working with the FIFA 19 data set which can be found here.
To start, let’s import the pandas package:
import pandas as pd
Next, let’s set the maximum number of display columns and rows to ‘None’:
pd.set_option('display.max_columns', None)pd.set_option('display.max_rows', None)
Now, let’s read in our data:
df = pd.read_csv('fifa_data.csv')
Next we will print the first five rows of data to get an idea of the column types and their values (column results are truncated):
print(df.head())
To start, let’s define a simple class called ‘Summary’ that reads in the data and displays the firsts five rows upon initialization:
class Summary: def __init__(self, data): pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) self.df = pd.read_csv(data) print(self.df.head())
If we call an instance of our Summary class with data = ‘fifa_data.csv’ we get:
Summary('fifa_data.csv')
Let’s modify this class such that we have a method that we can call to display the first five rows:
class Summary: def __init__(self, data): pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) self.df = pd.read_csv(data) def print_head(self): print(self.df.head())
Now if we define an instance, we can call the the ‘print_head’ method on our instance and it will display the first five rows:
data = Summary('fifa_data.csv')data.print_head()
We can also modify our ‘print_head’ method so that it can print more than the default five rows.
class Summary: def __init__(self, data): pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) self.df = pd.read_csv(data) def print_head(self, rows): print(self.df.head(rows))
Now if we call print head with ‘rows’=10 get (I truncated the number of columns shown:):
data = Summary('fifa_data.csv')data.print_head(10)
Let’s also define a function that gets the column names for the data:
class Summary: ... def get_columns(self): print(list(self.df.columns))
And if we call ‘get_columns’ we get:
data.get_columns()
We can also define a method that prints the number of columns and rows:
class Summary: ... def get_dim(self): print('Rows:', len(self.df)) print('Columns:', len(list(self.df.columns)))
And if we call ‘get_dim’ on ‘data’:
data.get_dim()
We see that our data has 18,207 rows and 88 columns. Now let’s define some functions that can give us some statistical insights. The Pandas data frame has an ‘describe()’ method that gives us some basic statistical info. This includes count, mean, standard deviation, min, max, and quartiles:
class Summary: ... def get_stats(self): print(self.df.describe())
Now let’s call ‘get_stats’. Below the stats for ‘Special’, ‘International Reputation’, ‘Weak Foot’, ‘Skill Moves’ are shown:
data. get_stats()
Since the data contains 88 columns it can be a bit daunting to inspect the summary statistics for all of these columns at once. We can define a function that calculates the mean for a specific column:
class Summary: ... def get_mean(self, column): print(f"Mean {column}:", self.df[column].mean())
Let’s call this method on the ‘Age’ column:
data.get_mean('Age')
We can do the same for the standard deviation:
class Summary: ... def get_standard_dev(self, column): print(f"STD {column}:", self.df[column].std())...data.get_standard_dev('Age')
For categorical columns we can define a method that displays the distribution in categorical values, using the ‘Counter’ method from the collections module. Let’s apply this to the ‘Nationality’ column:
...from collections import Counterclass Summary: ... def get_counter(self, column): print(dict(Counter(self.df[column])))...data.get_counter('Nationality')
We can define a function that displays a histogram for a specific numerical column. Let’s apply this to the ‘Age’ column:
...import matplotlib.pyplot as pltimport seaborn as snsclass Summary: ... def get_hist(self, column): sns.set() self.df[column].hist(bins=100) plt.title(f"{column} Histogram") plt.show()...data.get_hist('Age')
Next, we can use boxplots to visualize the distribution in numeric values across different categorical values in a categorical column:
class Summary: ... def get_boxplot_of_categories(self, categorical_column, numerical_column, limit): keys = [] for i in dict(Counter(self.df[categorical_column].values).most_common(limit)): keys.append(i) df_new = self.df[self.df[categorical_column].isin(keys)] sns.set() sns.boxplot(x = df_new[categorical_column], y = df_new[numerical_column])plt.show()
Let’s generate boxplots for ‘Age’ in the 5 most commonly occurring Nationalities :
data.get_boxplot_of_categories(df, 'Nationality', 'Age', 5)
Finally, we can define a function that displays a heat map for a specific numerical column:
class Summary: ... def get_heatmap(self, columns): df_new = self.df[columns] sns.heatmap(df_new.corr()) plt.title(f"Heatmap of {columns}")
Let’s apply this to ‘Age’, ‘Overall’, ‘Potential’, ‘Special’:
data.get_heatmap(['Age', 'Overall', 'Potential', 'Special'])
The nice thing about this class is that it is a general blueprint that can be reapplied to any ‘csv’ file. All you would need to change is the initiation of the instance with the file name:
data = Summary('new_file.csv')
Upon using ‘get_head’ and ‘get_column’ you will learn the column names and types and you will be able to start applying the statistics and visualization methods we used in this post. I’ll stop here but I encourage you to play around with the data and code yourself.
To summarize, in this post we showed how to use python classes to generate simple summary statistics using the Pandas library. First we showed basic operations like how to get the first set of rows, column and row lengths, and simple statistics using the describe method. These methods allow you to quickly get a rough understanding of the data types and their values. Further we built custom statistic functions that allow us to analyze specific columns. This is useful when we have too many columns to analyze quickly. We also showed some methods for visualizing the distribution in numerical values in our data which gives us insights into which values fall close to the mean and which are outliers. Finally, we discussed how to define a method that allows you to generate a heat-map of correlation values. This helps us visualize how variables depend on each other. This can be very useful for feature engineering and model building in machine learning. I hope you found this post useful/interesting. The code in this post is available on Github. Thank you for reading! | [
{
"code": null,
"e": 581,
"s": 171,
"text": "In computer programming, a class is a blueprint for a user-defined data type. Classes are defined in terms of attributes (data) and methods (functions). These data structures are a great way to organize data and methods such that they are easy to reuse and extend in the future. In this post, we will define a python class that will allow us to generate simple summary statistics and perform some EDA on data."
},
{
"code": null,
"e": 600,
"s": 581,
"text": "Let’s get started!"
},
{
"code": null,
"e": 687,
"s": 600,
"text": "For our purposes we will be working with the FIFA 19 data set which can be found here."
},
{
"code": null,
"e": 730,
"s": 687,
"text": "To start, let’s import the pandas package:"
},
{
"code": null,
"e": 750,
"s": 730,
"text": "import pandas as pd"
},
{
"code": null,
"e": 824,
"s": 750,
"text": "Next, let’s set the maximum number of display columns and rows to ‘None’:"
},
{
"code": null,
"e": 906,
"s": 824,
"text": "pd.set_option('display.max_columns', None)pd.set_option('display.max_rows', None)"
},
{
"code": null,
"e": 935,
"s": 906,
"text": "Now, let’s read in our data:"
},
{
"code": null,
"e": 969,
"s": 935,
"text": "df = pd.read_csv('fifa_data.csv')"
},
{
"code": null,
"e": 1100,
"s": 969,
"text": "Next we will print the first five rows of data to get an idea of the column types and their values (column results are truncated):"
},
{
"code": null,
"e": 1117,
"s": 1100,
"text": "print(df.head())"
},
{
"code": null,
"e": 1250,
"s": 1117,
"text": "To start, let’s define a simple class called ‘Summary’ that reads in the data and displays the firsts five rows upon initialization:"
},
{
"code": null,
"e": 1455,
"s": 1250,
"text": "class Summary: def __init__(self, data): pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) self.df = pd.read_csv(data) print(self.df.head())"
},
{
"code": null,
"e": 1535,
"s": 1455,
"text": "If we call an instance of our Summary class with data = ‘fifa_data.csv’ we get:"
},
{
"code": null,
"e": 1560,
"s": 1535,
"text": "Summary('fifa_data.csv')"
},
{
"code": null,
"e": 1660,
"s": 1560,
"text": "Let’s modify this class such that we have a method that we can call to display the first five rows:"
},
{
"code": null,
"e": 1890,
"s": 1660,
"text": "class Summary: def __init__(self, data): pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) self.df = pd.read_csv(data) def print_head(self): print(self.df.head())"
},
{
"code": null,
"e": 2017,
"s": 1890,
"text": "Now if we define an instance, we can call the the ‘print_head’ method on our instance and it will display the first five rows:"
},
{
"code": null,
"e": 2066,
"s": 2017,
"text": "data = Summary('fifa_data.csv')data.print_head()"
},
{
"code": null,
"e": 2163,
"s": 2066,
"text": "We can also modify our ‘print_head’ method so that it can print more than the default five rows."
},
{
"code": null,
"e": 2403,
"s": 2163,
"text": "class Summary: def __init__(self, data): pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) self.df = pd.read_csv(data) def print_head(self, rows): print(self.df.head(rows))"
},
{
"code": null,
"e": 2492,
"s": 2403,
"text": "Now if we call print head with ‘rows’=10 get (I truncated the number of columns shown:):"
},
{
"code": null,
"e": 2543,
"s": 2492,
"text": "data = Summary('fifa_data.csv')data.print_head(10)"
},
{
"code": null,
"e": 2613,
"s": 2543,
"text": "Let’s also define a function that gets the column names for the data:"
},
{
"code": null,
"e": 2697,
"s": 2613,
"text": "class Summary: ... def get_columns(self): print(list(self.df.columns))"
},
{
"code": null,
"e": 2734,
"s": 2697,
"text": "And if we call ‘get_columns’ we get:"
},
{
"code": null,
"e": 2753,
"s": 2734,
"text": "data.get_columns()"
},
{
"code": null,
"e": 2825,
"s": 2753,
"text": "We can also define a method that prints the number of columns and rows:"
},
{
"code": null,
"e": 2958,
"s": 2825,
"text": "class Summary: ... def get_dim(self): print('Rows:', len(self.df)) print('Columns:', len(list(self.df.columns)))"
},
{
"code": null,
"e": 2994,
"s": 2958,
"text": "And if we call ‘get_dim’ on ‘data’:"
},
{
"code": null,
"e": 3009,
"s": 2994,
"text": "data.get_dim()"
},
{
"code": null,
"e": 3302,
"s": 3009,
"text": "We see that our data has 18,207 rows and 88 columns. Now let’s define some functions that can give us some statistical insights. The Pandas data frame has an ‘describe()’ method that gives us some basic statistical info. This includes count, mean, standard deviation, min, max, and quartiles:"
},
{
"code": null,
"e": 3381,
"s": 3302,
"text": "class Summary: ... def get_stats(self): print(self.df.describe())"
},
{
"code": null,
"e": 3506,
"s": 3381,
"text": "Now let’s call ‘get_stats’. Below the stats for ‘Special’, ‘International Reputation’, ‘Weak Foot’, ‘Skill Moves’ are shown:"
},
{
"code": null,
"e": 3524,
"s": 3506,
"text": "data. get_stats()"
},
{
"code": null,
"e": 3725,
"s": 3524,
"text": "Since the data contains 88 columns it can be a bit daunting to inspect the summary statistics for all of these columns at once. We can define a function that calculates the mean for a specific column:"
},
{
"code": null,
"e": 3834,
"s": 3725,
"text": "class Summary: ... def get_mean(self, column): print(f\"Mean {column}:\", self.df[column].mean())"
},
{
"code": null,
"e": 3878,
"s": 3834,
"text": "Let’s call this method on the ‘Age’ column:"
},
{
"code": null,
"e": 3899,
"s": 3878,
"text": "data.get_mean('Age')"
},
{
"code": null,
"e": 3946,
"s": 3899,
"text": "We can do the same for the standard deviation:"
},
{
"code": null,
"e": 4092,
"s": 3946,
"text": "class Summary: ... def get_standard_dev(self, column): print(f\"STD {column}:\", self.df[column].std())...data.get_standard_dev('Age')"
},
{
"code": null,
"e": 4295,
"s": 4092,
"text": "For categorical columns we can define a method that displays the distribution in categorical values, using the ‘Counter’ method from the collections module. Let’s apply this to the ‘Nationality’ column:"
},
{
"code": null,
"e": 4464,
"s": 4295,
"text": "...from collections import Counterclass Summary: ... def get_counter(self, column): print(dict(Counter(self.df[column])))...data.get_counter('Nationality')"
},
{
"code": null,
"e": 4586,
"s": 4464,
"text": "We can define a function that displays a histogram for a specific numerical column. Let’s apply this to the ‘Age’ column:"
},
{
"code": null,
"e": 4830,
"s": 4586,
"text": "...import matplotlib.pyplot as pltimport seaborn as snsclass Summary: ... def get_hist(self, column): sns.set() self.df[column].hist(bins=100) plt.title(f\"{column} Histogram\") plt.show()...data.get_hist('Age')"
},
{
"code": null,
"e": 4965,
"s": 4830,
"text": "Next, we can use boxplots to visualize the distribution in numeric values across different categorical values in a categorical column:"
},
{
"code": null,
"e": 5373,
"s": 4965,
"text": "class Summary: ... def get_boxplot_of_categories(self, categorical_column, numerical_column, limit): keys = [] for i in dict(Counter(self.df[categorical_column].values).most_common(limit)): keys.append(i) df_new = self.df[self.df[categorical_column].isin(keys)] sns.set() sns.boxplot(x = df_new[categorical_column], y = df_new[numerical_column])plt.show()"
},
{
"code": null,
"e": 5456,
"s": 5373,
"text": "Let’s generate boxplots for ‘Age’ in the 5 most commonly occurring Nationalities :"
},
{
"code": null,
"e": 5516,
"s": 5456,
"text": "data.get_boxplot_of_categories(df, 'Nationality', 'Age', 5)"
},
{
"code": null,
"e": 5608,
"s": 5516,
"text": "Finally, we can define a function that displays a heat map for a specific numerical column:"
},
{
"code": null,
"e": 5774,
"s": 5608,
"text": "class Summary: ... def get_heatmap(self, columns): df_new = self.df[columns] sns.heatmap(df_new.corr()) plt.title(f\"Heatmap of {columns}\")"
},
{
"code": null,
"e": 5836,
"s": 5774,
"text": "Let’s apply this to ‘Age’, ‘Overall’, ‘Potential’, ‘Special’:"
},
{
"code": null,
"e": 5897,
"s": 5836,
"text": "data.get_heatmap(['Age', 'Overall', 'Potential', 'Special'])"
},
{
"code": null,
"e": 6087,
"s": 5897,
"text": "The nice thing about this class is that it is a general blueprint that can be reapplied to any ‘csv’ file. All you would need to change is the initiation of the instance with the file name:"
},
{
"code": null,
"e": 6118,
"s": 6087,
"text": "data = Summary('new_file.csv')"
},
{
"code": null,
"e": 6384,
"s": 6118,
"text": "Upon using ‘get_head’ and ‘get_column’ you will learn the column names and types and you will be able to start applying the statistics and visualization methods we used in this post. I’ll stop here but I encourage you to play around with the data and code yourself."
}
] |
How to remove hidden files and folders using Python? | On Unix OS(OSX, Linux, etc) hidden files start with a '.' so we can filter them out using a simple startswith check. On windows, we need to check file attributes and then determine whether the file/folder is hidden or not.
For example, you can use the following code to delete all hidden files:
import os
if os.name == 'nt':
import win32api, win32con
def file_is_hidden(p):
if os.name== 'nt':
attribute = win32api.GetFileAttributes(p)
return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
else:
return p.startswith('.') #linux-osx
[os.remove(f) for f in os.listdir('.') if file_is_hidden(f)] | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "On Unix OS(OSX, Linux, etc) hidden files start with a '.' so we can filter them out using a simple startswith check. On windows, we need to check file attributes and then determine whether the file/folder is hidden or not."
},
{
"code": null,
"e": 1357,
"s": 1285,
"text": "For example, you can use the following code to delete all hidden files:"
},
{
"code": null,
"e": 1721,
"s": 1357,
"text": "import os\nif os.name == 'nt':\n import win32api, win32con\ndef file_is_hidden(p):\n if os.name== 'nt':\n attribute = win32api.GetFileAttributes(p)\n return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)\n else:\n return p.startswith('.') #linux-osx\n[os.remove(f) for f in os.listdir('.') if file_is_hidden(f)]"
}
] |
Understand the Data With Univariate And Multivariate Charts and Plots in Python | by Rashida Nasrin Sucky | Towards Data Science | Univariate data analysis is the simplest form of data analysis. As the name suggests, it deals with one variable. It doesn’t find cause and effect or relationship between variables. The purpose of univariate data analysis is to summarize and describe one data or one variable. If two variables are included, it becomes bivariate. In this article, we will understand and visualize some data using univariate and bivariate data analysis. In some practice, we will include three variables as well. All the information is true only for the particular dataset used in this article.
We will use the Heart dataset from Kaggle. First import the packages and the dataset.
%matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdfrom statsmodels import api as smimport numpy as npdf = pd.read_csv("Heart.csv")
Let’s see the column names clearly:
df.columns#Output:Index(['Unnamed: 0', 'Age', 'Sex', 'ChestPain', 'RestBP', 'Chol', 'Fbs', 'RestECG', 'MaxHR', 'ExAng', 'Oldpeak', 'Slope', 'Ca', 'Thal', 'AHD'], dtype='object')
You may not understand now what each column means. I will only use a few columns in this article and I will keep explaining what the column name means as we go.
Find the population proportions with different types of blood disorders.
Find the population proportions with different types of blood disorders.
We will find that in the ‘Thal’ column. Here, ‘Thal’ means a blood disorder called thalassemia. There is a function in Pandas called ‘value_counts’ that count the value of each category in a Series.
x = df.Thal.value_counts()x
These are the numbers of people having normal, reversible, and fixed disorders. Now, divide each of them with the total population to find the population proportion.
x / x.sum()
If you notice, these proportions do not add up to 1. There is one thing we missed in this calculation. There might be some values. Fill those spaced with ‘Missing’ And then calculate the proportions again.
df["Thal"] = df.Thal.fillna("Missing")x = df.Thal.value_counts()x / x.sum()
So, there were a few missing values. In this dataset, 54.79% of people have normal thalassemia. The next big one was 38.16%, who have reversible thalassemia.
2. Find the minimum, maximum, average, and standard deviation of Cholesterol data.
There is a function called ‘describe’. Let’s use that. We will get all the information we needed and also some other useful parameters which will help us understand the data even better.
So, we got a few extra useful parameters. The population count is 303. We are not going to use that in this article. But it is important in statistical analysis. Especially in inferential statistics. ‘describe’ function also returns 25%, 50%, and 75% percentile data that gives an idea of the distribution of the data.
3. Make a plot of the distribution of the Cholesterol data.
sns.distplot(df.Chol.dropna())
The distribution is slightly right-skewed with some outliers.
4. Find the mean of the RestBP (Resting Blood Pressure). Then, calculate the population proportion of the people who have the higher RestBP than the mean RestBP.
mean_rbp = df.RestBP.dropna().mean()
Mean RestBP was 131.69. First, find the dataset where RestBP is bigger than mean RestBP. Divide it by the length of the total dataset.
len(df[df["RestBP"] > mean_rbp])/len(df)
The result is 0.44 or 44%.
5. Plot the Cholesterol data against the age group to observe the difference in cholesterol levels in different age groups of people.
Here is the solution. Make a new column in the dataset that will return the number of people in the different age groups.
df["agegrp"]=pd.cut(df.Age, [29,40,50,60,70,80])
Now, make the boxplots. Place age groups on the x-axis and the cholesterol level in the y-axis.
plt.figure(figsize=(12,5))sns.boxplot(x = "agegrp", y = "Chol", data=df)
The box plot shows an increasing trend of cholesterol with the increasing age. It is a good idea to check if gender plays any role. If the cholesterol level differs in different genders. In our sex column, we have the numbers 0 and 1 for females and males. We will make a new column replacing 0 or 1 with ‘Male’ and ‘Female’.
df["Sex1"] = df.Sex.replace({1: "Male", 0: "Female"})plt.figure(figsize=(12, 4))sns.boxplot(x = "agegrp", y = "Chol", hue = "Sex1", data=df)
Overall, the female population in this dataset has a higher level of cholesterol. In the age group of 29 to 40, it is different. In the age group of 70 to 80, there is cholesterol level only in the female population. That does not mean that the male population in that age has no cholesterol. In our dataset, we do not have enough male population in that age group. It will be helpful to understand if we plot the male and female population against the age.
sns.boxplot(x = "Sex1", y = "Age", data=df)
6. Make a chart to show the number of people having each type of chest pain in each age group.
df.groupby('agegrp')["ChestPain"].value_counts().unstack()
For each type of chest pain, the maximum people seem to be in the age group of 50 to 60. Probably because we have the most number of people in that age group in our dataset. Look at the picture above.
7. Make the same chart as the previous practice with the addition of Gender variable. Segregate the numbers by gender.
dx = df.dropna().groupby(["agegrp", "Sex1"])["ChestPain"].value_counts().unstack()
8. Present the population proportion for each type of chest pain in the same groups in the previous chart.
dx = dx.apply(lambda x: x/x.sum(), axis=1)
That was the last exercise. These were some techniques to make univariate and multivariate charts and plots. I hope that was helpful. Here, I have links to some relevant articles:
Understanding the data using histogram and boxplot
Understanding the data using histogram and boxplot
2. Confidence Interval, Calculation, and Characteristics
3. Confidence Intervals of Population Proportion and the Difference in Python
4. How to Calculate Confidence Interval of Mean and the Difference of Mean
5. How to Formulate Good Research Question for Data Analysis | [
{
"code": null,
"e": 749,
"s": 172,
"text": "Univariate data analysis is the simplest form of data analysis. As the name suggests, it deals with one variable. It doesn’t find cause and effect or relationship between variables. The purpose of univariate data analysis is to summarize and describe one data or one variable. If two variables are included, it becomes bivariate. In this article, we will understand and visualize some data using univariate and bivariate data analysis. In some practice, we will include three variables as well. All the information is true only for the particular dataset used in this article."
},
{
"code": null,
"e": 835,
"s": 749,
"text": "We will use the Heart dataset from Kaggle. First import the packages and the dataset."
},
{
"code": null,
"e": 1005,
"s": 835,
"text": "%matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdfrom statsmodels import api as smimport numpy as npdf = pd.read_csv(\"Heart.csv\")"
},
{
"code": null,
"e": 1041,
"s": 1005,
"text": "Let’s see the column names clearly:"
},
{
"code": null,
"e": 1232,
"s": 1041,
"text": "df.columns#Output:Index(['Unnamed: 0', 'Age', 'Sex', 'ChestPain', 'RestBP', 'Chol', 'Fbs', 'RestECG', 'MaxHR', 'ExAng', 'Oldpeak', 'Slope', 'Ca', 'Thal', 'AHD'], dtype='object')"
},
{
"code": null,
"e": 1393,
"s": 1232,
"text": "You may not understand now what each column means. I will only use a few columns in this article and I will keep explaining what the column name means as we go."
},
{
"code": null,
"e": 1466,
"s": 1393,
"text": "Find the population proportions with different types of blood disorders."
},
{
"code": null,
"e": 1539,
"s": 1466,
"text": "Find the population proportions with different types of blood disorders."
},
{
"code": null,
"e": 1738,
"s": 1539,
"text": "We will find that in the ‘Thal’ column. Here, ‘Thal’ means a blood disorder called thalassemia. There is a function in Pandas called ‘value_counts’ that count the value of each category in a Series."
},
{
"code": null,
"e": 1766,
"s": 1738,
"text": "x = df.Thal.value_counts()x"
},
{
"code": null,
"e": 1932,
"s": 1766,
"text": "These are the numbers of people having normal, reversible, and fixed disorders. Now, divide each of them with the total population to find the population proportion."
},
{
"code": null,
"e": 1944,
"s": 1932,
"text": "x / x.sum()"
},
{
"code": null,
"e": 2150,
"s": 1944,
"text": "If you notice, these proportions do not add up to 1. There is one thing we missed in this calculation. There might be some values. Fill those spaced with ‘Missing’ And then calculate the proportions again."
},
{
"code": null,
"e": 2226,
"s": 2150,
"text": "df[\"Thal\"] = df.Thal.fillna(\"Missing\")x = df.Thal.value_counts()x / x.sum()"
},
{
"code": null,
"e": 2384,
"s": 2226,
"text": "So, there were a few missing values. In this dataset, 54.79% of people have normal thalassemia. The next big one was 38.16%, who have reversible thalassemia."
},
{
"code": null,
"e": 2467,
"s": 2384,
"text": "2. Find the minimum, maximum, average, and standard deviation of Cholesterol data."
},
{
"code": null,
"e": 2654,
"s": 2467,
"text": "There is a function called ‘describe’. Let’s use that. We will get all the information we needed and also some other useful parameters which will help us understand the data even better."
},
{
"code": null,
"e": 2973,
"s": 2654,
"text": "So, we got a few extra useful parameters. The population count is 303. We are not going to use that in this article. But it is important in statistical analysis. Especially in inferential statistics. ‘describe’ function also returns 25%, 50%, and 75% percentile data that gives an idea of the distribution of the data."
},
{
"code": null,
"e": 3033,
"s": 2973,
"text": "3. Make a plot of the distribution of the Cholesterol data."
},
{
"code": null,
"e": 3064,
"s": 3033,
"text": "sns.distplot(df.Chol.dropna())"
},
{
"code": null,
"e": 3126,
"s": 3064,
"text": "The distribution is slightly right-skewed with some outliers."
},
{
"code": null,
"e": 3288,
"s": 3126,
"text": "4. Find the mean of the RestBP (Resting Blood Pressure). Then, calculate the population proportion of the people who have the higher RestBP than the mean RestBP."
},
{
"code": null,
"e": 3325,
"s": 3288,
"text": "mean_rbp = df.RestBP.dropna().mean()"
},
{
"code": null,
"e": 3460,
"s": 3325,
"text": "Mean RestBP was 131.69. First, find the dataset where RestBP is bigger than mean RestBP. Divide it by the length of the total dataset."
},
{
"code": null,
"e": 3501,
"s": 3460,
"text": "len(df[df[\"RestBP\"] > mean_rbp])/len(df)"
},
{
"code": null,
"e": 3528,
"s": 3501,
"text": "The result is 0.44 or 44%."
},
{
"code": null,
"e": 3662,
"s": 3528,
"text": "5. Plot the Cholesterol data against the age group to observe the difference in cholesterol levels in different age groups of people."
},
{
"code": null,
"e": 3784,
"s": 3662,
"text": "Here is the solution. Make a new column in the dataset that will return the number of people in the different age groups."
},
{
"code": null,
"e": 3833,
"s": 3784,
"text": "df[\"agegrp\"]=pd.cut(df.Age, [29,40,50,60,70,80])"
},
{
"code": null,
"e": 3929,
"s": 3833,
"text": "Now, make the boxplots. Place age groups on the x-axis and the cholesterol level in the y-axis."
},
{
"code": null,
"e": 4002,
"s": 3929,
"text": "plt.figure(figsize=(12,5))sns.boxplot(x = \"agegrp\", y = \"Chol\", data=df)"
},
{
"code": null,
"e": 4328,
"s": 4002,
"text": "The box plot shows an increasing trend of cholesterol with the increasing age. It is a good idea to check if gender plays any role. If the cholesterol level differs in different genders. In our sex column, we have the numbers 0 and 1 for females and males. We will make a new column replacing 0 or 1 with ‘Male’ and ‘Female’."
},
{
"code": null,
"e": 4469,
"s": 4328,
"text": "df[\"Sex1\"] = df.Sex.replace({1: \"Male\", 0: \"Female\"})plt.figure(figsize=(12, 4))sns.boxplot(x = \"agegrp\", y = \"Chol\", hue = \"Sex1\", data=df)"
},
{
"code": null,
"e": 4927,
"s": 4469,
"text": "Overall, the female population in this dataset has a higher level of cholesterol. In the age group of 29 to 40, it is different. In the age group of 70 to 80, there is cholesterol level only in the female population. That does not mean that the male population in that age has no cholesterol. In our dataset, we do not have enough male population in that age group. It will be helpful to understand if we plot the male and female population against the age."
},
{
"code": null,
"e": 4971,
"s": 4927,
"text": "sns.boxplot(x = \"Sex1\", y = \"Age\", data=df)"
},
{
"code": null,
"e": 5066,
"s": 4971,
"text": "6. Make a chart to show the number of people having each type of chest pain in each age group."
},
{
"code": null,
"e": 5125,
"s": 5066,
"text": "df.groupby('agegrp')[\"ChestPain\"].value_counts().unstack()"
},
{
"code": null,
"e": 5326,
"s": 5125,
"text": "For each type of chest pain, the maximum people seem to be in the age group of 50 to 60. Probably because we have the most number of people in that age group in our dataset. Look at the picture above."
},
{
"code": null,
"e": 5445,
"s": 5326,
"text": "7. Make the same chart as the previous practice with the addition of Gender variable. Segregate the numbers by gender."
},
{
"code": null,
"e": 5528,
"s": 5445,
"text": "dx = df.dropna().groupby([\"agegrp\", \"Sex1\"])[\"ChestPain\"].value_counts().unstack()"
},
{
"code": null,
"e": 5635,
"s": 5528,
"text": "8. Present the population proportion for each type of chest pain in the same groups in the previous chart."
},
{
"code": null,
"e": 5678,
"s": 5635,
"text": "dx = dx.apply(lambda x: x/x.sum(), axis=1)"
},
{
"code": null,
"e": 5858,
"s": 5678,
"text": "That was the last exercise. These were some techniques to make univariate and multivariate charts and plots. I hope that was helpful. Here, I have links to some relevant articles:"
},
{
"code": null,
"e": 5909,
"s": 5858,
"text": "Understanding the data using histogram and boxplot"
},
{
"code": null,
"e": 5960,
"s": 5909,
"text": "Understanding the data using histogram and boxplot"
},
{
"code": null,
"e": 6017,
"s": 5960,
"text": "2. Confidence Interval, Calculation, and Characteristics"
},
{
"code": null,
"e": 6095,
"s": 6017,
"text": "3. Confidence Intervals of Population Proportion and the Difference in Python"
},
{
"code": null,
"e": 6170,
"s": 6095,
"text": "4. How to Calculate Confidence Interval of Mean and the Difference of Mean"
}
] |
How to use getline() in C++ when there are blank lines in input? | 03 Jun, 2022
In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses <string.h> header file to be fully functional.
Here is a sample program in c++ that reads four sentences and displays them with “: newline” at the end
CPP
// A simple C++ program to show working of getline#include <cstring>#include <iostream>using namespace std;int main(){ string str; int t = 4; while (t--) { // Read a line from standard input in str getline(cin, str); cout << str << " : newline" << endl; } return 0;}
Sample Input :
This
is
Geeks
for
As the expected output is:
This : newline
is : newline
Geeks : newline
for : newline
The above input and output look good, there may be problems when the input has blank lines in between.
Sample Input :
This
is
Geeks
for
Output:
This : newline
: newline
is : newline
: newline
It doesn’t print the last 3 lines. The reason is that getline() reads till enter is encountered even if no characters are read. So even if there is nothing in the third line, getline() considers it as a single line. Further, observe the problem in the second line. The code can be modified to exclude such blank lines. Modified code:
CPP
// A simple C++ program that uses getline to read// input with blank lines#include <cstring>#include <iostream>using namespace std;int main(){ string str; int t = 4; while (t--) { getline(cin, str); // Keep reading a new line while there is // a blank line while (str.length() == 0) getline(cin, str); cout << str << " : newline" << endl; } return 0;}
Input:
This
is
Geeks
for
Output:
This : newline
is : newline
Geeks : newline
for : newline
This article is contributed by Sarin Nanda. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
harsh_shokeen
cpp-input-output
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 335,
"s": 54,
"text": "In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses <string.h> header file to be fully functional."
},
{
"code": null,
"e": 440,
"s": 335,
"text": "Here is a sample program in c++ that reads four sentences and displays them with “: newline” at the end "
},
{
"code": null,
"e": 444,
"s": 440,
"text": "CPP"
},
{
"code": "// A simple C++ program to show working of getline#include <cstring>#include <iostream>using namespace std;int main(){ string str; int t = 4; while (t--) { // Read a line from standard input in str getline(cin, str); cout << str << \" : newline\" << endl; } return 0;}",
"e": 747,
"s": 444,
"text": null
},
{
"code": null,
"e": 762,
"s": 747,
"text": "Sample Input :"
},
{
"code": null,
"e": 784,
"s": 762,
"text": " This\n is\n Geeks\n for"
},
{
"code": null,
"e": 811,
"s": 784,
"text": "As the expected output is:"
},
{
"code": null,
"e": 870,
"s": 811,
"text": "This : newline\nis : newline\nGeeks : newline\nfor : newline"
},
{
"code": null,
"e": 974,
"s": 870,
"text": "The above input and output look good, there may be problems when the input has blank lines in between. "
},
{
"code": null,
"e": 989,
"s": 974,
"text": "Sample Input :"
},
{
"code": null,
"e": 1011,
"s": 989,
"text": "This\n\nis \n\nGeeks\n\nfor"
},
{
"code": null,
"e": 1019,
"s": 1011,
"text": "Output:"
},
{
"code": null,
"e": 1070,
"s": 1019,
"text": "This : newline\n : newline\nis : newline\n : newline"
},
{
"code": null,
"e": 1405,
"s": 1070,
"text": "It doesn’t print the last 3 lines. The reason is that getline() reads till enter is encountered even if no characters are read. So even if there is nothing in the third line, getline() considers it as a single line. Further, observe the problem in the second line. The code can be modified to exclude such blank lines. Modified code: "
},
{
"code": null,
"e": 1409,
"s": 1405,
"text": "CPP"
},
{
"code": "// A simple C++ program that uses getline to read// input with blank lines#include <cstring>#include <iostream>using namespace std;int main(){ string str; int t = 4; while (t--) { getline(cin, str); // Keep reading a new line while there is // a blank line while (str.length() == 0) getline(cin, str); cout << str << \" : newline\" << endl; } return 0;}",
"e": 1824,
"s": 1409,
"text": null
},
{
"code": null,
"e": 1831,
"s": 1824,
"text": "Input:"
},
{
"code": null,
"e": 1853,
"s": 1831,
"text": "This\n\nis \n\nGeeks\n\nfor"
},
{
"code": null,
"e": 1861,
"s": 1853,
"text": "Output:"
},
{
"code": null,
"e": 1920,
"s": 1861,
"text": "This : newline\nis : newline\nGeeks : newline\nfor : newline"
},
{
"code": null,
"e": 2158,
"s": 1920,
"text": "This article is contributed by Sarin Nanda. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2172,
"s": 2158,
"text": "harsh_shokeen"
},
{
"code": null,
"e": 2189,
"s": 2172,
"text": "cpp-input-output"
},
{
"code": null,
"e": 2201,
"s": 2189,
"text": "CPP-Library"
},
{
"code": null,
"e": 2212,
"s": 2201,
"text": "C Language"
},
{
"code": null,
"e": 2216,
"s": 2212,
"text": "C++"
},
{
"code": null,
"e": 2220,
"s": 2216,
"text": "CPP"
}
] |
Maximal Independent Set in an Undirected Graph | 13 Jul, 2020
Given an undirected graph defined by the number of vertex V and the edges E[ ], the task is to find Maximal Independent Vertex Set in an undirected graph.
Independent Set: An independent set in a graph is a set of vertices which are not directly connected to each other.
Note: It is a given that there is at least one way to traverse from any vertex in the graph to another, i.e. the graph has one connected component.
Examples:
Input: V = 3, E = { (1, 2), (2, 3) }Output: {1, 3}Explanation:Since there are no edges between 1 and 3, and we cannot add 2 to this since it is a neighbour of 1, this is the Maximal Independent Set.
Input: V = 8,E = { (1, 2), (1, 3), (2, 4), (5, 6), (6, 7), (4, 8) }Output: {2, 3, 5, 7, 8}
Approach:This problem is an NP-Hard problem, which can only be solved in exponential time(as of right now).Follow the steps below to solve the problem:
Iterate through the vertices of the graph and use backtracking to check if a vertex can be included in the Maximal Independent Set or not.
Two possibilities arise for each vertex, whether it can be included or not in the maximal independent set.
Initially start, considering all vertices and edges. One by one, select a vertex. Remove that vertex from the graph, excluding it from the maximal independent set, and recursively traverse the remaining graph to find the maximal independent set.
Otherwise, consider the selected vertex in the maximal independent set and remove all its neighbors from it. Proceed to find the maximal independent set possible excluding its neighbors.
Repeat this process for all vertices and print the maximal independent set obtained.
Below is the implementation of the above approach:
Python3
# Python Program to implement# the above approach # Recursive Function to find the# Maximal Independent Vertex Set def graphSets(graph): # Base Case - Given Graph # has no nodes if(len(graph) == 0): return [] # Base Case - Given Graph # has 1 node if(len(graph) == 1): return [list(graph.keys())[0]] # Select a vertex from the graph vCurrent = list(graph.keys())[0] # Case 1 - Proceed removing # the selected vertex # from the Maximal Set graph2 = dict(graph) # Delete current vertex # from the Graph del graph2[vCurrent] # Recursive call - Gets # Maximal Set, # assuming current Vertex # not selected res1 = graphSets(graph2) # Case 2 - Proceed considering # the selected vertex as part # of the Maximal Set # Loop through its neighbours for v in graph[vCurrent]: # Delete neighbor from # the current subgraph if(v in graph2): del graph2[v] # This result set contains VFirst, # and the result of recursive # call assuming neighbors of vFirst # are not selected res2 = [vCurrent] + graphSets(graph2) # Our final result is the one # which is bigger, return it if(len(res1) > len(res2)): return res1 return res2 # Driver CodeV = 8 # Defines edgesE = [ (1, 2), (1, 3), (2, 4), (5, 6), (6, 7), (4, 8)] graph = dict([]) # Constructs Graph as a dictionary # of the following format- # graph[VertexNumber V] # = list[Neighbors of Vertex V]for i in range(len(E)): v1, v2 = E[i] if(v1 not in graph): graph[v1] = [] if(v2 not in graph): graph[v2] = [] graph[v1].append(v2) graph[v2].append(v1) # Recursive call considering # all vertices in the maximum # independent setmaximalIndependentSet = graphSets(graph) # Prints the Result for i in maximalIndependentSet: print(i, end =" ")
2 3 8 5 7
Time Complexity: O(2N)Auxiliary Space: O(N)
Backtracking
Graph
Recursion
Recursion
Graph
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
The Knight's tour problem | Backtracking-1
Generate all the binary strings of N bits
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Find if there is a path between two vertices in a directed graph
Graph and its representations | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jul, 2020"
},
{
"code": null,
"e": 183,
"s": 28,
"text": "Given an undirected graph defined by the number of vertex V and the edges E[ ], the task is to find Maximal Independent Vertex Set in an undirected graph."
},
{
"code": null,
"e": 299,
"s": 183,
"text": "Independent Set: An independent set in a graph is a set of vertices which are not directly connected to each other."
},
{
"code": null,
"e": 447,
"s": 299,
"text": "Note: It is a given that there is at least one way to traverse from any vertex in the graph to another, i.e. the graph has one connected component."
},
{
"code": null,
"e": 457,
"s": 447,
"text": "Examples:"
},
{
"code": null,
"e": 656,
"s": 457,
"text": "Input: V = 3, E = { (1, 2), (2, 3) }Output: {1, 3}Explanation:Since there are no edges between 1 and 3, and we cannot add 2 to this since it is a neighbour of 1, this is the Maximal Independent Set."
},
{
"code": null,
"e": 747,
"s": 656,
"text": "Input: V = 8,E = { (1, 2), (1, 3), (2, 4), (5, 6), (6, 7), (4, 8) }Output: {2, 3, 5, 7, 8}"
},
{
"code": null,
"e": 899,
"s": 747,
"text": "Approach:This problem is an NP-Hard problem, which can only be solved in exponential time(as of right now).Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1038,
"s": 899,
"text": "Iterate through the vertices of the graph and use backtracking to check if a vertex can be included in the Maximal Independent Set or not."
},
{
"code": null,
"e": 1145,
"s": 1038,
"text": "Two possibilities arise for each vertex, whether it can be included or not in the maximal independent set."
},
{
"code": null,
"e": 1391,
"s": 1145,
"text": "Initially start, considering all vertices and edges. One by one, select a vertex. Remove that vertex from the graph, excluding it from the maximal independent set, and recursively traverse the remaining graph to find the maximal independent set."
},
{
"code": null,
"e": 1578,
"s": 1391,
"text": "Otherwise, consider the selected vertex in the maximal independent set and remove all its neighbors from it. Proceed to find the maximal independent set possible excluding its neighbors."
},
{
"code": null,
"e": 1663,
"s": 1578,
"text": "Repeat this process for all vertices and print the maximal independent set obtained."
},
{
"code": null,
"e": 1714,
"s": 1663,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1722,
"s": 1714,
"text": "Python3"
},
{
"code": "# Python Program to implement# the above approach # Recursive Function to find the# Maximal Independent Vertex Set def graphSets(graph): # Base Case - Given Graph # has no nodes if(len(graph) == 0): return [] # Base Case - Given Graph # has 1 node if(len(graph) == 1): return [list(graph.keys())[0]] # Select a vertex from the graph vCurrent = list(graph.keys())[0] # Case 1 - Proceed removing # the selected vertex # from the Maximal Set graph2 = dict(graph) # Delete current vertex # from the Graph del graph2[vCurrent] # Recursive call - Gets # Maximal Set, # assuming current Vertex # not selected res1 = graphSets(graph2) # Case 2 - Proceed considering # the selected vertex as part # of the Maximal Set # Loop through its neighbours for v in graph[vCurrent]: # Delete neighbor from # the current subgraph if(v in graph2): del graph2[v] # This result set contains VFirst, # and the result of recursive # call assuming neighbors of vFirst # are not selected res2 = [vCurrent] + graphSets(graph2) # Our final result is the one # which is bigger, return it if(len(res1) > len(res2)): return res1 return res2 # Driver CodeV = 8 # Defines edgesE = [ (1, 2), (1, 3), (2, 4), (5, 6), (6, 7), (4, 8)] graph = dict([]) # Constructs Graph as a dictionary # of the following format- # graph[VertexNumber V] # = list[Neighbors of Vertex V]for i in range(len(E)): v1, v2 = E[i] if(v1 not in graph): graph[v1] = [] if(v2 not in graph): graph[v2] = [] graph[v1].append(v2) graph[v2].append(v1) # Recursive call considering # all vertices in the maximum # independent setmaximalIndependentSet = graphSets(graph) # Prints the Result for i in maximalIndependentSet: print(i, end =\" \")",
"e": 3700,
"s": 1722,
"text": null
},
{
"code": null,
"e": 3711,
"s": 3700,
"text": "2 3 8 5 7\n"
},
{
"code": null,
"e": 3755,
"s": 3711,
"text": "Time Complexity: O(2N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 3768,
"s": 3755,
"text": "Backtracking"
},
{
"code": null,
"e": 3774,
"s": 3768,
"text": "Graph"
},
{
"code": null,
"e": 3784,
"s": 3774,
"text": "Recursion"
},
{
"code": null,
"e": 3794,
"s": 3784,
"text": "Recursion"
},
{
"code": null,
"e": 3800,
"s": 3794,
"text": "Graph"
},
{
"code": null,
"e": 3813,
"s": 3800,
"text": "Backtracking"
},
{
"code": null,
"e": 3911,
"s": 3813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3939,
"s": 3911,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 3982,
"s": 3939,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 4024,
"s": 3982,
"text": "Generate all the binary strings of N bits"
},
{
"code": null,
"e": 4060,
"s": 4024,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 4095,
"s": 4060,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 4135,
"s": 4095,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 4173,
"s": 4135,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 4238,
"s": 4173,
"text": "Find if there is a path between two vertices in a directed graph"
}
] |
How to overlay one div over another div using CSS | 13 Jun, 2022
Creating an overlay effect simply means putting two div together at the same place but both the div appear when needed i.e while hovering or while clicking on one of the div to make the second one appear. Overlays are very clean and give the webpage a tidy look. It looks sophisticated and is simple to design. Overlays can create using two simple CSS properties:
z-index
position
Example 1:
HTML
<!DOCTYPE html><html> <head> <title>overlay div</title> <style> .geeks { position: absolute; justify-content: center; text-align: center; align-items: center; height: 250px; width: 500px; background-color: rgb(36, 168, 36); } .gfg1 { margin-top: 80px; color: white; font-size: 40px; font-weight: bold; } .gfg2{ font-size: 20px; } </style></head> <body> <div class="geeks"> <div class="gfg1">GeeksforGeeks</div> <div class="gfg2">A computer science portal for geeks</div> </div> </body> </html>
Output:
Note: Customize the overlay effects by adding more CSS to the page to make it look more elegant.
Example 2:
HTML
<!DOCTYPE html><html> <head> <title>overlay div</title> <style> .geeks { position: absolute; justify-content: center; text-align: center; align-items: center; height: 250px; width: 500px; background-color: rgb(36, 168, 36); font-size: 20px; } .gfg1 { margin-top: 80px; color: white; font-size: 40px; font-weight: bold; } .gfg1:hover { z-index: -1; opacity: 0.5; font-size: 20px; text-align: center; transform-style: all; transition-duration: 1s; } .gfg2:hover { z-index: -1; font-size: 40px; text-align: center; transform-style: all; transition-duration: 1s; } </style></head> <body> <div class="geeks"> <div class="gfg1">GeeksforGeeks</div> <div class="gfg2">A computer science portal for geeks</div> </div> </body> </html>
Output:
Before hovering:
After hovering:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML is the foundation of web pages and 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.
CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
sanjyotpanure
CSS-Misc
Picked
Technical Scripter 2018
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 418,
"s": 54,
"text": "Creating an overlay effect simply means putting two div together at the same place but both the div appear when needed i.e while hovering or while clicking on one of the div to make the second one appear. Overlays are very clean and give the webpage a tidy look. It looks sophisticated and is simple to design. Overlays can create using two simple CSS properties:"
},
{
"code": null,
"e": 426,
"s": 418,
"text": "z-index"
},
{
"code": null,
"e": 435,
"s": 426,
"text": "position"
},
{
"code": null,
"e": 446,
"s": 435,
"text": "Example 1:"
},
{
"code": null,
"e": 451,
"s": 446,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>overlay div</title> <style> .geeks { position: absolute; justify-content: center; text-align: center; align-items: center; height: 250px; width: 500px; background-color: rgb(36, 168, 36); } .gfg1 { margin-top: 80px; color: white; font-size: 40px; font-weight: bold; } .gfg2{ font-size: 20px; } </style></head> <body> <div class=\"geeks\"> <div class=\"gfg1\">GeeksforGeeks</div> <div class=\"gfg2\">A computer science portal for geeks</div> </div> </body> </html>",
"e": 1165,
"s": 451,
"text": null
},
{
"code": null,
"e": 1173,
"s": 1165,
"text": "Output:"
},
{
"code": null,
"e": 1272,
"s": 1175,
"text": "Note: Customize the overlay effects by adding more CSS to the page to make it look more elegant."
},
{
"code": null,
"e": 1283,
"s": 1272,
"text": "Example 2:"
},
{
"code": null,
"e": 1288,
"s": 1283,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>overlay div</title> <style> .geeks { position: absolute; justify-content: center; text-align: center; align-items: center; height: 250px; width: 500px; background-color: rgb(36, 168, 36); font-size: 20px; } .gfg1 { margin-top: 80px; color: white; font-size: 40px; font-weight: bold; } .gfg1:hover { z-index: -1; opacity: 0.5; font-size: 20px; text-align: center; transform-style: all; transition-duration: 1s; } .gfg2:hover { z-index: -1; font-size: 40px; text-align: center; transform-style: all; transition-duration: 1s; } </style></head> <body> <div class=\"geeks\"> <div class=\"gfg1\">GeeksforGeeks</div> <div class=\"gfg2\">A computer science portal for geeks</div> </div> </body> </html>",
"e": 2361,
"s": 1288,
"text": null
},
{
"code": null,
"e": 2369,
"s": 2361,
"text": "Output:"
},
{
"code": null,
"e": 2386,
"s": 2369,
"text": "Before hovering:"
},
{
"code": null,
"e": 2404,
"s": 2388,
"text": "After hovering:"
},
{
"code": null,
"e": 2445,
"s": 2408,
"text": "Supported Browsers are listed below:"
},
{
"code": null,
"e": 2459,
"s": 2445,
"text": "Google Chrome"
},
{
"code": null,
"e": 2477,
"s": 2459,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2485,
"s": 2477,
"text": "Firefox"
},
{
"code": null,
"e": 2491,
"s": 2485,
"text": "Opera"
},
{
"code": null,
"e": 2498,
"s": 2491,
"text": "Safari"
},
{
"code": null,
"e": 2697,
"s": 2498,
"text": "HTML is the foundation of web pages and 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": 2888,
"s": 2697,
"text": "CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 2902,
"s": 2888,
"text": "sanjyotpanure"
},
{
"code": null,
"e": 2911,
"s": 2902,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2918,
"s": 2911,
"text": "Picked"
},
{
"code": null,
"e": 2942,
"s": 2918,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2946,
"s": 2942,
"text": "CSS"
},
{
"code": null,
"e": 2951,
"s": 2946,
"text": "HTML"
},
{
"code": null,
"e": 2970,
"s": 2951,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2987,
"s": 2970,
"text": "Web Technologies"
},
{
"code": null,
"e": 2992,
"s": 2987,
"text": "HTML"
}
] |
Moore and Mealy machines to count number of substring ‘ab’ | 20 Nov, 2019
Prerequisite: Mealy and Moore Machines, Difference between Mealy machine and Moore machineProblem: Construction of the machines that take set of all string over {a, b} as input and count number of substring ‘ab’Assume,
Ε = {a, b} and
Δ = {0, 1}
where Ε and Δ are the input and output alphabet respectively.
Explanation:The required Moore machine is constructed below.
In the above diagram, the initial state ‘X’ on getting ‘b’ as the input it remains in the state of itself and print ‘0’ as the output and on getting ‘a’ as the input it transits to a state ‘Y’ and prints ‘0’ as the output.
The state ‘Y’ on getting ‘a’ as the input it remains in the state of itself and prints ‘0’ as the output and on getting ‘b’ as the input it transmits to the state ‘Z’ and prints ‘1’ as the output. The state ‘Z’ on getting ‘a’ as the input it transmits to the state ‘Y’ and prints ‘0’ as the output and on getting ‘b’ as the input it transmits to the state ‘X’ and prints ‘0’ as the output.
Thus finally above Moore machine can easily count the number of substring ‘ab’ i.e, on getting ‘ab’ as the input it gives ‘1’ as the output thus on counting the outputs ‘1’, we can easily count substring ‘ab’.
Conversion of Moore machine to Mealy machine:Above Moore machine takes set of all string over {a, b} as input and prints ‘1’ as the output for every occurrence of ‘ab’ as substring. Now we need to transform the above transition diagram of Moore machine to equivalent Mealy machine transition diagram.
Steps for the required conversion are given below:
Step-1: Formation of State Transition Table of the above Moore machine-In the above transition table, States ‘X’, ‘Y’ and ‘Z’ are kept in the first column which on getting ‘a’ as the input it transits to ‘Y’, ‘Y’ and ‘Y’ states respectively, kept in the second column and on getting ‘b’ as the input it transits to ‘X’, ‘Z’ and ‘X’ states respectively, kept in the third column. In the fourth column under Δ, there are corresponding outputs of the first column states. In the table, An arrow (→) indicates the initial state.
Step-2: Formation of Transition Table for Mealy machine from above Transition Table of Moore machine-Below transition table is going to be formed with the help of the above table and its entries just by using the corresponding output of the states of the first column and placing them in the second and third column accordingly.In the above table, the states in the first column like ‘X’ on getting ‘a’ as the input it goes to a state ‘Y’ and gives ‘0’ as the output and on getting ‘b’ as the input it goes to the state ‘X’ and gives ‘0’ as the output and so on for the remaining states in the first column. In the table, An arrow (→) indicates the initial state.
Step-3: Then finally we can form the state transition diagram of Mealy machine with help of it’s above transition table.The required diagram is shown below-Above Mealy machine takes set of all string over {a, b} as input and prints ‘1’ as the output for every occurrence of ‘ab’ as a substring.
Note: While converting from Moore to Mealy machine the number of states remains same for both Moore and Mealy machine but in case of Mealy to Moore conversion it do not give same number of states.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 247,
"s": 28,
"text": "Prerequisite: Mealy and Moore Machines, Difference between Mealy machine and Moore machineProblem: Construction of the machines that take set of all string over {a, b} as input and count number of substring ‘ab’Assume,"
},
{
"code": null,
"e": 275,
"s": 247,
"text": "Ε = {a, b} and \nΔ = {0, 1} "
},
{
"code": null,
"e": 337,
"s": 275,
"text": "where Ε and Δ are the input and output alphabet respectively."
},
{
"code": null,
"e": 398,
"s": 337,
"text": "Explanation:The required Moore machine is constructed below."
},
{
"code": null,
"e": 621,
"s": 398,
"text": "In the above diagram, the initial state ‘X’ on getting ‘b’ as the input it remains in the state of itself and print ‘0’ as the output and on getting ‘a’ as the input it transits to a state ‘Y’ and prints ‘0’ as the output."
},
{
"code": null,
"e": 1011,
"s": 621,
"text": "The state ‘Y’ on getting ‘a’ as the input it remains in the state of itself and prints ‘0’ as the output and on getting ‘b’ as the input it transmits to the state ‘Z’ and prints ‘1’ as the output. The state ‘Z’ on getting ‘a’ as the input it transmits to the state ‘Y’ and prints ‘0’ as the output and on getting ‘b’ as the input it transmits to the state ‘X’ and prints ‘0’ as the output."
},
{
"code": null,
"e": 1221,
"s": 1011,
"text": "Thus finally above Moore machine can easily count the number of substring ‘ab’ i.e, on getting ‘ab’ as the input it gives ‘1’ as the output thus on counting the outputs ‘1’, we can easily count substring ‘ab’."
},
{
"code": null,
"e": 1522,
"s": 1221,
"text": "Conversion of Moore machine to Mealy machine:Above Moore machine takes set of all string over {a, b} as input and prints ‘1’ as the output for every occurrence of ‘ab’ as substring. Now we need to transform the above transition diagram of Moore machine to equivalent Mealy machine transition diagram."
},
{
"code": null,
"e": 1573,
"s": 1522,
"text": "Steps for the required conversion are given below:"
},
{
"code": null,
"e": 2098,
"s": 1573,
"text": "Step-1: Formation of State Transition Table of the above Moore machine-In the above transition table, States ‘X’, ‘Y’ and ‘Z’ are kept in the first column which on getting ‘a’ as the input it transits to ‘Y’, ‘Y’ and ‘Y’ states respectively, kept in the second column and on getting ‘b’ as the input it transits to ‘X’, ‘Z’ and ‘X’ states respectively, kept in the third column. In the fourth column under Δ, there are corresponding outputs of the first column states. In the table, An arrow (→) indicates the initial state."
},
{
"code": null,
"e": 2762,
"s": 2098,
"text": "Step-2: Formation of Transition Table for Mealy machine from above Transition Table of Moore machine-Below transition table is going to be formed with the help of the above table and its entries just by using the corresponding output of the states of the first column and placing them in the second and third column accordingly.In the above table, the states in the first column like ‘X’ on getting ‘a’ as the input it goes to a state ‘Y’ and gives ‘0’ as the output and on getting ‘b’ as the input it goes to the state ‘X’ and gives ‘0’ as the output and so on for the remaining states in the first column. In the table, An arrow (→) indicates the initial state."
},
{
"code": null,
"e": 3057,
"s": 2762,
"text": "Step-3: Then finally we can form the state transition diagram of Mealy machine with help of it’s above transition table.The required diagram is shown below-Above Mealy machine takes set of all string over {a, b} as input and prints ‘1’ as the output for every occurrence of ‘ab’ as a substring."
},
{
"code": null,
"e": 3254,
"s": 3057,
"text": "Note: While converting from Moore to Mealy machine the number of states remains same for both Moore and Mealy machine but in case of Mealy to Moore conversion it do not give same number of states."
},
{
"code": null,
"e": 3262,
"s": 3254,
"text": "GATE CS"
},
{
"code": null,
"e": 3295,
"s": 3262,
"text": "Theory of Computation & Automata"
}
] |
Implementing Checksum Using Java | 31 May, 2022
The checksum is an error-detecting technique that can be applied to message of any length. It is used mostly at the network and transport layers of the TCP/IP protocol suite. Here, we have considered decimal data that is being sent by the sender to the receiver using socket programming. The number of segments that the data is divided into here depends on the length of data being sent. If the length of data being sent is ‘x’, then the number of segments is also ‘x’, implying that each segment has single data. Here, we basically deal with decimal data. The concept will be consistent for string data as well because each character of the string can be represented by its equivalent ASCII code, hence again leaving us with decimal data.
Prerequisite: Socket Programming in Java | CheckSum
Example :
At sender side :
Enter data length
4
Enter data to send
67
43
0
22
Checksum Calculated is : 90
Data being sent along with Checksum.....
Thanks for the feedback!!
Message received Successfully!
At receiver side :
Data received (along with checksum) is
67
43
0
22
90
Sum(in ones complement) is : 127
Calculated Checksum is : 0
Here the checksum calculated at
the receiver side was 0. Hence,
it indicates a successful data transfer.
Approach :
At the Sender Side :
First, ask for the length of data to send, in order to ascertain the number of segments.Then perform one complement of each data being entered simultaneously adding them. This means the sum would not be required to be complimented again.Then send the data along with the computed checksum to the server.Then report the successful transference of the message or otherwise depending on the feedback received from the server.
First, ask for the length of data to send, in order to ascertain the number of segments.
Then perform one complement of each data being entered simultaneously adding them. This means the sum would not be required to be complimented again.
Then send the data along with the computed checksum to the server.
Then report the successful transference of the message or otherwise depending on the feedback received from the server.
At the Receiver Side :
The receiver waits for data to arrive from the sender.Once the data along with checksum is received from the sender, the receiver complements what is received and simultaneously keeps on adding them.Finally, the receiver complements the above sum and checks whether the result is a zero or not, and reports the same to the sender. A zero would indicate a successful data transfer and anything else would indicate an error in the data that is received.
The receiver waits for data to arrive from the sender.
Once the data along with checksum is received from the sender, the receiver complements what is received and simultaneously keeps on adding them.
Finally, the receiver complements the above sum and checks whether the result is a zero or not, and reports the same to the sender. A zero would indicate a successful data transfer and anything else would indicate an error in the data that is received.
Finally, all connections are closed by both sides.
Below is the implementation for the above approach.
Here, “localhost” is used as the IP to set up the connection with port number 5000 opened for connection. The sender should start running prior and wait for the receiver.
Java
// Java code for Checksum_Senderpackage checksum_sender; import java.io.*;import java.net.*;import java.util.*; public class Checksum_Sender{ // Setting maximum data length private int MAX = 100; // initialize socket and I/O streams private Socket socket = null; private ServerSocket servsock = null; private DataInputStream dis = null; private DataOutputStream dos = null; public Checksum_Sender(int port) throws IOException { servsock = new ServerSocket(port); // Used to block until a client connects to the server socket = servsock.accept(); dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); while (true) { int i, l, sum = 0, nob; Scanner sc = new Scanner(System.in); System.out.println("Enter data length"); l = sc.nextInt(); // Array to hold the data being entered int data[] = new int[MAX]; // Array to hold the complement of each data int c_data[] = new int[MAX]; System.out.println("Enter data to send"); for (i = 0; i < l; i++) { data[i] = sc.nextInt(); // Complementing the entered data // Here we find the number of bits required to represent // the data, like say 8 requires 1000, i.e 4 bits nob = (int)(Math.floor(Math.log(data[i]) / Math.log(2))) + 1; // Here we do a XOR of the data with the number 2^n -1, // where n is the nob calculated in previous step c_data[i] = ((1 << nob) - 1) ^ data[i]; // Adding the complemented data and storing in sum sum += c_data[i]; } // The sum(i.e checksum) is also sent along with the data data[i] = sum; l += 1; System.out.println("Checksum Calculated is : " + sum); System.out.println("Data being sent along with Checksum....."); // Sends the data length to receiver dos.writeInt(l); // Sends the data one by one to receiver for (int j = 0; j < l; j++) dos.writeInt(data[j]); // Displaying appropriate message depending on feedback received if (dis.readUTF().equals("success")) { System.out.println("Thanks for the feedback!! Message received Successfully!"); break; } else if (dis.readUTF().equals("failure")) { System.out.println("Message was not received successfully!"); break; } } // Closing all connections dis.close(); dos.close(); socket.close(); } // Driver Method public static void main(String args[]) throws IOException { Checksum_Sender cs = new Checksum_Sender(45678); }}
Java
// Java code for Checksum_Receiverpackage checksum_sender; import java.net.*;import java.io.*;import java.util.*; public class Checksum_Receiver { // Initialize socket and I/O streams private Socket s = null; private DataInputStream dis = null; private DataOutputStream dos = null; // Constructor to put ip address and port public Checksum_Receiver(InetAddress ip,int port)throws IOException { // Opens a socket for connection s = new Socket(ip,port); dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); while (true) { Scanner sc = new Scanner(System.in); int i, l, nob, sum = 0, chk_sum; // Reads the data length sent by sender l = dis.readInt(); // Initializes the arrays based on data length received int c_data[] = new int[l]; int data[] = new int[l]; System.out.println("Data received (along with checksum) is"); for(i = 0; i< data.length; i++) { // Reading the data being sent one by one data[i] = dis.readInt(); System.out.println(data[i]); // Complementing the data being received nob = (int)(Math.floor(Math.log(data[i]) / Math.log(2))) + 1; c_data[i] = ((1 << nob) - 1) ^ data[i]; // Adding the complemented data sum += c_data[i]; } System.out.println("Sum(in ones complement) is : "+sum); // Complementing the sum nob = (int)(Math.floor(Math.log(sum) / Math.log(2))) + 1; sum = ((1 << nob) - 1) ^ sum; System.out.println("Calculated Checksum is : "+sum); // Checking whether final result is 0 or something else // and sending feedback accordingly if(sum == 0) { dos.writeUTF("success"); break; } else { dos.writeUTF("failure"); break; } } // Closing all connections dis.close(); dos.close(); s.close(); } // Driver Method public static void main(String args[])throws IOException { // Getting ip address on which the receiver is running // Here, it is "localhost" InetAddress ip = InetAddress.getLocalHost(); Checksum_Receiver cr = new Checksum_Receiver(ip,5000); } }
Output:
surinderdawra388
vaibhavsinghtanwar
Java - util package
Java-Networking
Computer Networks
Java
Java Programs
Java
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 768,
"s": 28,
"text": "The checksum is an error-detecting technique that can be applied to message of any length. It is used mostly at the network and transport layers of the TCP/IP protocol suite. Here, we have considered decimal data that is being sent by the sender to the receiver using socket programming. The number of segments that the data is divided into here depends on the length of data being sent. If the length of data being sent is ‘x’, then the number of segments is also ‘x’, implying that each segment has single data. Here, we basically deal with decimal data. The concept will be consistent for string data as well because each character of the string can be represented by its equivalent ASCII code, hence again leaving us with decimal data."
},
{
"code": null,
"e": 820,
"s": 768,
"text": "Prerequisite: Socket Programming in Java | CheckSum"
},
{
"code": null,
"e": 831,
"s": 820,
"text": "Example : "
},
{
"code": null,
"e": 1266,
"s": 831,
"text": "At sender side :\nEnter data length\n4\nEnter data to send\n67\n43\n0\n22\nChecksum Calculated is : 90\nData being sent along with Checksum.....\nThanks for the feedback!! \nMessage received Successfully! \nAt receiver side :\nData received (along with checksum) is\n67\n43\n0\n22\n90\nSum(in ones complement) is : 127\nCalculated Checksum is : 0\n\nHere the checksum calculated at \nthe receiver side was 0. Hence, \nit indicates a successful data transfer."
},
{
"code": null,
"e": 1278,
"s": 1266,
"text": "Approach : "
},
{
"code": null,
"e": 1300,
"s": 1278,
"text": "At the Sender Side : "
},
{
"code": null,
"e": 1723,
"s": 1300,
"text": "First, ask for the length of data to send, in order to ascertain the number of segments.Then perform one complement of each data being entered simultaneously adding them. This means the sum would not be required to be complimented again.Then send the data along with the computed checksum to the server.Then report the successful transference of the message or otherwise depending on the feedback received from the server."
},
{
"code": null,
"e": 1812,
"s": 1723,
"text": "First, ask for the length of data to send, in order to ascertain the number of segments."
},
{
"code": null,
"e": 1962,
"s": 1812,
"text": "Then perform one complement of each data being entered simultaneously adding them. This means the sum would not be required to be complimented again."
},
{
"code": null,
"e": 2029,
"s": 1962,
"text": "Then send the data along with the computed checksum to the server."
},
{
"code": null,
"e": 2149,
"s": 2029,
"text": "Then report the successful transference of the message or otherwise depending on the feedback received from the server."
},
{
"code": null,
"e": 2172,
"s": 2149,
"text": "At the Receiver Side :"
},
{
"code": null,
"e": 2624,
"s": 2172,
"text": "The receiver waits for data to arrive from the sender.Once the data along with checksum is received from the sender, the receiver complements what is received and simultaneously keeps on adding them.Finally, the receiver complements the above sum and checks whether the result is a zero or not, and reports the same to the sender. A zero would indicate a successful data transfer and anything else would indicate an error in the data that is received."
},
{
"code": null,
"e": 2679,
"s": 2624,
"text": "The receiver waits for data to arrive from the sender."
},
{
"code": null,
"e": 2825,
"s": 2679,
"text": "Once the data along with checksum is received from the sender, the receiver complements what is received and simultaneously keeps on adding them."
},
{
"code": null,
"e": 3078,
"s": 2825,
"text": "Finally, the receiver complements the above sum and checks whether the result is a zero or not, and reports the same to the sender. A zero would indicate a successful data transfer and anything else would indicate an error in the data that is received."
},
{
"code": null,
"e": 3129,
"s": 3078,
"text": "Finally, all connections are closed by both sides."
},
{
"code": null,
"e": 3182,
"s": 3129,
"text": "Below is the implementation for the above approach. "
},
{
"code": null,
"e": 3355,
"s": 3182,
"text": "Here, “localhost” is used as the IP to set up the connection with port number 5000 opened for connection. The sender should start running prior and wait for the receiver. "
},
{
"code": null,
"e": 3360,
"s": 3355,
"text": "Java"
},
{
"code": "// Java code for Checksum_Senderpackage checksum_sender; import java.io.*;import java.net.*;import java.util.*; public class Checksum_Sender{ // Setting maximum data length private int MAX = 100; // initialize socket and I/O streams private Socket socket = null; private ServerSocket servsock = null; private DataInputStream dis = null; private DataOutputStream dos = null; public Checksum_Sender(int port) throws IOException { servsock = new ServerSocket(port); // Used to block until a client connects to the server socket = servsock.accept(); dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); while (true) { int i, l, sum = 0, nob; Scanner sc = new Scanner(System.in); System.out.println(\"Enter data length\"); l = sc.nextInt(); // Array to hold the data being entered int data[] = new int[MAX]; // Array to hold the complement of each data int c_data[] = new int[MAX]; System.out.println(\"Enter data to send\"); for (i = 0; i < l; i++) { data[i] = sc.nextInt(); // Complementing the entered data // Here we find the number of bits required to represent // the data, like say 8 requires 1000, i.e 4 bits nob = (int)(Math.floor(Math.log(data[i]) / Math.log(2))) + 1; // Here we do a XOR of the data with the number 2^n -1, // where n is the nob calculated in previous step c_data[i] = ((1 << nob) - 1) ^ data[i]; // Adding the complemented data and storing in sum sum += c_data[i]; } // The sum(i.e checksum) is also sent along with the data data[i] = sum; l += 1; System.out.println(\"Checksum Calculated is : \" + sum); System.out.println(\"Data being sent along with Checksum.....\"); // Sends the data length to receiver dos.writeInt(l); // Sends the data one by one to receiver for (int j = 0; j < l; j++) dos.writeInt(data[j]); // Displaying appropriate message depending on feedback received if (dis.readUTF().equals(\"success\")) { System.out.println(\"Thanks for the feedback!! Message received Successfully!\"); break; } else if (dis.readUTF().equals(\"failure\")) { System.out.println(\"Message was not received successfully!\"); break; } } // Closing all connections dis.close(); dos.close(); socket.close(); } // Driver Method public static void main(String args[]) throws IOException { Checksum_Sender cs = new Checksum_Sender(45678); }}",
"e": 6586,
"s": 3360,
"text": null
},
{
"code": null,
"e": 6591,
"s": 6586,
"text": "Java"
},
{
"code": "// Java code for Checksum_Receiverpackage checksum_sender; import java.net.*;import java.io.*;import java.util.*; public class Checksum_Receiver { // Initialize socket and I/O streams private Socket s = null; private DataInputStream dis = null; private DataOutputStream dos = null; // Constructor to put ip address and port public Checksum_Receiver(InetAddress ip,int port)throws IOException { // Opens a socket for connection s = new Socket(ip,port); dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); while (true) { Scanner sc = new Scanner(System.in); int i, l, nob, sum = 0, chk_sum; // Reads the data length sent by sender l = dis.readInt(); // Initializes the arrays based on data length received int c_data[] = new int[l]; int data[] = new int[l]; System.out.println(\"Data received (along with checksum) is\"); for(i = 0; i< data.length; i++) { // Reading the data being sent one by one data[i] = dis.readInt(); System.out.println(data[i]); // Complementing the data being received nob = (int)(Math.floor(Math.log(data[i]) / Math.log(2))) + 1; c_data[i] = ((1 << nob) - 1) ^ data[i]; // Adding the complemented data sum += c_data[i]; } System.out.println(\"Sum(in ones complement) is : \"+sum); // Complementing the sum nob = (int)(Math.floor(Math.log(sum) / Math.log(2))) + 1; sum = ((1 << nob) - 1) ^ sum; System.out.println(\"Calculated Checksum is : \"+sum); // Checking whether final result is 0 or something else // and sending feedback accordingly if(sum == 0) { dos.writeUTF(\"success\"); break; } else { dos.writeUTF(\"failure\"); break; } } // Closing all connections dis.close(); dos.close(); s.close(); } // Driver Method public static void main(String args[])throws IOException { // Getting ip address on which the receiver is running // Here, it is \"localhost\" InetAddress ip = InetAddress.getLocalHost(); Checksum_Receiver cr = new Checksum_Receiver(ip,5000); } }",
"e": 9267,
"s": 6591,
"text": null
},
{
"code": null,
"e": 9276,
"s": 9267,
"text": "Output: "
},
{
"code": null,
"e": 9295,
"s": 9278,
"text": "surinderdawra388"
},
{
"code": null,
"e": 9314,
"s": 9295,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 9334,
"s": 9314,
"text": "Java - util package"
},
{
"code": null,
"e": 9350,
"s": 9334,
"text": "Java-Networking"
},
{
"code": null,
"e": 9368,
"s": 9350,
"text": "Computer Networks"
},
{
"code": null,
"e": 9373,
"s": 9368,
"text": "Java"
},
{
"code": null,
"e": 9387,
"s": 9373,
"text": "Java Programs"
},
{
"code": null,
"e": 9392,
"s": 9387,
"text": "Java"
},
{
"code": null,
"e": 9410,
"s": 9392,
"text": "Computer Networks"
}
] |
JavaScript | Function expression | 08 Oct, 2021
Function Expression allows us to create an anonymous function which doesn’t have any function name which is the main difference between Function Expression and Function Declaration. A function expression can be used as an IIFE (Immediately Invoked Function Expression)which runs as soon as it is defined. A function expression has to be stored in a variable and can be accessed using variableName. With the ES6 features introducing Arrow Function, it becomes more easier to declare function expression.
Syntax for Function Declaration:
function functionName(x, y) { statements... return (z) };
Syntax for Function Expression (anonymous) :
let variableName = function(x, y) { statements... return (z) };
Syntax for Function Expression (named) :
let variableName = function functionName(x, y)
{ statements... return (z) };
Syntax for Arrow Function:
let variableName = (x, y) => { statements... return (z) };
Note:
A function expression has to be defined first before calling it or using it as a parameter.
An arrow function must have an return statement.
Below examples illustrate the function expression in JavaScript:
Example 1: Code for Function Declaration.
Javascript
<script> function callAdd(x, y){ let z = x + y; return z; } console.log("Addition : " + callAdd(7, 4));</script>
Output:
Addition : 11
Example 2: Code for Function Expression (anonymous)
Javascript
<script> var calSub = function(x, y){ let z = x - y; return z; } console.log("Subtraction : " + calSub(7, 4)); </script>
Output:
Subtraction : 3
Example 3: Code for Function Expression (named)
Javascript
<script> var calMul = function Mul(x, y){ let z = x * y; return z; } console.log("Multiplication : " + calMul(7, 4));</script>
Output:
Multiplication : 28
Example 4: Code for Arrow Function
Javascript
<script> var calDiv = (x, y) => { let z = x / y; return z; } console.log("Division : " + calDiv(24, 4));</script>
Output:
Division : 6
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
simmytarika5
gulshankumarar231
surindertarika1234
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 533,
"s": 28,
"text": "Function Expression allows us to create an anonymous function which doesn’t have any function name which is the main difference between Function Expression and Function Declaration. A function expression can be used as an IIFE (Immediately Invoked Function Expression)which runs as soon as it is defined. A function expression has to be stored in a variable and can be accessed using variableName. With the ES6 features introducing Arrow Function, it becomes more easier to declare function expression."
},
{
"code": null,
"e": 567,
"s": 533,
"text": "Syntax for Function Declaration: "
},
{
"code": null,
"e": 625,
"s": 567,
"text": "function functionName(x, y) { statements... return (z) };"
},
{
"code": null,
"e": 672,
"s": 625,
"text": "Syntax for Function Expression (anonymous) : "
},
{
"code": null,
"e": 736,
"s": 672,
"text": "let variableName = function(x, y) { statements... return (z) };"
},
{
"code": null,
"e": 779,
"s": 736,
"text": "Syntax for Function Expression (named) : "
},
{
"code": null,
"e": 857,
"s": 779,
"text": "let variableName = function functionName(x, y) \n{ statements... return (z) };"
},
{
"code": null,
"e": 885,
"s": 857,
"text": "Syntax for Arrow Function: "
},
{
"code": null,
"e": 945,
"s": 885,
"text": "let variableName = (x, y) => { statements... return (z) }; "
},
{
"code": null,
"e": 952,
"s": 945,
"text": "Note: "
},
{
"code": null,
"e": 1044,
"s": 952,
"text": "A function expression has to be defined first before calling it or using it as a parameter."
},
{
"code": null,
"e": 1093,
"s": 1044,
"text": "An arrow function must have an return statement."
},
{
"code": null,
"e": 1158,
"s": 1093,
"text": "Below examples illustrate the function expression in JavaScript:"
},
{
"code": null,
"e": 1200,
"s": 1158,
"text": "Example 1: Code for Function Declaration."
},
{
"code": null,
"e": 1211,
"s": 1200,
"text": "Javascript"
},
{
"code": "<script> function callAdd(x, y){ let z = x + y; return z; } console.log(\"Addition : \" + callAdd(7, 4));</script>",
"e": 1350,
"s": 1211,
"text": null
},
{
"code": null,
"e": 1359,
"s": 1350,
"text": "Output: "
},
{
"code": null,
"e": 1373,
"s": 1359,
"text": "Addition : 11"
},
{
"code": null,
"e": 1426,
"s": 1373,
"text": "Example 2: Code for Function Expression (anonymous) "
},
{
"code": null,
"e": 1437,
"s": 1426,
"text": "Javascript"
},
{
"code": "<script> var calSub = function(x, y){ let z = x - y; return z; } console.log(\"Subtraction : \" + calSub(7, 4)); </script>",
"e": 1582,
"s": 1437,
"text": null
},
{
"code": null,
"e": 1591,
"s": 1582,
"text": "Output: "
},
{
"code": null,
"e": 1607,
"s": 1591,
"text": "Subtraction : 3"
},
{
"code": null,
"e": 1656,
"s": 1607,
"text": "Example 3: Code for Function Expression (named) "
},
{
"code": null,
"e": 1667,
"s": 1656,
"text": "Javascript"
},
{
"code": "<script> var calMul = function Mul(x, y){ let z = x * y; return z; } console.log(\"Multiplication : \" + calMul(7, 4));</script>",
"e": 1818,
"s": 1667,
"text": null
},
{
"code": null,
"e": 1827,
"s": 1818,
"text": "Output: "
},
{
"code": null,
"e": 1847,
"s": 1827,
"text": "Multiplication : 28"
},
{
"code": null,
"e": 1883,
"s": 1847,
"text": "Example 4: Code for Arrow Function "
},
{
"code": null,
"e": 1894,
"s": 1883,
"text": "Javascript"
},
{
"code": "<script> var calDiv = (x, y) => { let z = x / y; return z; } console.log(\"Division : \" + calDiv(24, 4));</script>",
"e": 2032,
"s": 1894,
"text": null
},
{
"code": null,
"e": 2041,
"s": 2032,
"text": "Output: "
},
{
"code": null,
"e": 2054,
"s": 2041,
"text": "Division : 6"
},
{
"code": null,
"e": 2073,
"s": 2054,
"text": "Supported Browser:"
},
{
"code": null,
"e": 2092,
"s": 2073,
"text": "Chrome 1 and above"
},
{
"code": null,
"e": 2110,
"s": 2092,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 2130,
"s": 2110,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 2160,
"s": 2130,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 2178,
"s": 2160,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 2197,
"s": 2178,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 2210,
"s": 2197,
"text": "simmytarika5"
},
{
"code": null,
"e": 2228,
"s": 2210,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 2247,
"s": 2228,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2259,
"s": 2247,
"text": "ysachin2314"
},
{
"code": null,
"e": 2280,
"s": 2259,
"text": "javascript-functions"
},
{
"code": null,
"e": 2291,
"s": 2280,
"text": "JavaScript"
},
{
"code": null,
"e": 2308,
"s": 2291,
"text": "Web Technologies"
}
] |
Resolving CUDA Being Out of Memory With Gradient Accumulation and AMP | by Rishik C. Mourya | Towards Data Science | Do you remember that delightful time, when you were so happily preprocessing your data, building your model with so many efforts, and then right at the moment when you expect to enjoy that soda while your model trains, an error pops up, telling you to get your butt down here again because you don’t have enough CUDA memory to enjoy? Well, I certainly can’t forget that, and this seriously is a really common issue among ML engineers. Alright then, let’s figure out if there’s a solution to our soda problem.
RuntimeError: CUDA error: out of memory
There’s nothing to explain actually, I mean the error message is already self-explanatory, but still, let’s have a quick brush up. The issue is, to train the model using GPU, you need the error between the labels and predictions, and for the error, you need to make predictions, and for making the predictions, you need both the model and the input data to be allocated in the CUDA memory. So when you try to execute the training, and you don’t have enough free CUDA memory available, then the framework you’re using throws this out of memory error.
So keeping that in mind, here are the common reasons why this error is so prone to occur:
When you’re model is big, by big I mean lot’s of parameters to train.
When you’re using such a model architecture that performs a lot of concatenation operations (in DenseNet). Or huge channels operations like additions (in ResNet)
When the size of your input data is too high. I don’t mean to say the size of data you have available, but the input size of single data instance, like in case of an image, it could be 3x224x224.
And finally, when you’re batch size is too high with respect to the dimensions of a data instance.
Now the issue is not that you can’t solve the problems above, I mean switching to a smaller model might take not more than 20 to 30 minutes, and decreasing the batch size is, of course, a piece of cake, and such solutions do solve issue for most of the cases, but at the cost of time and model’s accuracy.
For instance, if you set your batch size too low, then it might just take forever to make the loss converge because your model would be just oscillating too much, not only that, some model architectures don’t even perform well when batch size is not up to the requirements. And, if you decide to switch to a smaller model or reduce the dimensions of the input data, then you might just lose quite a lot of accuracy for obvious reasons.
So as you can see solving this error is not that hard to tackle, but its the cost of the solution which is too high for a good ML engineer.
Alright, so now it is pretty obvious that just one solution wouldn’t be enough to solve all of the above problems, in fact, a limited solution would only create even more problems. So after quite a lot of headaches I’ve finally came to these solutions, when applied together, do wonders :)
Gradient Accumulation.
Training with AMP(Automatic Mixed Precision).
Few of my own tricks.
Let’s have a look at them one by one.
This solution has been a de facto for solving out of memory issues. In fact, this is the very only reason why this technique exists in the first place. This technique solves the issue of model oscillation when the batch size is set too low. The nub here is actually very easy to understand.
The reason why model oscillates when batch size is too low is that the gradients are averages for less number of data instances. So after each training iteration (training a single batch), the model gets too specific updates, and thus parameters are changed too much towards a single direction. And reducing the learning rate would not be helpful here, in fact, it would just make the training even slower and just horrible because not only the updates are less generalized but with low magnitude too.
So the idea behind gradient accumulation is, keep adding gradients of the parameters for n number of batches, where batch size is small, and then after n batch iterations, apply the updates using the average of all those gradients accumulated over n iterations, that’s why its called gradient accumulation.
Below is the sample procedure for Pytorch implementation.
In the above example, note that we are dividing the loss by gradient_accumulations for keeping the scale of gradients same as if were training with 64 batch size. For an effective batch size of 64, ideally, we want to average over 64 gradients to apply the updates, so if we don’t divide by gradient_accumulations then we would be applying updates using an average of gradients over the batch size of 4 only, because we just kept adding the gradients for gradient_accumulations number of batch iterations before calling optimizer.step().
So, this technique effectively solves the problem of limited gradient averaging. Now mathematically we are totally good here, but the problem is the training time. As our batch size is really low, so definitely we are doing drastically less parallel computations as compared to high batch size.
And if you are accumulating the gradients for k batch iterations then it would approximately take k times the time for training with the batch size that you actually want. Let’s fix this.
Almost all of the deep learning frameworks operate on 32-bit floating-point or float32 data type by default. Though there are many operations the does not need to be this much precisely accurate.
3 years ago Nvidia researchers created a new methodology, that in a nutshell combines single-precision with the half-precision floating-point for training deep learning models, that achieves the same level of accuracy as float32.
It enables automatic conversion of certain GPU operations from float32 precision to mixed-precision, while improving performance and maintaining same accuracy. For an exact performance and accuracy comparisons make sure to check out Nvidia’s official benchmarks.
Main plus points of this method are:
Less training time.
Enabling larger batch sizes.
Larger models and large inputs.
Lower memory requirements.
So now you can see why I decided to combine AMP with gradient accumulation. Anyways, below is its Pytorch implementation.
I’ll let this paper Multi-Node BERT-Pretraining explain this to you
Typically in a computation graph, not all FP16 operators are numerically safe. This means operators that are considered numerically dangerous will have its calculation in full precision. For example, a plus operator is marked as safe while a 5 power or a log operator is considered numerically dangerous in half precision. Automated mixed precision handles the categorization of the numerical safety level through the rewriting of computation graph — Authors
For more info regarding different precisions, make sure to check out this brief article by non other than Nvidia.
So now, since we are set to use both of the techniques I’ve explained above, let’s put the together to come up with an awesome combo.
Yuppah, that’s pretty much it :)
Depending on the model and input sizes, and how much gradients you are accumulating, you could easily get somewhere around 1.2x to 1.5x (and sometimes even more) speed ups with AMP, and of course your loss would converge thanks to gradient accumulation.
Now for 95% of the times, you wouldn’t need to use techniques that I’m sharing here because AMP and gradient accumulation applied together works juuuuust fine. Though recently I’ve started working for a startup, where we are trying to detect violence in CCTV footages. This task basically is a video classification, where in a batch we would have to deal with one more dimension as compared to image classification, making total 5 dimensions of a single batch. So this definitely means massive input size.
I wanted to further speed up the training, cuz we had over 16GB of training data so speeding the things was definitely a requirement.
Here’s what I did.
Reducing the input data features. In my case I reduced the temporal dimensions to reasonable 28, rather than 36 as before. This not sound much of a decrease, but keep that in mind that a single step in temporal dimension in a video means covering 3 * 224 * 244 feature values... so in total I decreased over 1 million features :), not only that I also reduced the image size from 224 to reasonable 196.
Making classes distribution uniform over a batch. This is very simple actually, the idea is to make sure that every batch contains the same number of input data for every class. So in my case each batch always contained 4 non violence videos and 4 violence videos for batch size of 8. This would help to minimize the data imbalance (sort of, not 100%) that I had and finally improve the testing accuracy within same training time.
Yes, these ideas are not necessarily for solving the out of CUDA memory issue, but while applying these techniques, there was a well noticeable amount decrease in time for training, and helped me to get ahead by 3 training epochs where each epoch was approximately taking over 25 minutes.
So we saw how to use gradient accumulation and automatic mixed precision together to come out limited memory hell.
Gradient accumulation workouts the math and helps to solve the loss oscillation issue, but small batch size causes slower training
And this is where automatic mixed precision and few of my tweaks helps to speed up the whole training process.
Okie then, I hope after reading this article you’d be able to tackle out this really common issue and yeah, enjoy the soda. | [
{
"code": null,
"e": 681,
"s": 172,
"text": "Do you remember that delightful time, when you were so happily preprocessing your data, building your model with so many efforts, and then right at the moment when you expect to enjoy that soda while your model trains, an error pops up, telling you to get your butt down here again because you don’t have enough CUDA memory to enjoy? Well, I certainly can’t forget that, and this seriously is a really common issue among ML engineers. Alright then, let’s figure out if there’s a solution to our soda problem."
},
{
"code": null,
"e": 721,
"s": 681,
"text": "RuntimeError: CUDA error: out of memory"
},
{
"code": null,
"e": 1271,
"s": 721,
"text": "There’s nothing to explain actually, I mean the error message is already self-explanatory, but still, let’s have a quick brush up. The issue is, to train the model using GPU, you need the error between the labels and predictions, and for the error, you need to make predictions, and for making the predictions, you need both the model and the input data to be allocated in the CUDA memory. So when you try to execute the training, and you don’t have enough free CUDA memory available, then the framework you’re using throws this out of memory error."
},
{
"code": null,
"e": 1361,
"s": 1271,
"text": "So keeping that in mind, here are the common reasons why this error is so prone to occur:"
},
{
"code": null,
"e": 1431,
"s": 1361,
"text": "When you’re model is big, by big I mean lot’s of parameters to train."
},
{
"code": null,
"e": 1593,
"s": 1431,
"text": "When you’re using such a model architecture that performs a lot of concatenation operations (in DenseNet). Or huge channels operations like additions (in ResNet)"
},
{
"code": null,
"e": 1789,
"s": 1593,
"text": "When the size of your input data is too high. I don’t mean to say the size of data you have available, but the input size of single data instance, like in case of an image, it could be 3x224x224."
},
{
"code": null,
"e": 1888,
"s": 1789,
"text": "And finally, when you’re batch size is too high with respect to the dimensions of a data instance."
},
{
"code": null,
"e": 2194,
"s": 1888,
"text": "Now the issue is not that you can’t solve the problems above, I mean switching to a smaller model might take not more than 20 to 30 minutes, and decreasing the batch size is, of course, a piece of cake, and such solutions do solve issue for most of the cases, but at the cost of time and model’s accuracy."
},
{
"code": null,
"e": 2630,
"s": 2194,
"text": "For instance, if you set your batch size too low, then it might just take forever to make the loss converge because your model would be just oscillating too much, not only that, some model architectures don’t even perform well when batch size is not up to the requirements. And, if you decide to switch to a smaller model or reduce the dimensions of the input data, then you might just lose quite a lot of accuracy for obvious reasons."
},
{
"code": null,
"e": 2770,
"s": 2630,
"text": "So as you can see solving this error is not that hard to tackle, but its the cost of the solution which is too high for a good ML engineer."
},
{
"code": null,
"e": 3060,
"s": 2770,
"text": "Alright, so now it is pretty obvious that just one solution wouldn’t be enough to solve all of the above problems, in fact, a limited solution would only create even more problems. So after quite a lot of headaches I’ve finally came to these solutions, when applied together, do wonders :)"
},
{
"code": null,
"e": 3083,
"s": 3060,
"text": "Gradient Accumulation."
},
{
"code": null,
"e": 3129,
"s": 3083,
"text": "Training with AMP(Automatic Mixed Precision)."
},
{
"code": null,
"e": 3151,
"s": 3129,
"text": "Few of my own tricks."
},
{
"code": null,
"e": 3189,
"s": 3151,
"text": "Let’s have a look at them one by one."
},
{
"code": null,
"e": 3480,
"s": 3189,
"text": "This solution has been a de facto for solving out of memory issues. In fact, this is the very only reason why this technique exists in the first place. This technique solves the issue of model oscillation when the batch size is set too low. The nub here is actually very easy to understand."
},
{
"code": null,
"e": 3982,
"s": 3480,
"text": "The reason why model oscillates when batch size is too low is that the gradients are averages for less number of data instances. So after each training iteration (training a single batch), the model gets too specific updates, and thus parameters are changed too much towards a single direction. And reducing the learning rate would not be helpful here, in fact, it would just make the training even slower and just horrible because not only the updates are less generalized but with low magnitude too."
},
{
"code": null,
"e": 4289,
"s": 3982,
"text": "So the idea behind gradient accumulation is, keep adding gradients of the parameters for n number of batches, where batch size is small, and then after n batch iterations, apply the updates using the average of all those gradients accumulated over n iterations, that’s why its called gradient accumulation."
},
{
"code": null,
"e": 4347,
"s": 4289,
"text": "Below is the sample procedure for Pytorch implementation."
},
{
"code": null,
"e": 4885,
"s": 4347,
"text": "In the above example, note that we are dividing the loss by gradient_accumulations for keeping the scale of gradients same as if were training with 64 batch size. For an effective batch size of 64, ideally, we want to average over 64 gradients to apply the updates, so if we don’t divide by gradient_accumulations then we would be applying updates using an average of gradients over the batch size of 4 only, because we just kept adding the gradients for gradient_accumulations number of batch iterations before calling optimizer.step()."
},
{
"code": null,
"e": 5180,
"s": 4885,
"text": "So, this technique effectively solves the problem of limited gradient averaging. Now mathematically we are totally good here, but the problem is the training time. As our batch size is really low, so definitely we are doing drastically less parallel computations as compared to high batch size."
},
{
"code": null,
"e": 5368,
"s": 5180,
"text": "And if you are accumulating the gradients for k batch iterations then it would approximately take k times the time for training with the batch size that you actually want. Let’s fix this."
},
{
"code": null,
"e": 5564,
"s": 5368,
"text": "Almost all of the deep learning frameworks operate on 32-bit floating-point or float32 data type by default. Though there are many operations the does not need to be this much precisely accurate."
},
{
"code": null,
"e": 5794,
"s": 5564,
"text": "3 years ago Nvidia researchers created a new methodology, that in a nutshell combines single-precision with the half-precision floating-point for training deep learning models, that achieves the same level of accuracy as float32."
},
{
"code": null,
"e": 6057,
"s": 5794,
"text": "It enables automatic conversion of certain GPU operations from float32 precision to mixed-precision, while improving performance and maintaining same accuracy. For an exact performance and accuracy comparisons make sure to check out Nvidia’s official benchmarks."
},
{
"code": null,
"e": 6094,
"s": 6057,
"text": "Main plus points of this method are:"
},
{
"code": null,
"e": 6114,
"s": 6094,
"text": "Less training time."
},
{
"code": null,
"e": 6143,
"s": 6114,
"text": "Enabling larger batch sizes."
},
{
"code": null,
"e": 6175,
"s": 6143,
"text": "Larger models and large inputs."
},
{
"code": null,
"e": 6202,
"s": 6175,
"text": "Lower memory requirements."
},
{
"code": null,
"e": 6324,
"s": 6202,
"text": "So now you can see why I decided to combine AMP with gradient accumulation. Anyways, below is its Pytorch implementation."
},
{
"code": null,
"e": 6392,
"s": 6324,
"text": "I’ll let this paper Multi-Node BERT-Pretraining explain this to you"
},
{
"code": null,
"e": 6851,
"s": 6392,
"text": "Typically in a computation graph, not all FP16 operators are numerically safe. This means operators that are considered numerically dangerous will have its calculation in full precision. For example, a plus operator is marked as safe while a 5 power or a log operator is considered numerically dangerous in half precision. Automated mixed precision handles the categorization of the numerical safety level through the rewriting of computation graph — Authors"
},
{
"code": null,
"e": 6965,
"s": 6851,
"text": "For more info regarding different precisions, make sure to check out this brief article by non other than Nvidia."
},
{
"code": null,
"e": 7099,
"s": 6965,
"text": "So now, since we are set to use both of the techniques I’ve explained above, let’s put the together to come up with an awesome combo."
},
{
"code": null,
"e": 7132,
"s": 7099,
"text": "Yuppah, that’s pretty much it :)"
},
{
"code": null,
"e": 7386,
"s": 7132,
"text": "Depending on the model and input sizes, and how much gradients you are accumulating, you could easily get somewhere around 1.2x to 1.5x (and sometimes even more) speed ups with AMP, and of course your loss would converge thanks to gradient accumulation."
},
{
"code": null,
"e": 7892,
"s": 7386,
"text": "Now for 95% of the times, you wouldn’t need to use techniques that I’m sharing here because AMP and gradient accumulation applied together works juuuuust fine. Though recently I’ve started working for a startup, where we are trying to detect violence in CCTV footages. This task basically is a video classification, where in a batch we would have to deal with one more dimension as compared to image classification, making total 5 dimensions of a single batch. So this definitely means massive input size."
},
{
"code": null,
"e": 8026,
"s": 7892,
"text": "I wanted to further speed up the training, cuz we had over 16GB of training data so speeding the things was definitely a requirement."
},
{
"code": null,
"e": 8045,
"s": 8026,
"text": "Here’s what I did."
},
{
"code": null,
"e": 8448,
"s": 8045,
"text": "Reducing the input data features. In my case I reduced the temporal dimensions to reasonable 28, rather than 36 as before. This not sound much of a decrease, but keep that in mind that a single step in temporal dimension in a video means covering 3 * 224 * 244 feature values... so in total I decreased over 1 million features :), not only that I also reduced the image size from 224 to reasonable 196."
},
{
"code": null,
"e": 8879,
"s": 8448,
"text": "Making classes distribution uniform over a batch. This is very simple actually, the idea is to make sure that every batch contains the same number of input data for every class. So in my case each batch always contained 4 non violence videos and 4 violence videos for batch size of 8. This would help to minimize the data imbalance (sort of, not 100%) that I had and finally improve the testing accuracy within same training time."
},
{
"code": null,
"e": 9168,
"s": 8879,
"text": "Yes, these ideas are not necessarily for solving the out of CUDA memory issue, but while applying these techniques, there was a well noticeable amount decrease in time for training, and helped me to get ahead by 3 training epochs where each epoch was approximately taking over 25 minutes."
},
{
"code": null,
"e": 9283,
"s": 9168,
"text": "So we saw how to use gradient accumulation and automatic mixed precision together to come out limited memory hell."
},
{
"code": null,
"e": 9414,
"s": 9283,
"text": "Gradient accumulation workouts the math and helps to solve the loss oscillation issue, but small batch size causes slower training"
},
{
"code": null,
"e": 9525,
"s": 9414,
"text": "And this is where automatic mixed precision and few of my tweaks helps to speed up the whole training process."
}
] |
How to display image using Plotly? - GeeksforGeeks | 01 Oct, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
The Imshow method is the fastest method to show the 2d data. This method is used to generate an image from the numerical data. The numerical data can be in the form of NumPy array.
Syntax: imshow(labels={}, x=None, y=None, color_continuous_scale=None, color_continuous_midpoint=None, range_color=None,width=None, height=None)
This function can also show RGB data as an image. The data is provided in the format of NumPy array.
Example:
Python3
import plotly.express as pximport numpy as np # RGB Data as numpy arrayimg_rgb = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]], ], dtype=np.uint8) fig = px.imshow(img_rgb)fig.show()
Output:
A third-party library can be used like PIL, scikit-image, or OpenCV to read the image as an array.
Example:
Image used:
Python3
import plotly.express as pximport cv2 # You can give path to the # image as first argument img = cv2.imread('GFG.png') fig = px.imshow(img)fig.show()
Output:
Python-Plotly
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 Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 24596,
"s": 24292,
"text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 24777,
"s": 24596,
"text": "The Imshow method is the fastest method to show the 2d data. This method is used to generate an image from the numerical data. The numerical data can be in the form of NumPy array."
},
{
"code": null,
"e": 24922,
"s": 24777,
"text": "Syntax: imshow(labels={}, x=None, y=None, color_continuous_scale=None, color_continuous_midpoint=None, range_color=None,width=None, height=None)"
},
{
"code": null,
"e": 25023,
"s": 24922,
"text": "This function can also show RGB data as an image. The data is provided in the format of NumPy array."
},
{
"code": null,
"e": 25032,
"s": 25023,
"text": "Example:"
},
{
"code": null,
"e": 25040,
"s": 25032,
"text": "Python3"
},
{
"code": "import plotly.express as pximport numpy as np # RGB Data as numpy arrayimg_rgb = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]], ], dtype=np.uint8) fig = px.imshow(img_rgb)fig.show()",
"e": 25249,
"s": 25040,
"text": null
},
{
"code": null,
"e": 25257,
"s": 25249,
"text": "Output:"
},
{
"code": null,
"e": 25356,
"s": 25257,
"text": "A third-party library can be used like PIL, scikit-image, or OpenCV to read the image as an array."
},
{
"code": null,
"e": 25365,
"s": 25356,
"text": "Example:"
},
{
"code": null,
"e": 25377,
"s": 25365,
"text": "Image used:"
},
{
"code": null,
"e": 25385,
"s": 25377,
"text": "Python3"
},
{
"code": "import plotly.express as pximport cv2 # You can give path to the # image as first argument img = cv2.imread('GFG.png') fig = px.imshow(img)fig.show()",
"e": 25540,
"s": 25385,
"text": null
},
{
"code": null,
"e": 25548,
"s": 25540,
"text": "Output:"
},
{
"code": null,
"e": 25564,
"s": 25550,
"text": "Python-Plotly"
},
{
"code": null,
"e": 25571,
"s": 25564,
"text": "Python"
},
{
"code": null,
"e": 25669,
"s": 25571,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25701,
"s": 25669,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25743,
"s": 25701,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25799,
"s": 25743,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25841,
"s": 25799,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25872,
"s": 25841,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25927,
"s": 25872,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25949,
"s": 25927,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25988,
"s": 25949,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26017,
"s": 25988,
"text": "Create a directory in Python"
}
] |
Maximum Product Subarray | Practice | GeeksforGeeks | Given an array Arr[] that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray.
Example 1:
Input:
N = 5
Arr[] = {6, -3, -10, 0, 2}
Output: 180
Explanation: Subarray with maximum product
is [6, -3, -10] which gives product as 180.
Example 2:
Input:
N = 6
Arr[] = {2, 3, 4, 5, -1, 0}
Output: 120
Explanation: Subarray with maximum product
is [2, 3, 4, 5] which gives product as 120.
Your Task:
You don't need to read input or print anything. Your task is to complete the function maxProduct() which takes the array of integers arr and n as parameters and returns an integer denoting the answer.
Note: Use 64-bit integer data type to avoid overflow.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 500
-102 ≤ Arri ≤ 102
0
sm21mtech120084 days ago
logic : for every iteration save max, min multiplication ,save maximum element of present and previous multiplication in res ie res=max(res,ma)
long long maxProduct(vector<int> arr, int n)
{
long long res=arr[0],ma=1,mi=1;
for(auto i:arr)
{
long long t=i*ma;
//if you dont save ma in t then min value would be changed
ma=max(t,max(i*mi,(long long)i));
mi=min(t,min(i*mi,(long long)i));
res=max(res,ma);
}
return res;
}
+1
prajjwal9934 days ago
JAVA 0(n)
class Solution {
// Function to find maximum product subarray
long maxProduct(int[] arr, int n) {
long currmax = 1;
long msf = Integer.MIN_VALUE;
for(int i = 0; i < n; i++){
currmax*=arr[i];
msf=Math.max(msf,currmax);
if(currmax==0){
currmax=1;
}
}
currmax=1;
for(int i=n-1;i>=0;i--){
currmax*=arr[i];
msf=Math.max(msf,currmax);
if(currmax==0){
currmax=1;
}
}
return msf;
}
}
0
rajat8124 days ago
java solution O(n^2)
long maxProduct(int[] arr, int n) {
// code here
long pro=1,max=Long.MIN_VALUE;
for(int i=0;i<n;i++)
{
pro=1;
for(int j=i;j<n;j++)
{
pro*=arr[j];
max=Math.max(pro,max);
}
}
return max;
}
0
imramnazir2864 days ago
class Solution{
public:
// Function to find maximum product subarray
long long maxProduct(vector<int> arr, int n) {
// code here
long long mx=1,mn=1,ans=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i]==0)
{ mx=mn=1;
continue;
}
if(arr[i]<0)
{
long long t= mx;
mx=max((long long)arr[i],arr[i]*mn);
mn=min((long long)arr[i],arr[i]*t);
}
else
{
mx=max((long long)arr[i],arr[i]*mx);
mn=min((long long)arr[i],arr[i]*mn);
}
ans=max(ans,mx);
}
return ans;
}
};
0
syedmallakbasheer4 days ago
cpp soln
long long maxProduct(vector<int> a, int n) { long long glomp = a[0]; long long curmax = a[0]; long long curmin = a[0]; for(long long i=1;i<n;i++) { long long tmp = curmax*a[i]; curmax = max((long long)a[i],max(a[i]*curmax,a[i]*curmin)); curmin = min((long long)a[i],min(tmp,a[i]*curmin)); glomp = max(glomp,curmax); } return glomp;}
0
nitishmishra9374 days ago
Java Code
long maxProduct(int[] arr, int n) {
if (n == 1) {
return arr[0];
}
long leftProduct = arr[0];
long rightProduct = arr[n - 1];
long max = Math.max(leftProduct, rightProduct);
for (int i = 1; i < n; ++i) {
leftProduct = leftProduct == 0 ? arr[i] : leftProduct * arr[i];
rightProduct = rightProduct == 0 ? arr[n - i - 1] : rightProduct * arr[n - i - 1];
max = Math.max(max, Math.max(leftProduct, rightProduct));
}
return max;
}
0
vedratan85 days ago
long long maxProduct(vector<int> arr, int n) { long long ans=arr[0],maximum=arr[0], minimum=arr[0]; for(int i=1;i<n;i++) { if(arr[i]<0) { swap(maximum, minimum); } maximum = (arr[i]>arr[i]*maximum)?arr[i]:arr[i]*maximum; minimum = (arr[i]<arr[i]*minimum)?arr[i]:arr[i]*minimum; ans= (ans>maximum)?ans:maximum; } return ans;}
0
rathodumang3196 days ago
Java Solution:
class Solution {
long maxProduct(int[] arr, int n) {
long ans = arr[0];
long min = ans, max = ans;
for(int i=1; i<n; i++){
if(arr[i] < 0){
long temp = max;
max = min;
min = temp;
}
max = Math.max(arr[i], max*arr[i]);
min = Math.min(arr[i], min*arr[i]);
ans = Math.max(ans, max);
}
return ans;
}
}
0
amanmehar88
This comment was deleted.
+2
nareshshiva93171 week ago
long long maxProduct(vector<int> arr, int n) { long long max = INT_MIN; long long mul = 1; for(int i=0;i<n;i++){ mul = mul * arr[i]; if(arr[i] == 0){ mul = 1; } if(mul>max){ max = mul; } } mul = 1; for(int i=n-1;i>=0;i--){ mul = mul * arr[i]; if(arr[i] == 0){ mul = 1; } if(mul>max){ max = mul; } } return max;}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 371,
"s": 238,
"text": "Given an array Arr[] that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray."
},
{
"code": null,
"e": 382,
"s": 371,
"text": "Example 1:"
},
{
"code": null,
"e": 522,
"s": 382,
"text": "Input:\nN = 5\nArr[] = {6, -3, -10, 0, 2}\nOutput: 180\nExplanation: Subarray with maximum product\nis [6, -3, -10] which gives product as 180.\n"
},
{
"code": null,
"e": 533,
"s": 522,
"text": "Example 2:"
},
{
"code": null,
"e": 674,
"s": 533,
"text": "Input:\nN = 6\nArr[] = {2, 3, 4, 5, -1, 0}\nOutput: 120\nExplanation: Subarray with maximum product\nis [2, 3, 4, 5] which gives product as 120.\n"
},
{
"code": null,
"e": 940,
"s": 674,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function maxProduct() which takes the array of integers arr and n as parameters and returns an integer denoting the answer.\nNote: Use 64-bit integer data type to avoid overflow."
},
{
"code": null,
"e": 1002,
"s": 940,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1045,
"s": 1002,
"text": "Constraints:\n1 ≤ N ≤ 500\n-102 ≤ Arri ≤ 102"
},
{
"code": null,
"e": 1047,
"s": 1045,
"text": "0"
},
{
"code": null,
"e": 1072,
"s": 1047,
"text": "sm21mtech120084 days ago"
},
{
"code": null,
"e": 1216,
"s": 1072,
"text": "logic : for every iteration save max, min multiplication ,save maximum element of present and previous multiplication in res ie res=max(res,ma)"
},
{
"code": null,
"e": 1548,
"s": 1218,
"text": "long long maxProduct(vector<int> arr, int n)\n {\n long long res=arr[0],ma=1,mi=1;\n for(auto i:arr)\n {\n long long t=i*ma;\n //if you dont save ma in t then min value would be changed \n ma=max(t,max(i*mi,(long long)i));\n mi=min(t,min(i*mi,(long long)i));\n res=max(res,ma);\n }\n return res;\n}"
},
{
"code": null,
"e": 1551,
"s": 1548,
"text": "+1"
},
{
"code": null,
"e": 1573,
"s": 1551,
"text": "prajjwal9934 days ago"
},
{
"code": null,
"e": 1583,
"s": 1573,
"text": "JAVA 0(n)"
},
{
"code": null,
"e": 2165,
"s": 1585,
"text": "class Solution {\n // Function to find maximum product subarray\n long maxProduct(int[] arr, int n) {\n long currmax = 1;\n long msf = Integer.MIN_VALUE;\n for(int i = 0; i < n; i++){\n currmax*=arr[i];\n msf=Math.max(msf,currmax);\n if(currmax==0){\n currmax=1;\n }\n }\n currmax=1;\n for(int i=n-1;i>=0;i--){\n currmax*=arr[i];\n msf=Math.max(msf,currmax);\n if(currmax==0){\n currmax=1;\n }\n }\n return msf;\n }\n}"
},
{
"code": null,
"e": 2167,
"s": 2165,
"text": "0"
},
{
"code": null,
"e": 2186,
"s": 2167,
"text": "rajat8124 days ago"
},
{
"code": null,
"e": 2207,
"s": 2186,
"text": "java solution O(n^2)"
},
{
"code": null,
"e": 2496,
"s": 2207,
"text": " long maxProduct(int[] arr, int n) {\n // code here\n long pro=1,max=Long.MIN_VALUE;\n for(int i=0;i<n;i++)\n {\n pro=1;\n for(int j=i;j<n;j++)\n {\n pro*=arr[j];\n max=Math.max(pro,max);\n }\n \n }\n return max;\n }"
},
{
"code": null,
"e": 2498,
"s": 2496,
"text": "0"
},
{
"code": null,
"e": 2522,
"s": 2498,
"text": "imramnazir2864 days ago"
},
{
"code": null,
"e": 3152,
"s": 2522,
"text": "class Solution{\npublic:\n\n\t// Function to find maximum product subarray\n\tlong long maxProduct(vector<int> arr, int n) {\n\t // code here\n\t long long mx=1,mn=1,ans=arr[0];\n for(int i=0;i<n;i++)\n {\n if(arr[i]==0)\n { mx=mn=1;\n continue;\n }\n if(arr[i]<0)\n { \n long long t= mx;\n mx=max((long long)arr[i],arr[i]*mn);\n mn=min((long long)arr[i],arr[i]*t);\n }\n else\n {\n mx=max((long long)arr[i],arr[i]*mx);\n mn=min((long long)arr[i],arr[i]*mn);\n }\n ans=max(ans,mx);\n }\n return ans;\n\t \n\t}\n};"
},
{
"code": null,
"e": 3154,
"s": 3152,
"text": "0"
},
{
"code": null,
"e": 3182,
"s": 3154,
"text": "syedmallakbasheer4 days ago"
},
{
"code": null,
"e": 3191,
"s": 3182,
"text": "cpp soln"
},
{
"code": null,
"e": 3562,
"s": 3191,
"text": "long long maxProduct(vector<int> a, int n) { long long glomp = a[0]; long long curmax = a[0]; long long curmin = a[0]; for(long long i=1;i<n;i++) { long long tmp = curmax*a[i]; curmax = max((long long)a[i],max(a[i]*curmax,a[i]*curmin)); curmin = min((long long)a[i],min(tmp,a[i]*curmin)); glomp = max(glomp,curmax); } return glomp;}"
},
{
"code": null,
"e": 3564,
"s": 3562,
"text": "0"
},
{
"code": null,
"e": 3590,
"s": 3564,
"text": "nitishmishra9374 days ago"
},
{
"code": null,
"e": 3600,
"s": 3590,
"text": "Java Code"
},
{
"code": null,
"e": 4065,
"s": 3602,
"text": " long maxProduct(int[] arr, int n) {\n\t\tif (n == 1) {\n\t\t\treturn arr[0];\n\t\t}\n\n\t\tlong leftProduct = arr[0];\n\t\tlong rightProduct = arr[n - 1];\n\t\tlong max = Math.max(leftProduct, rightProduct);\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tleftProduct = leftProduct == 0 ? arr[i] : leftProduct * arr[i];\n\t\t\trightProduct = rightProduct == 0 ? arr[n - i - 1] : rightProduct * arr[n - i - 1];\n\t\t\tmax = Math.max(max, Math.max(leftProduct, rightProduct));\n\t\t}\n\n\t\treturn max;\n\t}"
},
{
"code": null,
"e": 4067,
"s": 4065,
"text": "0"
},
{
"code": null,
"e": 4087,
"s": 4067,
"text": "vedratan85 days ago"
},
{
"code": null,
"e": 4483,
"s": 4087,
"text": " long long maxProduct(vector<int> arr, int n) { long long ans=arr[0],maximum=arr[0], minimum=arr[0]; for(int i=1;i<n;i++) { if(arr[i]<0) { swap(maximum, minimum); } maximum = (arr[i]>arr[i]*maximum)?arr[i]:arr[i]*maximum; minimum = (arr[i]<arr[i]*minimum)?arr[i]:arr[i]*minimum; ans= (ans>maximum)?ans:maximum; } return ans;}"
},
{
"code": null,
"e": 4485,
"s": 4483,
"text": "0"
},
{
"code": null,
"e": 4510,
"s": 4485,
"text": "rathodumang3196 days ago"
},
{
"code": null,
"e": 4525,
"s": 4510,
"text": "Java Solution:"
},
{
"code": null,
"e": 4978,
"s": 4525,
"text": "class Solution {\n long maxProduct(int[] arr, int n) {\n long ans = arr[0];\n long min = ans, max = ans;\n for(int i=1; i<n; i++){\n if(arr[i] < 0){\n long temp = max;\n max = min;\n min = temp;\n }\n max = Math.max(arr[i], max*arr[i]);\n min = Math.min(arr[i], min*arr[i]);\n ans = Math.max(ans, max);\n }\n return ans;\n }\n}"
},
{
"code": null,
"e": 4980,
"s": 4978,
"text": "0"
},
{
"code": null,
"e": 4992,
"s": 4980,
"text": "amanmehar88"
},
{
"code": null,
"e": 5018,
"s": 4992,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5021,
"s": 5018,
"text": "+2"
},
{
"code": null,
"e": 5047,
"s": 5021,
"text": "nareshshiva93171 week ago"
},
{
"code": null,
"e": 5497,
"s": 5047,
"text": "long long maxProduct(vector<int> arr, int n) { long long max = INT_MIN; long long mul = 1; for(int i=0;i<n;i++){ mul = mul * arr[i]; if(arr[i] == 0){ mul = 1; } if(mul>max){ max = mul; } } mul = 1; for(int i=n-1;i>=0;i--){ mul = mul * arr[i]; if(arr[i] == 0){ mul = 1; } if(mul>max){ max = mul; } } return max;}"
},
{
"code": null,
"e": 5645,
"s": 5499,
"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": 5681,
"s": 5645,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5691,
"s": 5681,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5701,
"s": 5691,
"text": "\nContest\n"
},
{
"code": null,
"e": 5764,
"s": 5701,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5949,
"s": 5764,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6233,
"s": 5949,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6379,
"s": 6233,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6456,
"s": 6379,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6497,
"s": 6456,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6525,
"s": 6497,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6596,
"s": 6525,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6783,
"s": 6596,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
How to Take Input From User in Java? | 08 Jun, 2022
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data types, characters, files, etc to fully execute the I/O operations. There are two ways by which we can take input from the user or from a file
BufferedReader Class
Scanner Class
It is a simple class that is used to read a sequence of characters. It has a simple function that reads a character another read which reads, an array of characters, and a readLine() function which reads a line.
InputStreamReader() is a function that converts the input stream of bytes into a stream of characters so that it can be read as BufferedReader expects a stream of characters.
BufferedReader can throw checked Exceptions
Java
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
// Java Program for taking user// input using BufferedReader Classimport java.io.*; class GFG { // Main Method public static void main(String [] args) throws IOException { // Creating BufferedReader Object // InputStreamReader converts bytes to // stream of character BufferedReader bfn = new BufferedReader(new InputStreamReader(System.in)); // Asking for input from user System.out.println("Enter String : "); System.out.println("Enter Integer : "); // String reading internally String str = bfn.readLine(); // Integer reading internally int it = Integer.parseInt(bfn.readLine()); // Printing String System.out.println("Entered String : "+ str); // Printing Integer System.out.println("Entered Integer : "+ it); } }
Input:
GFG
123
Output:
Enter String :
Enter Integer :
Entered String : GFG
Entered Integer : 123
It is an advanced version of BufferedReader which was added in later versions of Java. The scanner can read formatted input. It has different functions for different types of data types.
The scanner is much easier to read as we don’t have to write throws as there is no exception thrown by it.
It was added in later versions of Java
It contains predefined functions to read an Integer, Character, and other data types as well.
Syntax for Scanner
Scanner scn = new Scanner(System.in);
Syntax for importing Scanner Class: To use the Scanner we need to import the Scanner Class
import java.util.Scanner;
Inbuilt Scanner functions are as follows
Integer: nextInt()
Float: nextFloat()
String : next() and nextLine()
Hence, in the case of Integer and String in Scanner, we don’t require parsing as we did require in BufferedReader.
Java
// Java Program to show how to take// input from user using Scanner Class import java.util.*; class GFG { public static void main(String[] args) { // Scanner definition Scanner scn = new Scanner(System.in); // input is a string ( one word ) // read by next() function String str1 = scn.next(); // print String System.out.println("Entered String str1 : " + str1); // input is a String ( complete Sentence ) // read by nextLine()function String str2 = scn.nextLine(); // print string System.out.println("Entered String str2 : " + str2); // input is an Integer // read by nextInt() function int x = scn.nextInt(); // print integer System.out.println("Entered Integer : " + x); // input is a floatingValue // read by nextFloat() function float f = scn.nextFloat(); // print floating value System.out.println("Entered FloatValue : " + f); }}
Input:
Geeks for Geeks
Geeks for Geeks
123
123.090
Output :
Entered String str1 : Geeks
Entered String str2 : Geeks For Geeks
Entered Integer : 123
Entered FloatValue : 123.090
BufferedReader is a very basic way to read the input generally used to read the stream of characters. It gives an edge over Scanner as it is faster than Scanner because Scanner does lots of post-processing for parsing the input; as seen in nextInt(), nextFloat()
BufferedReader is more flexible as we can specify the size of stream input to be read. (In general, it is there that BufferedReader reads larger input than Scanner)
These two factors come into play when we are reading larger input. In general, the Scanner Class serves the input.
BufferedReader is preferred as it is synchronized. While dealing with multiple threads it is preferred.
For decent input, easy readability. The Scanner is preferred over BufferedReader.
simmytarika5
surinderdawra388
lakshaypruthi
kaelankjgzf
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 360,
"s": 52,
"text": "Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data types, characters, files, etc to fully execute the I/O operations. There are two ways by which we can take input from the user or from a file"
},
{
"code": null,
"e": 381,
"s": 360,
"text": "BufferedReader Class"
},
{
"code": null,
"e": 395,
"s": 381,
"text": "Scanner Class"
},
{
"code": null,
"e": 607,
"s": 395,
"text": "It is a simple class that is used to read a sequence of characters. It has a simple function that reads a character another read which reads, an array of characters, and a readLine() function which reads a line."
},
{
"code": null,
"e": 782,
"s": 607,
"text": "InputStreamReader() is a function that converts the input stream of bytes into a stream of characters so that it can be read as BufferedReader expects a stream of characters."
},
{
"code": null,
"e": 826,
"s": 782,
"text": "BufferedReader can throw checked Exceptions"
},
{
"code": null,
"e": 831,
"s": 826,
"text": "Java"
},
{
"code": null,
"e": 840,
"s": 831,
"text": "Chapters"
},
{
"code": null,
"e": 867,
"s": 840,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 917,
"s": 867,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 940,
"s": 917,
"text": "captions off, selected"
},
{
"code": null,
"e": 948,
"s": 940,
"text": "English"
},
{
"code": null,
"e": 972,
"s": 948,
"text": "This is a modal window."
},
{
"code": null,
"e": 1041,
"s": 972,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1063,
"s": 1041,
"text": "End of dialog window."
},
{
"code": "// Java Program for taking user// input using BufferedReader Classimport java.io.*; class GFG { // Main Method public static void main(String [] args) throws IOException { // Creating BufferedReader Object // InputStreamReader converts bytes to // stream of character BufferedReader bfn = new BufferedReader(new InputStreamReader(System.in)); // Asking for input from user System.out.println(\"Enter String : \"); System.out.println(\"Enter Integer : \"); // String reading internally String str = bfn.readLine(); // Integer reading internally int it = Integer.parseInt(bfn.readLine()); // Printing String System.out.println(\"Entered String : \"+ str); // Printing Integer System.out.println(\"Entered Integer : \"+ it); } }",
"e": 2018,
"s": 1063,
"text": null
},
{
"code": null,
"e": 2025,
"s": 2018,
"text": "Input:"
},
{
"code": null,
"e": 2033,
"s": 2025,
"text": "GFG\n123"
},
{
"code": null,
"e": 2041,
"s": 2033,
"text": "Output:"
},
{
"code": null,
"e": 2117,
"s": 2041,
"text": "Enter String : \nEnter Integer : \nEntered String : GFG\nEntered Integer : 123"
},
{
"code": null,
"e": 2305,
"s": 2117,
"text": "It is an advanced version of BufferedReader which was added in later versions of Java. The scanner can read formatted input. It has different functions for different types of data types. "
},
{
"code": null,
"e": 2412,
"s": 2305,
"text": "The scanner is much easier to read as we don’t have to write throws as there is no exception thrown by it."
},
{
"code": null,
"e": 2451,
"s": 2412,
"text": "It was added in later versions of Java"
},
{
"code": null,
"e": 2545,
"s": 2451,
"text": "It contains predefined functions to read an Integer, Character, and other data types as well."
},
{
"code": null,
"e": 2564,
"s": 2545,
"text": "Syntax for Scanner"
},
{
"code": null,
"e": 2602,
"s": 2564,
"text": "Scanner scn = new Scanner(System.in);"
},
{
"code": null,
"e": 2693,
"s": 2602,
"text": "Syntax for importing Scanner Class: To use the Scanner we need to import the Scanner Class"
},
{
"code": null,
"e": 2721,
"s": 2693,
"text": "import java.util.Scanner; "
},
{
"code": null,
"e": 2762,
"s": 2721,
"text": "Inbuilt Scanner functions are as follows"
},
{
"code": null,
"e": 2781,
"s": 2762,
"text": "Integer: nextInt()"
},
{
"code": null,
"e": 2800,
"s": 2781,
"text": "Float: nextFloat()"
},
{
"code": null,
"e": 2831,
"s": 2800,
"text": "String : next() and nextLine()"
},
{
"code": null,
"e": 2946,
"s": 2831,
"text": "Hence, in the case of Integer and String in Scanner, we don’t require parsing as we did require in BufferedReader."
},
{
"code": null,
"e": 2951,
"s": 2946,
"text": "Java"
},
{
"code": "// Java Program to show how to take// input from user using Scanner Class import java.util.*; class GFG { public static void main(String[] args) { // Scanner definition Scanner scn = new Scanner(System.in); // input is a string ( one word ) // read by next() function String str1 = scn.next(); // print String System.out.println(\"Entered String str1 : \" + str1); // input is a String ( complete Sentence ) // read by nextLine()function String str2 = scn.nextLine(); // print string System.out.println(\"Entered String str2 : \" + str2); // input is an Integer // read by nextInt() function int x = scn.nextInt(); // print integer System.out.println(\"Entered Integer : \" + x); // input is a floatingValue // read by nextFloat() function float f = scn.nextFloat(); // print floating value System.out.println(\"Entered FloatValue : \" + f); }}",
"e": 3961,
"s": 2951,
"text": null
},
{
"code": null,
"e": 3968,
"s": 3961,
"text": "Input:"
},
{
"code": null,
"e": 4012,
"s": 3968,
"text": "Geeks for Geeks\nGeeks for Geeks\n123\n123.090"
},
{
"code": null,
"e": 4021,
"s": 4012,
"text": "Output :"
},
{
"code": null,
"e": 4138,
"s": 4021,
"text": "Entered String str1 : Geeks\nEntered String str2 : Geeks For Geeks\nEntered Integer : 123\nEntered FloatValue : 123.090"
},
{
"code": null,
"e": 4401,
"s": 4138,
"text": "BufferedReader is a very basic way to read the input generally used to read the stream of characters. It gives an edge over Scanner as it is faster than Scanner because Scanner does lots of post-processing for parsing the input; as seen in nextInt(), nextFloat()"
},
{
"code": null,
"e": 4566,
"s": 4401,
"text": "BufferedReader is more flexible as we can specify the size of stream input to be read. (In general, it is there that BufferedReader reads larger input than Scanner)"
},
{
"code": null,
"e": 4681,
"s": 4566,
"text": "These two factors come into play when we are reading larger input. In general, the Scanner Class serves the input."
},
{
"code": null,
"e": 4785,
"s": 4681,
"text": "BufferedReader is preferred as it is synchronized. While dealing with multiple threads it is preferred."
},
{
"code": null,
"e": 4867,
"s": 4785,
"text": "For decent input, easy readability. The Scanner is preferred over BufferedReader."
},
{
"code": null,
"e": 4880,
"s": 4867,
"text": "simmytarika5"
},
{
"code": null,
"e": 4897,
"s": 4880,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4911,
"s": 4897,
"text": "lakshaypruthi"
},
{
"code": null,
"e": 4923,
"s": 4911,
"text": "kaelankjgzf"
},
{
"code": null,
"e": 4935,
"s": 4923,
"text": "java-basics"
},
{
"code": null,
"e": 4940,
"s": 4935,
"text": "Java"
},
{
"code": null,
"e": 4945,
"s": 4940,
"text": "Java"
},
{
"code": null,
"e": 5043,
"s": 4945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5058,
"s": 5043,
"text": "Stream In Java"
},
{
"code": null,
"e": 5079,
"s": 5058,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5100,
"s": 5079,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5119,
"s": 5100,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5136,
"s": 5119,
"text": "Generics in Java"
},
{
"code": null,
"e": 5166,
"s": 5136,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 5192,
"s": 5166,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5208,
"s": 5192,
"text": "Strings in Java"
},
{
"code": null,
"e": 5245,
"s": 5208,
"text": "Differences between JDK, JRE and JVM"
}
] |
Program to print solid and hollow rhombus patterns | 06 Jun, 2022
For any given number n, print Hollow and solid Squares and Rhombus made with stars(*). Examples:
Input : n = 4
Output :
Solid Rhombus:
****
****
****
****
Hollow Rhombus:
****
* *
* *
****
1. Solid Rhombus : Making Solid Rhombus is a bit similar to making solid square rather than the concept that for each ith row we have n-i blank spaces before stars as: – – – **** – – **** – **** **** 2. Hollow Rhombus : Formation of Hollow Rhombus uses the idea behind formation of hollow square and solid rhombus. A hollow square with n-i blank spaces before stars in each ith rows result in formation of hollow rhombus.
C/C++
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to print// hollow and solid rhombus patterns #include <bits/stdc++.h>using namespace std; // Function for Solid Rhombusvoid solidRhombus(int rows){ int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) cout << " "; // Print stars after spaces for (j=1; j<=rows; j++) cout << "*"; // Move to the next line/row cout << "\n"; }} // Function for Rhombusvoid hollowRhombus(int rows){ int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) cout << " "; // Print stars after spaces // Print stars for each solid rows if (i==1 || i==rows) for (j=1; j<=rows; j++) cout << "*"; // stars for hollow rows else for (j=1; j<=rows; j++) if (j==1 || j==rows) cout << "*"; else cout << " "; // Move to the next line/row cout << "\n"; }} // utility program to print all patternsvoid printPattern(int rows){ cout << "\nSolid Rhombus:\n"; solidRhombus(rows); cout << "\nHollow Rhombus:\n"; hollowRhombus(rows);} // driver programint main(){ int rows = 5; printPattern (rows); return 0;}
// Java program to print// hollow and solid rhombus patternsimport java.io.*; class GFG{ // Function for Solid Rhombus static void solidRhombus(int rows) { int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) System.out.print(" "); // Print stars after spaces for (j=1; j<=rows; j++) System.out.print("*"); // Move to the next line/row System.out.println(); } } // Function for Hollow Rhombus static void hollowRhombus(int rows) { int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) System.out.print(" "); // Print stars after spaces // Print stars for each solid rows if (i==1 || i==rows) for (j=1; j<=rows; j++) System.out.print("*"); // stars for hollow rows else for (j=1; j<=rows; j++) if (j==1 || j==rows) System.out.print("*"); else System.out.print(" "); // Move to the next line/row System.out.println(); } } // utility program to print all patterns static void printPattern(int rows) { System.out.println("Solid Rhombus:"); solidRhombus(rows); System.out.println("Hollow Rhombus:"); hollowRhombus(rows); } // driver program public static void main (String[] args) { int rows = 5; printPattern (rows); }} // Contributed by Pramod Kumar
# Python 3 program to print# hollow and solid rhombus patterns # Function for Solid Rhombus def solidRhombus(rows): for i in range (1,rows + 1): # Print trailing spaces for j in range (1,rows - i + 1): print (end=" ") # Print stars after spaces for j in range (1,rows + 1): print ("*",end="") # Move to the next line/row print() # Function for Hollow Rhombus def hollowRhombus(rows): for i in range (1, rows + 1): # Print trailing spaces for j in range (1, rows - i + 1): print (end=" ") # Print stars after spaces # Print stars for each solid rows if i == 1 or i == rows: for j in range (1, rows + 1): print ("*",end="") # stars for hollow rows else: for j in range (1,rows+1): if (j == 1 or j == rows): print ("*",end="") else: print (end=" ") # Move to the next line/row print() # utility program to print all patternsdef printPattern(rows): print ("Solid Rhombus:") solidRhombus(rows) print("\nHollow Rhombus:") hollowRhombus(rows) # driver program if __name__ == "__main__": rows = 5 printPattern (rows)
// C# program to print// hollow and solid rhombus patternsusing System; class GFG{ // Function for Solid Rhombus static void solidRhombus(int rows) { int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) Console.Write(" "); // Print stars after spaces for (j=1; j<=rows; j++) Console.Write("*"); // Move to the next line/row Console.WriteLine(); } } // Function for Hollow Rhombus static void hollowRhombus(int rows) { int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) Console.Write(" "); // Print stars after spaces // Print stars for each solid rows if (i==1 || i==rows) for (j=1; j<=rows; j++) Console.Write("*"); // stars for hollow rows else for (j=1; j<=rows; j++) if (j==1 || j==rows) Console.Write("*"); else Console.Write(" "); // Move to the next line/row Console.WriteLine(); } } // utility program to print all patterns static void printPattern(int rows) { Console.WriteLine("\nSolid Rhombus:\n"); solidRhombus(rows); Console.WriteLine("\nHollow Rhombus:\n"); hollowRhombus(rows); } // driver program public static void Main () { int rows = 5; printPattern (rows); }} // Contributed by vt_m.
<?php// php program to print hollow`// and solid rhombus patterns // Function for Solid Rhombusfunction solidRhombus($rows){ for ($i = 1; $i <= $rows; $i++) { // Print trailing spaces for ($j = 1; $j <= $rows - $i; $j++) echo " "; // Print stars after spaces for ($j = 1; $j <= $rows; $j++) echo "*"; // Move to the next line/row echo "\n"; }} // Function for Hollow Rhombusfunction hollowRhombus($rows){ for ($i = 1; $i <= $rows; $i++) { // Print trailing spaces for ($j = 1; $j <= $rows - $i; $j++) echo " "; // Print stars after spaces // Print stars for each solid $rows if ($i == 1 || $i == $rows) for ($j = 1; $j <= $rows; $j++) echo "*"; // stars for hollow $rows else for ($j = 1; $j <= $rows; $j++) if ($j == 1 || $j == $rows) echo "*"; else echo " "; // Move to the next line/row echo "\n"; }} // utility program to print// all patternsfunction printPattern($rows){ echo "\nSolid Rhombus:\n"; solidRhombus($rows); echo "\nHollow Rhombus:\n"; hollowRhombus($rows);} // Driver Code $rows = 5; printPattern ($rows); // This code is contributed by mits?>
<script> // JavaScript program to print // hollow and solid rhombus patterns // Function for Solid Rhombus function solidRhombus(rows) { var i, j; for (i = 1; i <= rows; i++) { // Print trailing spaces for (j = 1; j <= rows - i; j++) document.write(" "); // Print stars after spaces for (j = 1; j <= rows; j++) document.write("*"); // Move to the next line/row document.write("<br>"); } } // Function for Rhombus function hollowRhombus(rows) { var i, j; for (i = 1; i <= rows; i++) { // Print trailing spaces for (j = 1; j <= rows - i; j++) document.write(" "); // Print stars after spaces // Print stars for each solid rows if (i == 1 || i == rows) for (j = 1; j <= rows; j++) document.write("*"); // stars for hollow rows else for (j = 1; j <= rows; j++) if (j == 1 || j == rows) document.write("*"); else document.write(" "); // Move to the next line/row document.write("<br>"); } } // utility program to print all patterns function printPattern(rows) { document.write("Solid Rhombus:<br>"); solidRhombus(rows); document.write("Hollow Rhombus:<br>"); hollowRhombus(rows); } // driver program var rows = 5; printPattern(rows); // This code is contributed by rdtank. </script>
Output:
Solid Rhombus:
*****
*****
*****
*****
*****
Hollow Rhombus:
*****
* *
* *
* *
*****
Time Complexity: O(r2), where r represents the given number of rows.Auxiliary Space: O(1), no extra space is required, so it is a constant.
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
ukasp
saiyampaliwal
rdtank
tamanna17122007
pattern-printing
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 152,
"s": 53,
"text": "For any given number n, print Hollow and solid Squares and Rhombus made with stars(*). Examples: "
},
{
"code": null,
"e": 260,
"s": 152,
"text": "Input : n = 4\nOutput : \nSolid Rhombus:\n ****\n ****\n ****\n****\n\nHollow Rhombus:\n ****\n * *\n * *\n****"
},
{
"code": null,
"e": 686,
"s": 262,
"text": "1. Solid Rhombus : Making Solid Rhombus is a bit similar to making solid square rather than the concept that for each ith row we have n-i blank spaces before stars as: – – – **** – – **** – **** **** 2. Hollow Rhombus : Formation of Hollow Rhombus uses the idea behind formation of hollow square and solid rhombus. A hollow square with n-i blank spaces before stars in each ith rows result in formation of hollow rhombus. "
},
{
"code": null,
"e": 694,
"s": 688,
"text": "C/C++"
},
{
"code": null,
"e": 702,
"s": 698,
"text": "C++"
},
{
"code": null,
"e": 707,
"s": 702,
"text": "Java"
},
{
"code": null,
"e": 716,
"s": 707,
"text": "Python 3"
},
{
"code": null,
"e": 719,
"s": 716,
"text": "C#"
},
{
"code": null,
"e": 723,
"s": 719,
"text": "PHP"
},
{
"code": null,
"e": 734,
"s": 723,
"text": "Javascript"
},
{
"code": "// C++ program to print// hollow and solid rhombus patterns #include <bits/stdc++.h>using namespace std; // Function for Solid Rhombusvoid solidRhombus(int rows){ int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) cout << \" \"; // Print stars after spaces for (j=1; j<=rows; j++) cout << \"*\"; // Move to the next line/row cout << \"\\n\"; }} // Function for Rhombusvoid hollowRhombus(int rows){ int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) cout << \" \"; // Print stars after spaces // Print stars for each solid rows if (i==1 || i==rows) for (j=1; j<=rows; j++) cout << \"*\"; // stars for hollow rows else for (j=1; j<=rows; j++) if (j==1 || j==rows) cout << \"*\"; else cout << \" \"; // Move to the next line/row cout << \"\\n\"; }} // utility program to print all patternsvoid printPattern(int rows){ cout << \"\\nSolid Rhombus:\\n\"; solidRhombus(rows); cout << \"\\nHollow Rhombus:\\n\"; hollowRhombus(rows);} // driver programint main(){ int rows = 5; printPattern (rows); return 0;}",
"e": 2135,
"s": 734,
"text": null
},
{
"code": "// Java program to print// hollow and solid rhombus patternsimport java.io.*; class GFG{ // Function for Solid Rhombus static void solidRhombus(int rows) { int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) System.out.print(\" \"); // Print stars after spaces for (j=1; j<=rows; j++) System.out.print(\"*\"); // Move to the next line/row System.out.println(); } } // Function for Hollow Rhombus static void hollowRhombus(int rows) { int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) System.out.print(\" \"); // Print stars after spaces // Print stars for each solid rows if (i==1 || i==rows) for (j=1; j<=rows; j++) System.out.print(\"*\"); // stars for hollow rows else for (j=1; j<=rows; j++) if (j==1 || j==rows) System.out.print(\"*\"); else System.out.print(\" \"); // Move to the next line/row System.out.println(); } } // utility program to print all patterns static void printPattern(int rows) { System.out.println(\"Solid Rhombus:\"); solidRhombus(rows); System.out.println(\"Hollow Rhombus:\"); hollowRhombus(rows); } // driver program public static void main (String[] args) { int rows = 5; printPattern (rows); }} // Contributed by Pramod Kumar",
"e": 3917,
"s": 2135,
"text": null
},
{
"code": "# Python 3 program to print# hollow and solid rhombus patterns # Function for Solid Rhombus def solidRhombus(rows): for i in range (1,rows + 1): # Print trailing spaces for j in range (1,rows - i + 1): print (end=\" \") # Print stars after spaces for j in range (1,rows + 1): print (\"*\",end=\"\") # Move to the next line/row print() # Function for Hollow Rhombus def hollowRhombus(rows): for i in range (1, rows + 1): # Print trailing spaces for j in range (1, rows - i + 1): print (end=\" \") # Print stars after spaces # Print stars for each solid rows if i == 1 or i == rows: for j in range (1, rows + 1): print (\"*\",end=\"\") # stars for hollow rows else: for j in range (1,rows+1): if (j == 1 or j == rows): print (\"*\",end=\"\") else: print (end=\" \") # Move to the next line/row print() # utility program to print all patternsdef printPattern(rows): print (\"Solid Rhombus:\") solidRhombus(rows) print(\"\\nHollow Rhombus:\") hollowRhombus(rows) # driver program if __name__ == \"__main__\": rows = 5 printPattern (rows)",
"e": 5319,
"s": 3917,
"text": null
},
{
"code": "// C# program to print// hollow and solid rhombus patternsusing System; class GFG{ // Function for Solid Rhombus static void solidRhombus(int rows) { int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) Console.Write(\" \"); // Print stars after spaces for (j=1; j<=rows; j++) Console.Write(\"*\"); // Move to the next line/row Console.WriteLine(); } } // Function for Hollow Rhombus static void hollowRhombus(int rows) { int i, j; for (i=1; i<=rows; i++) { // Print trailing spaces for (j=1; j<=rows - i; j++) Console.Write(\" \"); // Print stars after spaces // Print stars for each solid rows if (i==1 || i==rows) for (j=1; j<=rows; j++) Console.Write(\"*\"); // stars for hollow rows else for (j=1; j<=rows; j++) if (j==1 || j==rows) Console.Write(\"*\"); else Console.Write(\" \"); // Move to the next line/row Console.WriteLine(); } } // utility program to print all patterns static void printPattern(int rows) { Console.WriteLine(\"\\nSolid Rhombus:\\n\"); solidRhombus(rows); Console.WriteLine(\"\\nHollow Rhombus:\\n\"); hollowRhombus(rows); } // driver program public static void Main () { int rows = 5; printPattern (rows); }} // Contributed by vt_m.",
"e": 7051,
"s": 5319,
"text": null
},
{
"code": "<?php// php program to print hollow`// and solid rhombus patterns // Function for Solid Rhombusfunction solidRhombus($rows){ for ($i = 1; $i <= $rows; $i++) { // Print trailing spaces for ($j = 1; $j <= $rows - $i; $j++) echo \" \"; // Print stars after spaces for ($j = 1; $j <= $rows; $j++) echo \"*\"; // Move to the next line/row echo \"\\n\"; }} // Function for Hollow Rhombusfunction hollowRhombus($rows){ for ($i = 1; $i <= $rows; $i++) { // Print trailing spaces for ($j = 1; $j <= $rows - $i; $j++) echo \" \"; // Print stars after spaces // Print stars for each solid $rows if ($i == 1 || $i == $rows) for ($j = 1; $j <= $rows; $j++) echo \"*\"; // stars for hollow $rows else for ($j = 1; $j <= $rows; $j++) if ($j == 1 || $j == $rows) echo \"*\"; else echo \" \"; // Move to the next line/row echo \"\\n\"; }} // utility program to print// all patternsfunction printPattern($rows){ echo \"\\nSolid Rhombus:\\n\"; solidRhombus($rows); echo \"\\nHollow Rhombus:\\n\"; hollowRhombus($rows);} // Driver Code $rows = 5; printPattern ($rows); // This code is contributed by mits?>",
"e": 8479,
"s": 7051,
"text": null
},
{
"code": "<script> // JavaScript program to print // hollow and solid rhombus patterns // Function for Solid Rhombus function solidRhombus(rows) { var i, j; for (i = 1; i <= rows; i++) { // Print trailing spaces for (j = 1; j <= rows - i; j++) document.write(\" \"); // Print stars after spaces for (j = 1; j <= rows; j++) document.write(\"*\"); // Move to the next line/row document.write(\"<br>\"); } } // Function for Rhombus function hollowRhombus(rows) { var i, j; for (i = 1; i <= rows; i++) { // Print trailing spaces for (j = 1; j <= rows - i; j++) document.write(\" \"); // Print stars after spaces // Print stars for each solid rows if (i == 1 || i == rows) for (j = 1; j <= rows; j++) document.write(\"*\"); // stars for hollow rows else for (j = 1; j <= rows; j++) if (j == 1 || j == rows) document.write(\"*\"); else document.write(\" \"); // Move to the next line/row document.write(\"<br>\"); } } // utility program to print all patterns function printPattern(rows) { document.write(\"Solid Rhombus:<br>\"); solidRhombus(rows); document.write(\"Hollow Rhombus:<br>\"); hollowRhombus(rows); } // driver program var rows = 5; printPattern(rows); // This code is contributed by rdtank. </script>",
"e": 10081,
"s": 8479,
"text": null
},
{
"code": null,
"e": 10091,
"s": 10081,
"text": "Output: "
},
{
"code": null,
"e": 10203,
"s": 10091,
"text": "Solid Rhombus:\n *****\n *****\n *****\n *****\n*****\n\nHollow Rhombus:\n *****\n * *\n * *\n * *\n*****"
},
{
"code": null,
"e": 10343,
"s": 10203,
"text": "Time Complexity: O(r2), where r represents the given number of rows.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 10779,
"s": 10343,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10792,
"s": 10779,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10798,
"s": 10792,
"text": "ukasp"
},
{
"code": null,
"e": 10812,
"s": 10798,
"text": "saiyampaliwal"
},
{
"code": null,
"e": 10819,
"s": 10812,
"text": "rdtank"
},
{
"code": null,
"e": 10835,
"s": 10819,
"text": "tamanna17122007"
},
{
"code": null,
"e": 10852,
"s": 10835,
"text": "pattern-printing"
},
{
"code": null,
"e": 10871,
"s": 10852,
"text": "School Programming"
},
{
"code": null,
"e": 10888,
"s": 10871,
"text": "pattern-printing"
}
] |
Minimum and maximum number of digits required to be removed to make a given number divisible by 3 | 22 Nov, 2021
Given a numeric string S, the task is to find the minimum and the maximum number of digits that must be removed from S such that it is divisible by 3. If it is impossible to do so, then print “-1”.
Examples:
Input: S = “12345”Output:Minimum: 0Maximum: 4Explanation: The given number 12345 is divisible by 3. Therefore, the minimum digits required to be removed to make it divisible by 3 is 0. After removing digits 1, 2, 4 and 5, only 3 remains, which is divisible by 3. Therefore, the maximum number of digits required to be removed is 4.
Input: S = “44”Output:Minimum: -1Maximum: -1
Approach: The problem can be solved based on the observation that for any number to be divisible by 3, the sum of digits must also be divisible by 3. Follow the steps below to solve this problem:
Insert each digit of the given string into an array, say arr[], as (S[i] – ‘0’) % 3.
Find the count of 0s, 1s, and 2s in the array arr[].
Then, calculate the sum of digits, i.e. (arr[0] % 3) + (arr[1] % 3) + (arr[2] % 3)..... Update sum = sum % 3.
Depending on the value of sum, following three cases arise: If sum = 0: Minimum number of digits required to be removed is 0.If sum = 1: Those digits should be removed whose sum gives a remainder 1 on dividing by 3. Therefore, following situations need to be considered: If the count of 1s is greater than or equal to 1, then the minimum number of digits required to be removed is 1.If the count of 2s is greater than or equal to 2, then the minimum number of digits required to be removed will be 2 [Since (2 + 2) % 3 = 1].If sum = 3: Those digits should be removed whose sum gives a remainder 2 on dividing by 3. Therefore, following situations arise: If the count of 2s is greater than or equal to 1, then the minimum number of digits required to be removed will be 1.Otherwise, if the count of 1s is greater than or equal to 2, then the minimum number of digits to be removed will be 2 [(1 + 1) % 3 = 2].
If sum = 0: Minimum number of digits required to be removed is 0.
If sum = 1: Those digits should be removed whose sum gives a remainder 1 on dividing by 3. Therefore, following situations need to be considered: If the count of 1s is greater than or equal to 1, then the minimum number of digits required to be removed is 1.If the count of 2s is greater than or equal to 2, then the minimum number of digits required to be removed will be 2 [Since (2 + 2) % 3 = 1].
If the count of 1s is greater than or equal to 1, then the minimum number of digits required to be removed is 1.
If the count of 2s is greater than or equal to 2, then the minimum number of digits required to be removed will be 2 [Since (2 + 2) % 3 = 1].
If sum = 3: Those digits should be removed whose sum gives a remainder 2 on dividing by 3. Therefore, following situations arise: If the count of 2s is greater than or equal to 1, then the minimum number of digits required to be removed will be 1.Otherwise, if the count of 1s is greater than or equal to 2, then the minimum number of digits to be removed will be 2 [(1 + 1) % 3 = 2].
If the count of 2s is greater than or equal to 1, then the minimum number of digits required to be removed will be 1.
Otherwise, if the count of 1s is greater than or equal to 2, then the minimum number of digits to be removed will be 2 [(1 + 1) % 3 = 2].
For finding the maximum number of digits to be removed, following three cases need to be considered: If the count of 0s is greater than or equal to 1, then the maximum digits required to be removed will be (number of digits – 1).If both the count of 1s and 2s are greater than or equal to 1, then maximum digits required to be removed will be (number of digits – 2) [(1+2) % 3 = 0].If the count of either 1s or 2s is greater than or equal to 3, then maximum digits required to be removed will be (number of digits – 3) [(1+1+1) % 3 = 0, (2+2+2) % 3 = 0].
If the count of 0s is greater than or equal to 1, then the maximum digits required to be removed will be (number of digits – 1).
If both the count of 1s and 2s are greater than or equal to 1, then maximum digits required to be removed will be (number of digits – 2) [(1+2) % 3 = 0].
If the count of either 1s or 2s is greater than or equal to 3, then maximum digits required to be removed will be (number of digits – 3) [(1+1+1) % 3 = 0, (2+2+2) % 3 = 0].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum and// minimum number of digits to be// removed to make str divisible by 3void minMaxDigits(string str, int N){ // Convert the string into // array of digits int arr[N]; for (int i = 0; i < N; i++) arr[i] = (str[i] - '0') % 3; // Count of 0s, 1s, and 2s int zero = 0, one = 0, two = 0; // Traverse the array for (int i = 0; i < N; i++) { if (arr[i] == 0) zero++; if (arr[i] == 1) one++; if (arr[i] == 2) two++; } // Find the sum of digits % 3 int sum = 0; for (int i = 0; i < N; i++) { sum = (sum + arr[i]) % 3; } // Cases to find minimum number // of digits to be removed if (sum == 0) { cout << 0 << ' '; } if (sum == 1) { if (one && N > 1) cout << 1 << ' '; else if (two > 1 && N > 2) cout << 2 << ' '; else cout << -1 << ' '; } if (sum == 2) { if (two && N > 1) cout << 1 << ' '; else if (one > 1 && N > 2) cout << 2 << ' '; else cout << -1 << ' '; } // Cases to find maximum number // of digits to be removed if (zero > 0) cout << N - 1 << ' '; else if (one > 0 && two > 0) cout << N - 2 << ' '; else if (one > 2 || two > 2) cout << N - 3 << ' '; else cout << -1 << ' ';} // Driver Codeint main(){ string str = "12345"; int N = str.length(); // Function Call minMaxDigits(str, N); return 0;}
// Java program for the above approachclass GFG{ // Function to find the maximum and// minimum number of digits to be// removed to make str divisible by 3static void minMaxDigits(String str, int N){ // Convert the string into // array of digits int arr[] = new int[N]; for(int i = 0; i < N; i++) arr[i] = (str.charAt(i) - '0') % 3; // Count of 0s, 1s, and 2s int zero = 0, one = 0, two = 0; // Traverse the array for(int i = 0; i < N; i++) { if (arr[i] == 0) zero++; if (arr[i] == 1) one++; if (arr[i] == 2) two++; } // Find the sum of digits % 3 int sum = 0; for(int i = 0; i < N; i++) { sum = (sum + arr[i]) % 3; } // Cases to find minimum number // of digits to be removed if (sum == 0) { System.out.print(0 + " "); } if (sum == 1) { if ((one != 0) && (N > 1)) System.out.print(1 + " "); else if (two > 1 && N > 2) System.out.print(2 + " "); else System.out.print(-1 + " "); } if (sum == 2) { if (two != 0 && N > 1) System.out.print(1 + " "); else if (one > 1 && N > 2) System.out.print(2 + " "); else System.out.print(-1 + " "); } // Cases to find maximum number // of digits to be removed if (zero > 0) System.out.print(N - 1 + " "); else if (one > 0 && two > 0) System.out.print(N - 2 + " "); else if (one > 2 || two > 2) System.out.print(N - 3 + " "); else System.out.print(-1 + " ");} // Driver codepublic static void main(String[] args){ String str = "12345"; int N = str.length(); // Function Call minMaxDigits(str, N);}} // This code is contributed by sanjoy_62
# Python3 program for the above approach # Function to find the maximum and# minimum number of digits to be# removed to make str divisible by 3def minMaxDigits(str, N): # Convert the string into # array of digits arr = [0]* N for i in range(N): arr[i] = (ord(str[i]) - ord('0')) % 3 # Count of 0s, 1s, and 2s zero = 0 one = 0 two = 0 # Traverse the array for i in range(N): if (arr[i] == 0): zero += 1 if (arr[i] == 1): one += 1 if (arr[i] == 2): two += 1 # Find the sum of digits % 3 sum = 0 for i in range(N): sum = (sum + arr[i]) % 3 # Cases to find minimum number # of digits to be removed if (sum == 0): print("0", end = " ") if (sum == 1): if (one and N > 1): print("1", end = " ") elif (two > 1 and N > 2): print("2", end = " ") else: print("-1", end = " ") if (sum == 2): if (two and N > 1): print("1", end = " ") elif (one > 1 and N > 2): print("2", end = " ") else: print("-1", end = " ") # Cases to find maximum number # of digits to be removed if (zero > 0): print(N - 1, end = " ") elif (one > 0 and two > 0): print(N - 2, end = " ") elif (one > 2 or two > 2): print(N - 3, end = " ") else : print("-1", end = " ") # Driver Codestr = "12345"N = len(str) # Function CallminMaxDigits(str, N) # This code is contributed by susmitakundugoaldanga
// C# program for the above approachusing System; class GFG{ // Function to find the maximum and// minimum number of digits to be// removed to make str divisible by 3static void minMaxDigits(string str, int N){ // Convert the string into // array of digits int[] arr = new int[N]; for(int i = 0; i < N; i++) arr[i] = (str[i] - '0') % 3; // Count of 0s, 1s, and 2s int zero = 0, one = 0, two = 0; // Traverse the array for(int i = 0; i < N; i++) { if (arr[i] == 0) zero++; if (arr[i] == 1) one++; if (arr[i] == 2) two++; } // Find the sum of digits % 3 int sum = 0; for(int i = 0; i < N; i++) { sum = (sum + arr[i]) % 3; } // Cases to find minimum number // of digits to be removed if (sum == 0) { Console.Write(0 + " "); } if (sum == 1) { if ((one != 0) && (N > 1)) Console.Write(1 + " "); else if (two > 1 && N > 2) Console.Write(2 + " "); else Console.Write(-1 + " "); } if (sum == 2) { if (two != 0 && N > 1) Console.Write(1 + " "); else if (one > 1 && N > 2) Console.Write(2 + " "); else Console.Write(-1 + " "); } // Cases to find maximum number // of digits to be removed if (zero > 0) Console.Write(N - 1 + " "); else if (one > 0 && two > 0) Console.Write(N - 2 + " "); else if (one > 2 || two > 2) Console.Write(N - 3 + " "); else Console.Write(-1 + " ");} // Driver codepublic static void Main(){ string str = "12345"; int N = str.Length; // Function Call minMaxDigits(str, N);}} // This code is contributed by code_hunt
<script> // Javascript program for the above approach // Function to find the maximum and// minimum number of digits to be// removed to make str divisible by 3function minMaxDigits(str, N){ // Convert the string into // array of digits let arr = []; for(let i = 0; i < N; i++) arr[i] = (str[i] - '0') % 3; // Count of 0s, 1s, and 2s let zero = 0, one = 0, two = 0; // Traverse the array for(let i = 0; i < N; i++) { if (arr[i] == 0) zero++; if (arr[i] == 1) one++; if (arr[i] == 2) two++; } // Find the sum of digits % 3 let sum = 0; for(let i = 0; i < N; i++) { sum = (sum + arr[i]) % 3; } // Cases to find minimum number // of digits to be removed if (sum == 0) { document.write(0 + " "); } if (sum == 1) { if ((one != 0) && (N > 1)) document.write(1 + " "); else if (two > 1 && N > 2) document.write(2 + " "); else document.write(-1 + " "); } if (sum == 2) { if (two != 0 && N > 1) document.write(1 + " "); else if (one > 1 && N > 2) document.write(2 + " "); else document.write(-1 + " "); } // Cases to find maximum number // of digits to be removed if (zero > 0) document.write(N - 1 + " "); else if (one > 0 && two > 0) document.write(N - 2 + " "); else if (one > 2 || two > 2) document.write(N - 3 + " "); else document.write(-1 + " ");} // Driver codelet str = "12345";let N = str.length; // Function CallminMaxDigits(str, N); // This code is contributed by avijitmondal1998 </script>
0 4
Time Complexity: O(log10N)Auxiliary Space: O(log10N)
sanjoy_62
code_hunt
susmitakundugoaldanga
avijitmondal1998
Kirti_Mangal
divisibility
Number Divisibility
Arrays
Mathematical
Strings
Arrays
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 252,
"s": 54,
"text": "Given a numeric string S, the task is to find the minimum and the maximum number of digits that must be removed from S such that it is divisible by 3. If it is impossible to do so, then print “-1”."
},
{
"code": null,
"e": 262,
"s": 252,
"text": "Examples:"
},
{
"code": null,
"e": 594,
"s": 262,
"text": "Input: S = “12345”Output:Minimum: 0Maximum: 4Explanation: The given number 12345 is divisible by 3. Therefore, the minimum digits required to be removed to make it divisible by 3 is 0. After removing digits 1, 2, 4 and 5, only 3 remains, which is divisible by 3. Therefore, the maximum number of digits required to be removed is 4."
},
{
"code": null,
"e": 639,
"s": 594,
"text": "Input: S = “44”Output:Minimum: -1Maximum: -1"
},
{
"code": null,
"e": 835,
"s": 639,
"text": "Approach: The problem can be solved based on the observation that for any number to be divisible by 3, the sum of digits must also be divisible by 3. Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 920,
"s": 835,
"text": "Insert each digit of the given string into an array, say arr[], as (S[i] – ‘0’) % 3."
},
{
"code": null,
"e": 973,
"s": 920,
"text": "Find the count of 0s, 1s, and 2s in the array arr[]."
},
{
"code": null,
"e": 1083,
"s": 973,
"text": "Then, calculate the sum of digits, i.e. (arr[0] % 3) + (arr[1] % 3) + (arr[2] % 3)..... Update sum = sum % 3."
},
{
"code": null,
"e": 1992,
"s": 1083,
"text": "Depending on the value of sum, following three cases arise: If sum = 0: Minimum number of digits required to be removed is 0.If sum = 1: Those digits should be removed whose sum gives a remainder 1 on dividing by 3. Therefore, following situations need to be considered: If the count of 1s is greater than or equal to 1, then the minimum number of digits required to be removed is 1.If the count of 2s is greater than or equal to 2, then the minimum number of digits required to be removed will be 2 [Since (2 + 2) % 3 = 1].If sum = 3: Those digits should be removed whose sum gives a remainder 2 on dividing by 3. Therefore, following situations arise: If the count of 2s is greater than or equal to 1, then the minimum number of digits required to be removed will be 1.Otherwise, if the count of 1s is greater than or equal to 2, then the minimum number of digits to be removed will be 2 [(1 + 1) % 3 = 2]."
},
{
"code": null,
"e": 2058,
"s": 1992,
"text": "If sum = 0: Minimum number of digits required to be removed is 0."
},
{
"code": null,
"e": 2458,
"s": 2058,
"text": "If sum = 1: Those digits should be removed whose sum gives a remainder 1 on dividing by 3. Therefore, following situations need to be considered: If the count of 1s is greater than or equal to 1, then the minimum number of digits required to be removed is 1.If the count of 2s is greater than or equal to 2, then the minimum number of digits required to be removed will be 2 [Since (2 + 2) % 3 = 1]."
},
{
"code": null,
"e": 2571,
"s": 2458,
"text": "If the count of 1s is greater than or equal to 1, then the minimum number of digits required to be removed is 1."
},
{
"code": null,
"e": 2713,
"s": 2571,
"text": "If the count of 2s is greater than or equal to 2, then the minimum number of digits required to be removed will be 2 [Since (2 + 2) % 3 = 1]."
},
{
"code": null,
"e": 3098,
"s": 2713,
"text": "If sum = 3: Those digits should be removed whose sum gives a remainder 2 on dividing by 3. Therefore, following situations arise: If the count of 2s is greater than or equal to 1, then the minimum number of digits required to be removed will be 1.Otherwise, if the count of 1s is greater than or equal to 2, then the minimum number of digits to be removed will be 2 [(1 + 1) % 3 = 2]."
},
{
"code": null,
"e": 3216,
"s": 3098,
"text": "If the count of 2s is greater than or equal to 1, then the minimum number of digits required to be removed will be 1."
},
{
"code": null,
"e": 3354,
"s": 3216,
"text": "Otherwise, if the count of 1s is greater than or equal to 2, then the minimum number of digits to be removed will be 2 [(1 + 1) % 3 = 2]."
},
{
"code": null,
"e": 3909,
"s": 3354,
"text": "For finding the maximum number of digits to be removed, following three cases need to be considered: If the count of 0s is greater than or equal to 1, then the maximum digits required to be removed will be (number of digits – 1).If both the count of 1s and 2s are greater than or equal to 1, then maximum digits required to be removed will be (number of digits – 2) [(1+2) % 3 = 0].If the count of either 1s or 2s is greater than or equal to 3, then maximum digits required to be removed will be (number of digits – 3) [(1+1+1) % 3 = 0, (2+2+2) % 3 = 0]."
},
{
"code": null,
"e": 4038,
"s": 3909,
"text": "If the count of 0s is greater than or equal to 1, then the maximum digits required to be removed will be (number of digits – 1)."
},
{
"code": null,
"e": 4192,
"s": 4038,
"text": "If both the count of 1s and 2s are greater than or equal to 1, then maximum digits required to be removed will be (number of digits – 2) [(1+2) % 3 = 0]."
},
{
"code": null,
"e": 4365,
"s": 4192,
"text": "If the count of either 1s or 2s is greater than or equal to 3, then maximum digits required to be removed will be (number of digits – 3) [(1+1+1) % 3 = 0, (2+2+2) % 3 = 0]."
},
{
"code": null,
"e": 4416,
"s": 4365,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 4420,
"s": 4416,
"text": "C++"
},
{
"code": null,
"e": 4425,
"s": 4420,
"text": "Java"
},
{
"code": null,
"e": 4433,
"s": 4425,
"text": "Python3"
},
{
"code": null,
"e": 4436,
"s": 4433,
"text": "C#"
},
{
"code": null,
"e": 4447,
"s": 4436,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum and// minimum number of digits to be// removed to make str divisible by 3void minMaxDigits(string str, int N){ // Convert the string into // array of digits int arr[N]; for (int i = 0; i < N; i++) arr[i] = (str[i] - '0') % 3; // Count of 0s, 1s, and 2s int zero = 0, one = 0, two = 0; // Traverse the array for (int i = 0; i < N; i++) { if (arr[i] == 0) zero++; if (arr[i] == 1) one++; if (arr[i] == 2) two++; } // Find the sum of digits % 3 int sum = 0; for (int i = 0; i < N; i++) { sum = (sum + arr[i]) % 3; } // Cases to find minimum number // of digits to be removed if (sum == 0) { cout << 0 << ' '; } if (sum == 1) { if (one && N > 1) cout << 1 << ' '; else if (two > 1 && N > 2) cout << 2 << ' '; else cout << -1 << ' '; } if (sum == 2) { if (two && N > 1) cout << 1 << ' '; else if (one > 1 && N > 2) cout << 2 << ' '; else cout << -1 << ' '; } // Cases to find maximum number // of digits to be removed if (zero > 0) cout << N - 1 << ' '; else if (one > 0 && two > 0) cout << N - 2 << ' '; else if (one > 2 || two > 2) cout << N - 3 << ' '; else cout << -1 << ' ';} // Driver Codeint main(){ string str = \"12345\"; int N = str.length(); // Function Call minMaxDigits(str, N); return 0;}",
"e": 6074,
"s": 4447,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to find the maximum and// minimum number of digits to be// removed to make str divisible by 3static void minMaxDigits(String str, int N){ // Convert the string into // array of digits int arr[] = new int[N]; for(int i = 0; i < N; i++) arr[i] = (str.charAt(i) - '0') % 3; // Count of 0s, 1s, and 2s int zero = 0, one = 0, two = 0; // Traverse the array for(int i = 0; i < N; i++) { if (arr[i] == 0) zero++; if (arr[i] == 1) one++; if (arr[i] == 2) two++; } // Find the sum of digits % 3 int sum = 0; for(int i = 0; i < N; i++) { sum = (sum + arr[i]) % 3; } // Cases to find minimum number // of digits to be removed if (sum == 0) { System.out.print(0 + \" \"); } if (sum == 1) { if ((one != 0) && (N > 1)) System.out.print(1 + \" \"); else if (two > 1 && N > 2) System.out.print(2 + \" \"); else System.out.print(-1 + \" \"); } if (sum == 2) { if (two != 0 && N > 1) System.out.print(1 + \" \"); else if (one > 1 && N > 2) System.out.print(2 + \" \"); else System.out.print(-1 + \" \"); } // Cases to find maximum number // of digits to be removed if (zero > 0) System.out.print(N - 1 + \" \"); else if (one > 0 && two > 0) System.out.print(N - 2 + \" \"); else if (one > 2 || two > 2) System.out.print(N - 3 + \" \"); else System.out.print(-1 + \" \");} // Driver codepublic static void main(String[] args){ String str = \"12345\"; int N = str.length(); // Function Call minMaxDigits(str, N);}} // This code is contributed by sanjoy_62",
"e": 7895,
"s": 6074,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the maximum and# minimum number of digits to be# removed to make str divisible by 3def minMaxDigits(str, N): # Convert the string into # array of digits arr = [0]* N for i in range(N): arr[i] = (ord(str[i]) - ord('0')) % 3 # Count of 0s, 1s, and 2s zero = 0 one = 0 two = 0 # Traverse the array for i in range(N): if (arr[i] == 0): zero += 1 if (arr[i] == 1): one += 1 if (arr[i] == 2): two += 1 # Find the sum of digits % 3 sum = 0 for i in range(N): sum = (sum + arr[i]) % 3 # Cases to find minimum number # of digits to be removed if (sum == 0): print(\"0\", end = \" \") if (sum == 1): if (one and N > 1): print(\"1\", end = \" \") elif (two > 1 and N > 2): print(\"2\", end = \" \") else: print(\"-1\", end = \" \") if (sum == 2): if (two and N > 1): print(\"1\", end = \" \") elif (one > 1 and N > 2): print(\"2\", end = \" \") else: print(\"-1\", end = \" \") # Cases to find maximum number # of digits to be removed if (zero > 0): print(N - 1, end = \" \") elif (one > 0 and two > 0): print(N - 2, end = \" \") elif (one > 2 or two > 2): print(N - 3, end = \" \") else : print(\"-1\", end = \" \") # Driver Codestr = \"12345\"N = len(str) # Function CallminMaxDigits(str, N) # This code is contributed by susmitakundugoaldanga",
"e": 9500,
"s": 7895,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the maximum and// minimum number of digits to be// removed to make str divisible by 3static void minMaxDigits(string str, int N){ // Convert the string into // array of digits int[] arr = new int[N]; for(int i = 0; i < N; i++) arr[i] = (str[i] - '0') % 3; // Count of 0s, 1s, and 2s int zero = 0, one = 0, two = 0; // Traverse the array for(int i = 0; i < N; i++) { if (arr[i] == 0) zero++; if (arr[i] == 1) one++; if (arr[i] == 2) two++; } // Find the sum of digits % 3 int sum = 0; for(int i = 0; i < N; i++) { sum = (sum + arr[i]) % 3; } // Cases to find minimum number // of digits to be removed if (sum == 0) { Console.Write(0 + \" \"); } if (sum == 1) { if ((one != 0) && (N > 1)) Console.Write(1 + \" \"); else if (two > 1 && N > 2) Console.Write(2 + \" \"); else Console.Write(-1 + \" \"); } if (sum == 2) { if (two != 0 && N > 1) Console.Write(1 + \" \"); else if (one > 1 && N > 2) Console.Write(2 + \" \"); else Console.Write(-1 + \" \"); } // Cases to find maximum number // of digits to be removed if (zero > 0) Console.Write(N - 1 + \" \"); else if (one > 0 && two > 0) Console.Write(N - 2 + \" \"); else if (one > 2 || two > 2) Console.Write(N - 3 + \" \"); else Console.Write(-1 + \" \");} // Driver codepublic static void Main(){ string str = \"12345\"; int N = str.Length; // Function Call minMaxDigits(str, N);}} // This code is contributed by code_hunt",
"e": 11292,
"s": 9500,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the maximum and// minimum number of digits to be// removed to make str divisible by 3function minMaxDigits(str, N){ // Convert the string into // array of digits let arr = []; for(let i = 0; i < N; i++) arr[i] = (str[i] - '0') % 3; // Count of 0s, 1s, and 2s let zero = 0, one = 0, two = 0; // Traverse the array for(let i = 0; i < N; i++) { if (arr[i] == 0) zero++; if (arr[i] == 1) one++; if (arr[i] == 2) two++; } // Find the sum of digits % 3 let sum = 0; for(let i = 0; i < N; i++) { sum = (sum + arr[i]) % 3; } // Cases to find minimum number // of digits to be removed if (sum == 0) { document.write(0 + \" \"); } if (sum == 1) { if ((one != 0) && (N > 1)) document.write(1 + \" \"); else if (two > 1 && N > 2) document.write(2 + \" \"); else document.write(-1 + \" \"); } if (sum == 2) { if (two != 0 && N > 1) document.write(1 + \" \"); else if (one > 1 && N > 2) document.write(2 + \" \"); else document.write(-1 + \" \"); } // Cases to find maximum number // of digits to be removed if (zero > 0) document.write(N - 1 + \" \"); else if (one > 0 && two > 0) document.write(N - 2 + \" \"); else if (one > 2 || two > 2) document.write(N - 3 + \" \"); else document.write(-1 + \" \");} // Driver codelet str = \"12345\";let N = str.length; // Function CallminMaxDigits(str, N); // This code is contributed by avijitmondal1998 </script>",
"e": 13030,
"s": 11292,
"text": null
},
{
"code": null,
"e": 13034,
"s": 13030,
"text": "0 4"
},
{
"code": null,
"e": 13089,
"s": 13036,
"text": "Time Complexity: O(log10N)Auxiliary Space: O(log10N)"
},
{
"code": null,
"e": 13099,
"s": 13089,
"text": "sanjoy_62"
},
{
"code": null,
"e": 13109,
"s": 13099,
"text": "code_hunt"
},
{
"code": null,
"e": 13131,
"s": 13109,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 13148,
"s": 13131,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 13161,
"s": 13148,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 13174,
"s": 13161,
"text": "divisibility"
},
{
"code": null,
"e": 13194,
"s": 13174,
"text": "Number Divisibility"
},
{
"code": null,
"e": 13201,
"s": 13194,
"text": "Arrays"
},
{
"code": null,
"e": 13214,
"s": 13201,
"text": "Mathematical"
},
{
"code": null,
"e": 13222,
"s": 13214,
"text": "Strings"
},
{
"code": null,
"e": 13229,
"s": 13222,
"text": "Arrays"
},
{
"code": null,
"e": 13237,
"s": 13229,
"text": "Strings"
},
{
"code": null,
"e": 13250,
"s": 13237,
"text": "Mathematical"
}
] |
Loss when two items are sold at same price and same percentage profit/loss | 09 Jun, 2022
Given the Selling price i.e ‘SP’ of the two items each. One item is sold at ‘P%’ Profit and other at ‘P%’ Loss. The task is to find out the overall Loss.Examples:
Input: SP = 2400, P = 30%
Output: Loss = 474.725
Input: SP = 5000, P = 10%
Output: Loss = 101.01
Approach:
How does the above formula work? For profit making item : With selling price (100 + P), we get P profit. With selling price SP, we get SP * (P/(100 + P)) profitFor loss making item : With selling price (100 – P), we get P loss. With selling price SP, we get SP * (P/(100 – P)) lossNet Loss = Total Loss – Total Profit = SP * (P/(100 – P)) – SP * (P/(100 + P)) = (SP * P * P * 2) / (100*100 – P*P)Note: The above formula is applicable only when the Cost price of both the items are different. If CP of both the items are same then, in that case, there is ‘No profit No loss’.Below is the implementation of the above approach
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach.#include <bits/stdc++.h>using namespace std; // Function that will// find lossvoid Loss(int SP, int P){ float loss = 0; loss = (2 * P * P * SP) / float(100 * 100 - P * P); cout << "Loss = " << loss;} // Driver Codeint main(){ int SP = 2400, P = 30; // Calling Function Loss(SP, P); return 0;}
// Java implementation of above approach.class GFG{ // Function that will// find lossstatic void Loss(int SP, int P){ float loss = 0; loss = (float)(2 * P * P * SP) / (100 * 100 - P * P); System.out.println("Loss = " + loss);} // Driver Codepublic static void main(String[] args){ int SP = 2400, P = 30; // Calling Function Loss(SP, P);}} // This code has been contributed by 29AjayKumar
# Python3 implementation of above approach. # Function that will find lossdef Loss(SP, P): loss = 0 loss = ((2 * P * P * SP) / (100 * 100 - P * P)) print("Loss =", round(loss, 3)) # Driver Codeif __name__ == "__main__": SP, P = 2400, 30 # Calling Function Loss(SP, P) # This code is contributed by Rituraj Jain
// C# implementation of above approach.class GFG{ // Function that will// find lossstatic void Loss(int SP, int P){ double loss = 0; loss = (double)(2 * P * P * SP) / (100 * 100 - P * P); System.Console.WriteLine("Loss = " + System.Math.Round(loss,3));} // Driver Codestatic void Main(){ int SP = 2400, P = 30; // Calling Function Loss(SP, P);}} // This code has been contributed by mits
<?php// PHP implementation of above approach. // Function that will find lossfunction Loss($SP, $P){ $loss = 0; $loss = ((2 * $P * $P * $SP) / (100 * 100 - $P * $P)); print("Loss = " . round($loss, 3));} // Driver Code$SP = 2400;$P = 30; // Calling FunctionLoss($SP, $P); // This code is contributed by mits?>
<script> // javascript implementation of above approach.// Function that will// find loss function Loss(SP , P) { var loss = 0; loss = (2 * P * P * SP) / (100 * 100 - P * P); document.write("Loss = " + loss.toFixed(3)); } // Driver Code var SP = 2400, P = 30; // Calling Function Loss(SP, P); // This code contributed by gauravrajput1 </script>
Loss = 474.725
Time Complexity: O(1)Auxiliary Space: O(1)
rituraj_jain
Mithun Kumar
29AjayKumar
nidhi_biet
GauravRajput1
subham348
Profit and Loss
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 218,
"s": 53,
"text": "Given the Selling price i.e ‘SP’ of the two items each. One item is sold at ‘P%’ Profit and other at ‘P%’ Loss. The task is to find out the overall Loss.Examples: "
},
{
"code": null,
"e": 318,
"s": 218,
"text": "Input: SP = 2400, P = 30% \nOutput: Loss = 474.725\n\nInput: SP = 5000, P = 10%\nOutput: Loss = 101.01"
},
{
"code": null,
"e": 331,
"s": 320,
"text": "Approach: "
},
{
"code": null,
"e": 956,
"s": 331,
"text": "How does the above formula work? For profit making item : With selling price (100 + P), we get P profit. With selling price SP, we get SP * (P/(100 + P)) profitFor loss making item : With selling price (100 – P), we get P loss. With selling price SP, we get SP * (P/(100 – P)) lossNet Loss = Total Loss – Total Profit = SP * (P/(100 – P)) – SP * (P/(100 + P)) = (SP * P * P * 2) / (100*100 – P*P)Note: The above formula is applicable only when the Cost price of both the items are different. If CP of both the items are same then, in that case, there is ‘No profit No loss’.Below is the implementation of the above approach "
},
{
"code": null,
"e": 960,
"s": 956,
"text": "C++"
},
{
"code": null,
"e": 965,
"s": 960,
"text": "Java"
},
{
"code": null,
"e": 973,
"s": 965,
"text": "Python3"
},
{
"code": null,
"e": 976,
"s": 973,
"text": "C#"
},
{
"code": null,
"e": 980,
"s": 976,
"text": "PHP"
},
{
"code": null,
"e": 991,
"s": 980,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach.#include <bits/stdc++.h>using namespace std; // Function that will// find lossvoid Loss(int SP, int P){ float loss = 0; loss = (2 * P * P * SP) / float(100 * 100 - P * P); cout << \"Loss = \" << loss;} // Driver Codeint main(){ int SP = 2400, P = 30; // Calling Function Loss(SP, P); return 0;}",
"e": 1350,
"s": 991,
"text": null
},
{
"code": "// Java implementation of above approach.class GFG{ // Function that will// find lossstatic void Loss(int SP, int P){ float loss = 0; loss = (float)(2 * P * P * SP) / (100 * 100 - P * P); System.out.println(\"Loss = \" + loss);} // Driver Codepublic static void main(String[] args){ int SP = 2400, P = 30; // Calling Function Loss(SP, P);}} // This code has been contributed by 29AjayKumar",
"e": 1760,
"s": 1350,
"text": null
},
{
"code": "# Python3 implementation of above approach. # Function that will find lossdef Loss(SP, P): loss = 0 loss = ((2 * P * P * SP) / (100 * 100 - P * P)) print(\"Loss =\", round(loss, 3)) # Driver Codeif __name__ == \"__main__\": SP, P = 2400, 30 # Calling Function Loss(SP, P) # This code is contributed by Rituraj Jain",
"e": 2107,
"s": 1760,
"text": null
},
{
"code": "// C# implementation of above approach.class GFG{ // Function that will// find lossstatic void Loss(int SP, int P){ double loss = 0; loss = (double)(2 * P * P * SP) / (100 * 100 - P * P); System.Console.WriteLine(\"Loss = \" + System.Math.Round(loss,3));} // Driver Codestatic void Main(){ int SP = 2400, P = 30; // Calling Function Loss(SP, P);}} // This code has been contributed by mits",
"e": 2544,
"s": 2107,
"text": null
},
{
"code": "<?php// PHP implementation of above approach. // Function that will find lossfunction Loss($SP, $P){ $loss = 0; $loss = ((2 * $P * $P * $SP) / (100 * 100 - $P * $P)); print(\"Loss = \" . round($loss, 3));} // Driver Code$SP = 2400;$P = 30; // Calling FunctionLoss($SP, $P); // This code is contributed by mits?>",
"e": 2877,
"s": 2544,
"text": null
},
{
"code": "<script> // javascript implementation of above approach.// Function that will// find loss function Loss(SP , P) { var loss = 0; loss = (2 * P * P * SP) / (100 * 100 - P * P); document.write(\"Loss = \" + loss.toFixed(3)); } // Driver Code var SP = 2400, P = 30; // Calling Function Loss(SP, P); // This code contributed by gauravrajput1 </script>",
"e": 3284,
"s": 2877,
"text": null
},
{
"code": null,
"e": 3299,
"s": 3284,
"text": "Loss = 474.725"
},
{
"code": null,
"e": 3342,
"s": 3299,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3355,
"s": 3342,
"text": "rituraj_jain"
},
{
"code": null,
"e": 3368,
"s": 3355,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 3380,
"s": 3368,
"text": "29AjayKumar"
},
{
"code": null,
"e": 3391,
"s": 3380,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3405,
"s": 3391,
"text": "GauravRajput1"
},
{
"code": null,
"e": 3415,
"s": 3405,
"text": "subham348"
},
{
"code": null,
"e": 3431,
"s": 3415,
"text": "Profit and Loss"
},
{
"code": null,
"e": 3444,
"s": 3431,
"text": "Mathematical"
},
{
"code": null,
"e": 3463,
"s": 3444,
"text": "School Programming"
},
{
"code": null,
"e": 3476,
"s": 3463,
"text": "Mathematical"
}
] |
Program for Muller Method | 26 Apr, 2021
Given a function f(x) on floating number x and three initial distinct guesses for root of the function, find the root of function. Here, f(x) can be an algebraic or transcendental function.Examples:
Input : A function f(x) = x + 2x + 10x - 20
and three initial guesses - 0, 1 and 2 .
Output : The value of the root is 1.3688 or
any other value within permittable deviation
from the root.
Input : A function f(x) = x - 5x + 2
and three initial guesses - 0, 1 and 2 .
Output :The value of the root is 0.4021 or
any other value within permittable deviation
from the root.
Muller Method
Muller Method is a root-finding algorithm for finding the root of a equation of the form, f(x)=0. It was discovered by David E. Muller in 1956.It begins with three initial assumptions of the root, and then constructing a parabola through these three points, and takes the intersection of the x-axis with the parabola to be the next approximation. This process continues until a root with the desired level of accuracy is found .
Why to learn Muller’s Method?
Muller Method, being one of the root-finding method along with the other ones like Bisection Method, Regula – Falsi Method, Secant Method and Newton – Raphson Method. But, it offers certain advantages over these methods, as follows –
The rate of convergence, i.e., how much closer we move to the root at each step, is approximately 1.84 in Muller Method, whereas it is 1.62 for secant method, and linear, i.e., 1 for both Regula – falsi Method and bisection method . So, Muller Method is faster than Bisection, Regula – Falsi and Secant method.Although, it is slower than Newton – Raphson’s Method, which has a rate of convergence of 2, but it overcomes one of the biggest drawbacks of Newton-Raphson Method, i.e., computation of derivative at each step.
The rate of convergence, i.e., how much closer we move to the root at each step, is approximately 1.84 in Muller Method, whereas it is 1.62 for secant method, and linear, i.e., 1 for both Regula – falsi Method and bisection method . So, Muller Method is faster than Bisection, Regula – Falsi and Secant method.
Although, it is slower than Newton – Raphson’s Method, which has a rate of convergence of 2, but it overcomes one of the biggest drawbacks of Newton-Raphson Method, i.e., computation of derivative at each step.
So, this shows that Muller Method is an efficient method in calculating root of the function.
Algorithm And Its Working
Assume any three distinct initial roots of the function, let it be x0, x1 and x2. Now, draw a second degree polynomial, i.e., a parabola, through the values of function f(x) for these points – x0, x1 and x2. The equation of the parabola, p(x), through these points is as follows- p(x) = c + b(x – x) + a(x – x), where a, b and c are constants.
Assume any three distinct initial roots of the function, let it be x0, x1 and x2.
Now, draw a second degree polynomial, i.e., a parabola, through the values of function f(x) for these points – x0, x1 and x2. The equation of the parabola, p(x), through these points is as follows- p(x) = c + b(x – x) + a(x – x), where a, b and c are constants.
After drawing the parabola, then find the intersection of this parabola with the x-axis, let us say x3 . Finding the intersection of parabola with the x-axis, i.e., x3: To find x, the root of p(x), where p(x) = c + b(x – x) + a(x – x), such that p(x) = c + b(x– x) + a(x– x)= 0, apply the quadratic formula to p(x).Since, there will be two roots, but we have to take that one which is closer to x.To avoid round-off errors due to subtraction of nearby equal numbers, use the following equation:Now, since, root of p(x) has to be closer to x, so we have to take that value which has a greater denominator out of the two values possible from the above equation.To find a, b and c for the above equation, put x in p(x) as x, xand x, and let these values be p(x), p(x) and p(x), which are as follows-p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= c = f(x). So, we have three equations and three variables – a, b, c. After solving them to found out the values of these variables, we get the following values of a, b and c-
After drawing the parabola, then find the intersection of this parabola with the x-axis, let us say x3 .
Finding the intersection of parabola with the x-axis, i.e., x3: To find x, the root of p(x), where p(x) = c + b(x – x) + a(x – x), such that p(x) = c + b(x– x) + a(x– x)= 0, apply the quadratic formula to p(x).Since, there will be two roots, but we have to take that one which is closer to x.To avoid round-off errors due to subtraction of nearby equal numbers, use the following equation:Now, since, root of p(x) has to be closer to x, so we have to take that value which has a greater denominator out of the two values possible from the above equation.To find a, b and c for the above equation, put x in p(x) as x, xand x, and let these values be p(x), p(x) and p(x), which are as follows-p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= c = f(x). So, we have three equations and three variables – a, b, c. After solving them to found out the values of these variables, we get the following values of a, b and c-
To find x, the root of p(x), where p(x) = c + b(x – x) + a(x – x), such that p(x) = c + b(x– x) + a(x– x)= 0, apply the quadratic formula to p(x).Since, there will be two roots, but we have to take that one which is closer to x.To avoid round-off errors due to subtraction of nearby equal numbers, use the following equation:Now, since, root of p(x) has to be closer to x, so we have to take that value which has a greater denominator out of the two values possible from the above equation.
To find a, b and c for the above equation, put x in p(x) as x, xand x, and let these values be p(x), p(x) and p(x), which are as follows-p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= c = f(x).
So, we have three equations and three variables – a, b, c. After solving them to found out the values of these variables, we get the following values of a, b and c-
c = p(x) = f(x) .
b = (d*(h) - d*(h) ) / ( hh * (h - h)) .
a = (d*(h) - d*(h)) / ( hh * (h - h)).
where, d= p(x) – p(x) = f(x) – f(x) d= p(x) – p(x) = f(x) – f(x) h= x– xh= x– x
Now, put these values in the expression for x– x, and obtain x. This is how root of p(x) = xis obtained.
If xis very close to xwithin the permittable error, then xbecomes the root of f(x), otherwise, keep repeating the process of finding the next x, with previous x, xand xas the new x, xand x.
If xis very close to xwithin the permittable error, then xbecomes the root of f(x), otherwise, keep repeating the process of finding the next x, with previous x, xand xas the new x, xand x.
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find root of a function, f(x)#include<bits/stdc++.h>using namespace std; const int MAX_ITERATIONS = 10000; // Function to calculate f(x)float f(float x){ // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*pow(x, 3) + 2*x*x + 10*x - 20;} void Muller(float a, float b, float c){ int i; float res; for (i = 0;;++i) { // Calculating various constants required // to calculate x3 float f1 = f(a); float f2 = f(b); float f3 = f(c); float d1 = f1 - f3; float d2 = f2 - f3; float h1 = a - c; float h2 = b - c; float a0 = f3; float a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2))) / ((h1*h2) * (h1-h2))); float a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); float x = ((-2*a0) / (a1 + abs(sqrt(a1*a1-4*a0*a2)))); float y = ((-2*a0) / (a1-abs(sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) res = x + c; else res = y + c; // checking for resemblance of x3 with x2 till // two decimal places float m = res*100; float n = c*100; m = floor(m); n = floor(n); if (m == n) break; a = b; b = c; c = res; if (i > MAX_ITERATIONS) { cout << "Root cannot be found using" << " Muller's method"; break; } } if (i <= MAX_ITERATIONS) cout << "The value of the root is " << res;} // Driver main functionint main(){ float a = 0, b = 1, c = 2; Muller(a, b, c); return 0;}
// Java Program to find root of a function, f(x)import java.io.*;import static java.lang.Math.*; class Muller{ static final int MAX_ITERATIONS = 10000; // function to calculate f(x) static double f(double x) { // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*pow(x, 3) + 2*x*x + 10*x - 20; } static void Muller(double a, double b, double c) { int i; double res; for (i = 0;; ++i) { // Calculating various constants required // to calculate x3 double f1 = f(a); double f2 = f(b); double f3 = f(c); double d1 = f1 - f3; double d2 = f2 - f3; double h1 = a - c; double h2 = b - c; double a0 = f3; double a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2))) / ((h1*h2) * (h1-h2))); double a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); double x = ((-2*a0)/(a1 + abs(sqrt(a1*a1-4*a0*a2)))); double y = ((-2*a0)/(a1-abs(sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) res = x + c; else res = y + c; // checking for resemblance of x3 with x2 till // two decimal places double m = res*100; double n = c*100; m = floor(m); n = floor(n); if (m == n) break; a = b; b = c; c = res; if (i > MAX_ITERATIONS) { System.out.println("Root cannot be found using" + " Muller's method"); break; } } if (i <= MAX_ITERATIONS) System.out.println("The value of the root is " + res); } // Driver main function public static void main(String args[]) { double a = 0, b = 1, c = 2; Muller(a, b, c); }}
# Python3 Program to find root of# a function, f(x)import math; MAX_ITERATIONS = 10000; # Function to calculate f(x)def f(x): # Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return (1 * pow(x, 3) + 2 * x * x + 10 * x - 20); def Muller(a, b, c): res = 0; i = 0; while (True): # Calculating various constants # required to calculate x3 f1 = f(a); f2 = f(b); f3 = f(c); d1 = f1 - f3; d2 = f2 - f3; h1 = a - c; h2 = b - c; a0 = f3; a1 = (((d2 * pow(h1, 2)) - (d1 * pow(h2, 2))) / ((h1 * h2) * (h1 - h2))); a2 = (((d1 * h2) - (d2 * h1)) / ((h1 * h2) * (h1 - h2))); x = ((-2 * a0) / (a1 + abs(math.sqrt(a1 * a1 - 4 * a0 * a2)))); y = ((-2 * a0) / (a1 - abs(math.sqrt(a1 * a1 - 4 * a0 * a2)))); # Taking the root which is # closer to x2 if (x >= y): res = x + c; else: res = y + c; # checking for resemblance of x3 # with x2 till two decimal places m = res * 100; n = c * 100; m = math.floor(m); n = math.floor(n); if (m == n): break; a = b; b = c; c = res; if (i > MAX_ITERATIONS): print("Root cannot be found using", "Muller's method"); break; i += 1; if (i <= MAX_ITERATIONS): print("The value of the root is", round(res, 4)); # Driver Codea = 0;b = 1;c = 2;Muller(a, b, c); # This code is contributed by mits
// C# Program to find root of a function, f(x)using System; class Muller1{ static int MAX_ITERATIONS = 10000; // function to calculate f(x) static double f(double x) { // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*Math.Pow(x, 3) + 2*x*x + 10*x - 20; } static void Muller(double a, double b, double c) { int i; double res; for (i = 0;; ++i) { // Calculating various constants required // to calculate x3 double f1 = f(a); double f2 = f(b); double f3 = f(c); double d1 = f1 - f3; double d2 = f2 - f3; double h1 = a - c; double h2 = b - c; double a0 = f3; double a1 = (((d2*Math.Pow(h1, 2)) - (d1*Math.Pow(h2, 2))) / ((h1*h2) * (h1-h2))); double a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); double x = ((-2*a0)/(a1 + Math.Abs(Math.Sqrt(a1*a1-4*a0*a2)))); double y = ((-2*a0)/(a1-Math.Abs(Math.Sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) res = x + c; else res = y + c; // checking for resemblance of x3 with x2 till // two decimal places double m = res*100; double n = c*100; m = Math.Floor(m); n = Math.Floor(n); if (m == n) break; a = b; b = c; c = res; if (i > MAX_ITERATIONS) { Console.WriteLine("Root cannot be found using" + " Muller's method"); break; } } if (i <= MAX_ITERATIONS) Console.WriteLine("The value of the root is " + Math.Round(res,4)); } // Driver main function static void Main() { double a = 0, b = 1, c = 2; Muller(a, b, c); }}// this code is contributed by mits
<?php// PHP Program to find root of a function, f(x) $MAX_ITERATIONS = 10000; // Function to calculate f(x)function f($x){ // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*pow($x, 3) + 2*$x*$x + 10*$x - 20;} function Muller($a, $b, $c){ global $MAX_ITERATIONS; $res=0; for ($i = 0;;++$i) { // Calculating various constants required // to calculate x3 $f1 = f($a); $f2 = f($b); $f3 = f($c); $d1 = $f1 - $f3; $d2 = $f2 - $f3; $h1 = $a - $c; $h2 = $b - $c; $a0 = $f3; $a1 = ((($d2*pow($h1, 2)) - ($d1*pow($h2, 2))) / (($h1*$h2) * ($h1-$h2))); $a2 = ((($d1*$h2) - ($d2*$h1))/(($h1*$h2) * ($h1-$h2))); $x = ((-2*$a0) / ($a1 + abs(sqrt($a1*$a1-4*$a0*$a2)))); $y = ((-2*$a0) / ($a1-abs(sqrt($a1*$a1-4*$a0*$a2)))); // Taking the root which is closer to x2 if ($x >= $y) $res = $x + $c; else $res = $y + $c; // checking for resemblance of x3 with x2 till // two decimal places $m = $res*100; $n = $c*100; $m = floor($m); $n = floor($n); if ($m == $n) break; $a = $b; $b = $c; $c = $res; if ($i > $MAX_ITERATIONS) { echo"Root cannot be found using Muller's method"; break; } } if ($i <= $MAX_ITERATIONS) echo "The value of the root is ".round($res,4);} // Driver main function $a = 0; $b = 1; $c = 2; Muller($a, $b, $c); // This code is contributed by mits?>
<script>// JavaScript Program to find root of a function, f(x) const MAX_ITERATIONS = 10000; // Function to calculate f(x)function f(x){ // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*Math.pow(x, 3) + 2*x*x + 10*x - 20;} function Muller(a, b, c){ let i; let res; for (i = 0;;++i) { // Calculating various constants required // to calculate x3 let f1 = f(a); let f2 = f(b); let f3 = f(c); let d1 = f1 - f3; let d2 = f2 - f3; let h1 = a - c; let h2 = b - c; let a0 = f3; let a1 = (((d2*Math.pow(h1, 2)) - (d1*Math.pow(h2, 2))) / ((h1*h2) * (h1-h2))); let a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); let x = ((-2*a0) / (a1 + Math.abs(Math.sqrt(a1*a1-4*a0*a2)))); let y = ((-2*a0) / (a1-Math.abs(Math.sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) res = x + c; else res = y + c; // checking for resemblance of x3 with x2 till // two decimal places let m = res*100; let n = c*100; m = Math.floor(m); n = Math.floor(n); if (m == n) break; a = b; b = c; c = res; if (i > MAX_ITERATIONS) { document.write("Root cannot be found using" + " Muller's method"); break; } } if (i <= MAX_ITERATIONS) document.write("The value of the root is " + res.toFixed(4));} // Driver main function let a = 0, b = 1, c = 2; Muller(a, b, c); // This code is contributed by Surbhi Tyagi.</script>
Output:
The value of the root is 1.3688
Advantages
Can find imaginary roots.
No need to find derivatives.
Disadvantages
Long to do by hand, more room for error.
Extraneous roots can be found.
Reference-
Higher Engineer Mathematics by B.S. Grewal.
Higher Engineer Mathematics by B.S. Grewal.
This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
surbhityagi15
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 255,
"s": 54,
"text": "Given a function f(x) on floating number x and three initial distinct guesses for root of the function, find the root of function. Here, f(x) can be an algebraic or transcendental function.Examples: "
},
{
"code": null,
"e": 699,
"s": 255,
"text": "Input : A function f(x) = x + 2x + 10x - 20 \n\n and three initial guesses - 0, 1 and 2 .\n\nOutput : The value of the root is 1.3688 or \n\n any other value within permittable deviation \n\n from the root. \nInput : A function f(x) = x - 5x + 2 \n\n and three initial guesses - 0, 1 and 2 .\n\nOutput :The value of the root is 0.4021 or \n\n any other value within permittable deviation \n\n from the root. "
},
{
"code": null,
"e": 715,
"s": 701,
"text": "Muller Method"
},
{
"code": null,
"e": 1145,
"s": 715,
"text": "Muller Method is a root-finding algorithm for finding the root of a equation of the form, f(x)=0. It was discovered by David E. Muller in 1956.It begins with three initial assumptions of the root, and then constructing a parabola through these three points, and takes the intersection of the x-axis with the parabola to be the next approximation. This process continues until a root with the desired level of accuracy is found . "
},
{
"code": null,
"e": 1175,
"s": 1145,
"text": "Why to learn Muller’s Method?"
},
{
"code": null,
"e": 1411,
"s": 1175,
"text": "Muller Method, being one of the root-finding method along with the other ones like Bisection Method, Regula – Falsi Method, Secant Method and Newton – Raphson Method. But, it offers certain advantages over these methods, as follows – "
},
{
"code": null,
"e": 1934,
"s": 1411,
"text": "The rate of convergence, i.e., how much closer we move to the root at each step, is approximately 1.84 in Muller Method, whereas it is 1.62 for secant method, and linear, i.e., 1 for both Regula – falsi Method and bisection method . So, Muller Method is faster than Bisection, Regula – Falsi and Secant method.Although, it is slower than Newton – Raphson’s Method, which has a rate of convergence of 2, but it overcomes one of the biggest drawbacks of Newton-Raphson Method, i.e., computation of derivative at each step. "
},
{
"code": null,
"e": 2245,
"s": 1934,
"text": "The rate of convergence, i.e., how much closer we move to the root at each step, is approximately 1.84 in Muller Method, whereas it is 1.62 for secant method, and linear, i.e., 1 for both Regula – falsi Method and bisection method . So, Muller Method is faster than Bisection, Regula – Falsi and Secant method."
},
{
"code": null,
"e": 2458,
"s": 2245,
"text": "Although, it is slower than Newton – Raphson’s Method, which has a rate of convergence of 2, but it overcomes one of the biggest drawbacks of Newton-Raphson Method, i.e., computation of derivative at each step. "
},
{
"code": null,
"e": 2553,
"s": 2458,
"text": "So, this shows that Muller Method is an efficient method in calculating root of the function. "
},
{
"code": null,
"e": 2579,
"s": 2553,
"text": "Algorithm And Its Working"
},
{
"code": null,
"e": 2927,
"s": 2581,
"text": "Assume any three distinct initial roots of the function, let it be x0, x1 and x2. Now, draw a second degree polynomial, i.e., a parabola, through the values of function f(x) for these points – x0, x1 and x2. The equation of the parabola, p(x), through these points is as follows- p(x) = c + b(x – x) + a(x – x), where a, b and c are constants. "
},
{
"code": null,
"e": 3011,
"s": 2927,
"text": "Assume any three distinct initial roots of the function, let it be x0, x1 and x2. "
},
{
"code": null,
"e": 3274,
"s": 3011,
"text": "Now, draw a second degree polynomial, i.e., a parabola, through the values of function f(x) for these points – x0, x1 and x2. The equation of the parabola, p(x), through these points is as follows- p(x) = c + b(x – x) + a(x – x), where a, b and c are constants. "
},
{
"code": null,
"e": 4352,
"s": 3274,
"text": " After drawing the parabola, then find the intersection of this parabola with the x-axis, let us say x3 . Finding the intersection of parabola with the x-axis, i.e., x3: To find x, the root of p(x), where p(x) = c + b(x – x) + a(x – x), such that p(x) = c + b(x– x) + a(x– x)= 0, apply the quadratic formula to p(x).Since, there will be two roots, but we have to take that one which is closer to x.To avoid round-off errors due to subtraction of nearby equal numbers, use the following equation:Now, since, root of p(x) has to be closer to x, so we have to take that value which has a greater denominator out of the two values possible from the above equation.To find a, b and c for the above equation, put x in p(x) as x, xand x, and let these values be p(x), p(x) and p(x), which are as follows-p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= c = f(x). So, we have three equations and three variables – a, b, c. After solving them to found out the values of these variables, we get the following values of a, b and c- "
},
{
"code": null,
"e": 4461,
"s": 4354,
"text": "After drawing the parabola, then find the intersection of this parabola with the x-axis, let us say x3 . "
},
{
"code": null,
"e": 5432,
"s": 4461,
"text": "Finding the intersection of parabola with the x-axis, i.e., x3: To find x, the root of p(x), where p(x) = c + b(x – x) + a(x – x), such that p(x) = c + b(x– x) + a(x– x)= 0, apply the quadratic formula to p(x).Since, there will be two roots, but we have to take that one which is closer to x.To avoid round-off errors due to subtraction of nearby equal numbers, use the following equation:Now, since, root of p(x) has to be closer to x, so we have to take that value which has a greater denominator out of the two values possible from the above equation.To find a, b and c for the above equation, put x in p(x) as x, xand x, and let these values be p(x), p(x) and p(x), which are as follows-p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= c = f(x). So, we have three equations and three variables – a, b, c. After solving them to found out the values of these variables, we get the following values of a, b and c- "
},
{
"code": null,
"e": 5923,
"s": 5432,
"text": "To find x, the root of p(x), where p(x) = c + b(x – x) + a(x – x), such that p(x) = c + b(x– x) + a(x– x)= 0, apply the quadratic formula to p(x).Since, there will be two roots, but we have to take that one which is closer to x.To avoid round-off errors due to subtraction of nearby equal numbers, use the following equation:Now, since, root of p(x) has to be closer to x, so we have to take that value which has a greater denominator out of the two values possible from the above equation."
},
{
"code": null,
"e": 6174,
"s": 5923,
"text": "To find a, b and c for the above equation, put x in p(x) as x, xand x, and let these values be p(x), p(x) and p(x), which are as follows-p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= f(x). p(x) = c + b(x– x) + a(x– x)= c = f(x). "
},
{
"code": null,
"e": 6341,
"s": 6174,
"text": "So, we have three equations and three variables – a, b, c. After solving them to found out the values of these variables, we get the following values of a, b and c- "
},
{
"code": null,
"e": 6441,
"s": 6341,
"text": "c = p(x) = f(x) .\n\nb = (d*(h) - d*(h) ) / ( hh * (h - h)) .\n\na = (d*(h) - d*(h)) / ( hh * (h - h))."
},
{
"code": null,
"e": 6522,
"s": 6441,
"text": "where, d= p(x) – p(x) = f(x) – f(x) d= p(x) – p(x) = f(x) – f(x) h= x– xh= x– x "
},
{
"code": null,
"e": 6629,
"s": 6522,
"text": "Now, put these values in the expression for x– x, and obtain x. This is how root of p(x) = xis obtained. "
},
{
"code": null,
"e": 6821,
"s": 6629,
"text": "If xis very close to xwithin the permittable error, then xbecomes the root of f(x), otherwise, keep repeating the process of finding the next x, with previous x, xand xas the new x, xand x. "
},
{
"code": null,
"e": 7013,
"s": 6821,
"text": "If xis very close to xwithin the permittable error, then xbecomes the root of f(x), otherwise, keep repeating the process of finding the next x, with previous x, xand xas the new x, xand x. "
},
{
"code": null,
"e": 7019,
"s": 7015,
"text": "C++"
},
{
"code": null,
"e": 7024,
"s": 7019,
"text": "Java"
},
{
"code": null,
"e": 7032,
"s": 7024,
"text": "Python3"
},
{
"code": null,
"e": 7035,
"s": 7032,
"text": "C#"
},
{
"code": null,
"e": 7039,
"s": 7035,
"text": "PHP"
},
{
"code": null,
"e": 7050,
"s": 7039,
"text": "Javascript"
},
{
"code": "// C++ Program to find root of a function, f(x)#include<bits/stdc++.h>using namespace std; const int MAX_ITERATIONS = 10000; // Function to calculate f(x)float f(float x){ // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*pow(x, 3) + 2*x*x + 10*x - 20;} void Muller(float a, float b, float c){ int i; float res; for (i = 0;;++i) { // Calculating various constants required // to calculate x3 float f1 = f(a); float f2 = f(b); float f3 = f(c); float d1 = f1 - f3; float d2 = f2 - f3; float h1 = a - c; float h2 = b - c; float a0 = f3; float a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2))) / ((h1*h2) * (h1-h2))); float a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); float x = ((-2*a0) / (a1 + abs(sqrt(a1*a1-4*a0*a2)))); float y = ((-2*a0) / (a1-abs(sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) res = x + c; else res = y + c; // checking for resemblance of x3 with x2 till // two decimal places float m = res*100; float n = c*100; m = floor(m); n = floor(n); if (m == n) break; a = b; b = c; c = res; if (i > MAX_ITERATIONS) { cout << \"Root cannot be found using\" << \" Muller's method\"; break; } } if (i <= MAX_ITERATIONS) cout << \"The value of the root is \" << res;} // Driver main functionint main(){ float a = 0, b = 1, c = 2; Muller(a, b, c); return 0;}",
"e": 8680,
"s": 7050,
"text": null
},
{
"code": "// Java Program to find root of a function, f(x)import java.io.*;import static java.lang.Math.*; class Muller{ static final int MAX_ITERATIONS = 10000; // function to calculate f(x) static double f(double x) { // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*pow(x, 3) + 2*x*x + 10*x - 20; } static void Muller(double a, double b, double c) { int i; double res; for (i = 0;; ++i) { // Calculating various constants required // to calculate x3 double f1 = f(a); double f2 = f(b); double f3 = f(c); double d1 = f1 - f3; double d2 = f2 - f3; double h1 = a - c; double h2 = b - c; double a0 = f3; double a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2))) / ((h1*h2) * (h1-h2))); double a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); double x = ((-2*a0)/(a1 + abs(sqrt(a1*a1-4*a0*a2)))); double y = ((-2*a0)/(a1-abs(sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) res = x + c; else res = y + c; // checking for resemblance of x3 with x2 till // two decimal places double m = res*100; double n = c*100; m = floor(m); n = floor(n); if (m == n) break; a = b; b = c; c = res; if (i > MAX_ITERATIONS) { System.out.println(\"Root cannot be found using\" + \" Muller's method\"); break; } } if (i <= MAX_ITERATIONS) System.out.println(\"The value of the root is \" + res); } // Driver main function public static void main(String args[]) { double a = 0, b = 1, c = 2; Muller(a, b, c); }}",
"e": 10659,
"s": 8680,
"text": null
},
{
"code": "# Python3 Program to find root of# a function, f(x)import math; MAX_ITERATIONS = 10000; # Function to calculate f(x)def f(x): # Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return (1 * pow(x, 3) + 2 * x * x + 10 * x - 20); def Muller(a, b, c): res = 0; i = 0; while (True): # Calculating various constants # required to calculate x3 f1 = f(a); f2 = f(b); f3 = f(c); d1 = f1 - f3; d2 = f2 - f3; h1 = a - c; h2 = b - c; a0 = f3; a1 = (((d2 * pow(h1, 2)) - (d1 * pow(h2, 2))) / ((h1 * h2) * (h1 - h2))); a2 = (((d1 * h2) - (d2 * h1)) / ((h1 * h2) * (h1 - h2))); x = ((-2 * a0) / (a1 + abs(math.sqrt(a1 * a1 - 4 * a0 * a2)))); y = ((-2 * a0) / (a1 - abs(math.sqrt(a1 * a1 - 4 * a0 * a2)))); # Taking the root which is # closer to x2 if (x >= y): res = x + c; else: res = y + c; # checking for resemblance of x3 # with x2 till two decimal places m = res * 100; n = c * 100; m = math.floor(m); n = math.floor(n); if (m == n): break; a = b; b = c; c = res; if (i > MAX_ITERATIONS): print(\"Root cannot be found using\", \"Muller's method\"); break; i += 1; if (i <= MAX_ITERATIONS): print(\"The value of the root is\", round(res, 4)); # Driver Codea = 0;b = 1;c = 2;Muller(a, b, c); # This code is contributed by mits",
"e": 12290,
"s": 10659,
"text": null
},
{
"code": "// C# Program to find root of a function, f(x)using System; class Muller1{ static int MAX_ITERATIONS = 10000; // function to calculate f(x) static double f(double x) { // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*Math.Pow(x, 3) + 2*x*x + 10*x - 20; } static void Muller(double a, double b, double c) { int i; double res; for (i = 0;; ++i) { // Calculating various constants required // to calculate x3 double f1 = f(a); double f2 = f(b); double f3 = f(c); double d1 = f1 - f3; double d2 = f2 - f3; double h1 = a - c; double h2 = b - c; double a0 = f3; double a1 = (((d2*Math.Pow(h1, 2)) - (d1*Math.Pow(h2, 2))) / ((h1*h2) * (h1-h2))); double a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); double x = ((-2*a0)/(a1 + Math.Abs(Math.Sqrt(a1*a1-4*a0*a2)))); double y = ((-2*a0)/(a1-Math.Abs(Math.Sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) res = x + c; else res = y + c; // checking for resemblance of x3 with x2 till // two decimal places double m = res*100; double n = c*100; m = Math.Floor(m); n = Math.Floor(n); if (m == n) break; a = b; b = c; c = res; if (i > MAX_ITERATIONS) { Console.WriteLine(\"Root cannot be found using\" + \" Muller's method\"); break; } } if (i <= MAX_ITERATIONS) Console.WriteLine(\"The value of the root is \" + Math.Round(res,4)); } // Driver main function static void Main() { double a = 0, b = 1, c = 2; Muller(a, b, c); }}// this code is contributed by mits",
"e": 14296,
"s": 12290,
"text": null
},
{
"code": "<?php// PHP Program to find root of a function, f(x) $MAX_ITERATIONS = 10000; // Function to calculate f(x)function f($x){ // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*pow($x, 3) + 2*$x*$x + 10*$x - 20;} function Muller($a, $b, $c){ global $MAX_ITERATIONS; $res=0; for ($i = 0;;++$i) { // Calculating various constants required // to calculate x3 $f1 = f($a); $f2 = f($b); $f3 = f($c); $d1 = $f1 - $f3; $d2 = $f2 - $f3; $h1 = $a - $c; $h2 = $b - $c; $a0 = $f3; $a1 = ((($d2*pow($h1, 2)) - ($d1*pow($h2, 2))) / (($h1*$h2) * ($h1-$h2))); $a2 = ((($d1*$h2) - ($d2*$h1))/(($h1*$h2) * ($h1-$h2))); $x = ((-2*$a0) / ($a1 + abs(sqrt($a1*$a1-4*$a0*$a2)))); $y = ((-2*$a0) / ($a1-abs(sqrt($a1*$a1-4*$a0*$a2)))); // Taking the root which is closer to x2 if ($x >= $y) $res = $x + $c; else $res = $y + $c; // checking for resemblance of x3 with x2 till // two decimal places $m = $res*100; $n = $c*100; $m = floor($m); $n = floor($n); if ($m == $n) break; $a = $b; $b = $c; $c = $res; if ($i > $MAX_ITERATIONS) { echo\"Root cannot be found using Muller's method\"; break; } } if ($i <= $MAX_ITERATIONS) echo \"The value of the root is \".round($res,4);} // Driver main function $a = 0; $b = 1; $c = 2; Muller($a, $b, $c); // This code is contributed by mits?>",
"e": 15883,
"s": 14296,
"text": null
},
{
"code": "<script>// JavaScript Program to find root of a function, f(x) const MAX_ITERATIONS = 10000; // Function to calculate f(x)function f(x){ // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*Math.pow(x, 3) + 2*x*x + 10*x - 20;} function Muller(a, b, c){ let i; let res; for (i = 0;;++i) { // Calculating various constants required // to calculate x3 let f1 = f(a); let f2 = f(b); let f3 = f(c); let d1 = f1 - f3; let d2 = f2 - f3; let h1 = a - c; let h2 = b - c; let a0 = f3; let a1 = (((d2*Math.pow(h1, 2)) - (d1*Math.pow(h2, 2))) / ((h1*h2) * (h1-h2))); let a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); let x = ((-2*a0) / (a1 + Math.abs(Math.sqrt(a1*a1-4*a0*a2)))); let y = ((-2*a0) / (a1-Math.abs(Math.sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) res = x + c; else res = y + c; // checking for resemblance of x3 with x2 till // two decimal places let m = res*100; let n = c*100; m = Math.floor(m); n = Math.floor(n); if (m == n) break; a = b; b = c; c = res; if (i > MAX_ITERATIONS) { document.write(\"Root cannot be found using\" + \" Muller's method\"); break; } } if (i <= MAX_ITERATIONS) document.write(\"The value of the root is \" + res.toFixed(4));} // Driver main function let a = 0, b = 1, c = 2; Muller(a, b, c); // This code is contributed by Surbhi Tyagi.</script>",
"e": 17531,
"s": 15883,
"text": null
},
{
"code": null,
"e": 17541,
"s": 17531,
"text": "Output: "
},
{
"code": null,
"e": 17573,
"s": 17541,
"text": "The value of the root is 1.3688"
},
{
"code": null,
"e": 17586,
"s": 17573,
"text": "Advantages "
},
{
"code": null,
"e": 17612,
"s": 17586,
"text": "Can find imaginary roots."
},
{
"code": null,
"e": 17641,
"s": 17612,
"text": "No need to find derivatives."
},
{
"code": null,
"e": 17657,
"s": 17641,
"text": "Disadvantages "
},
{
"code": null,
"e": 17698,
"s": 17657,
"text": "Long to do by hand, more room for error."
},
{
"code": null,
"e": 17729,
"s": 17698,
"text": "Extraneous roots can be found."
},
{
"code": null,
"e": 17742,
"s": 17729,
"text": "Reference- "
},
{
"code": null,
"e": 17788,
"s": 17742,
"text": "Higher Engineer Mathematics by B.S. Grewal. "
},
{
"code": null,
"e": 17834,
"s": 17788,
"text": "Higher Engineer Mathematics by B.S. Grewal. "
},
{
"code": null,
"e": 18262,
"s": 17834,
"text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 18275,
"s": 18262,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 18289,
"s": 18275,
"text": "surbhityagi15"
},
{
"code": null,
"e": 18302,
"s": 18289,
"text": "Mathematical"
},
{
"code": null,
"e": 18315,
"s": 18302,
"text": "Mathematical"
}
] |
Vector indexOf() Method in Java | 31 Oct, 2021
The java.util.vector.indexOf(Object element) method is used to check and find the occurrence of a particular element in the vector. If the element is present then the index of the first occurrence of the element is returned otherwise -1 is returned if the vector does not contain the element.
Syntax:
Vector.indexOf(Object element)
Parameters: Element of the type of Vector which is mandatory as it specifies the element whose occurrence is needed to be checked in the Vector.
Return Value: Index or position of the first occurrence of the element in the vector. Else it returns -1 if the element is not present in the vector. The returned value is of integer type.
Example 1:
Java
// Java Program to illustrate indexOf() Method// of Vector class // Importing required classesimport java.util.*; // Main class// VectorDemopublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty Vector by creating object of // Vector class of string type Vector<String> vec_tor = new Vector<String>(); // Adding elements in the Vector // using add() method vec_tor.add("Geeks"); vec_tor.add("for"); vec_tor.add("Geeks"); vec_tor.add("10"); vec_tor.add("20"); // Print and display all elements in above vector // object System.out.println("Vector: " + vec_tor); // Print commands where we are returning the 1st // position of element in vector object using // indexOf() method System.out.println( "The first occurrence of Geeks is at index:" + vec_tor.indexOf("Geeks")); System.out.println( "The first occurrence of 10 is at index: " + vec_tor.indexOf("10")); }}
Vector: [Geeks, for, Geeks, 10, 20]
The first occurrence of Geeks is at index:0
The first occurrence of 10 is at index: 3
Output Explanation: Here we have inserted elements inside the vector in which few elements were duplicated. In the above example “Geeks” is the only element inside Vector class being getting repeated so do we returned the first occurrence which is present at index so do we returned ‘0’ while if the element is not getting duplicated then simply its index will be returned.
Example 2:
Java
// Java Program to illustrate indexOf() Method// of Vector class // Importing required classesimport java.util.*; // Main class// VectorDemopublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(); // Adding elements in the Vector // using add() method vec_tor.add(1); vec_tor.add(2); vec_tor.add(3); vec_tor.add(1); vec_tor.add(5); // Print and display all elements of vector object System.out.println("Vector: " + vec_tor); // Returning the 1st position of an element // using indexOf() method // Print and display commands System.out.println("The first occurrence of 1 is at index : "+ vec_tor.indexOf(1)); System.out.println("The first occurrence of 3 is at index : "+ vec_tor.indexOf(7)); }}
Vector: [1, 2, 3, 1, 5]
The first occurrence of 1 is at index : 0
The first occurrence of 3 is at index : -1
Output Explanation: As we did above here we take integers in the case of strings where the here only thing that we plot differently is bypassing an element that does not exists then ‘-1’ will be returned because there do not exist any negative indexes in java so do we assign -1 in general.
solankimayank
surinderdawra388
sweetyty
Java - util package
Java-Collections
Java-Functions
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 321,
"s": 28,
"text": "The java.util.vector.indexOf(Object element) method is used to check and find the occurrence of a particular element in the vector. If the element is present then the index of the first occurrence of the element is returned otherwise -1 is returned if the vector does not contain the element."
},
{
"code": null,
"e": 330,
"s": 321,
"text": "Syntax: "
},
{
"code": null,
"e": 361,
"s": 330,
"text": "Vector.indexOf(Object element)"
},
{
"code": null,
"e": 506,
"s": 361,
"text": "Parameters: Element of the type of Vector which is mandatory as it specifies the element whose occurrence is needed to be checked in the Vector."
},
{
"code": null,
"e": 695,
"s": 506,
"text": "Return Value: Index or position of the first occurrence of the element in the vector. Else it returns -1 if the element is not present in the vector. The returned value is of integer type."
},
{
"code": null,
"e": 706,
"s": 695,
"text": "Example 1:"
},
{
"code": null,
"e": 711,
"s": 706,
"text": "Java"
},
{
"code": "// Java Program to illustrate indexOf() Method// of Vector class // Importing required classesimport java.util.*; // Main class// VectorDemopublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty Vector by creating object of // Vector class of string type Vector<String> vec_tor = new Vector<String>(); // Adding elements in the Vector // using add() method vec_tor.add(\"Geeks\"); vec_tor.add(\"for\"); vec_tor.add(\"Geeks\"); vec_tor.add(\"10\"); vec_tor.add(\"20\"); // Print and display all elements in above vector // object System.out.println(\"Vector: \" + vec_tor); // Print commands where we are returning the 1st // position of element in vector object using // indexOf() method System.out.println( \"The first occurrence of Geeks is at index:\" + vec_tor.indexOf(\"Geeks\")); System.out.println( \"The first occurrence of 10 is at index: \" + vec_tor.indexOf(\"10\")); }}",
"e": 1808,
"s": 711,
"text": null
},
{
"code": null,
"e": 1930,
"s": 1808,
"text": "Vector: [Geeks, for, Geeks, 10, 20]\nThe first occurrence of Geeks is at index:0\nThe first occurrence of 10 is at index: 3"
},
{
"code": null,
"e": 2306,
"s": 1932,
"text": "Output Explanation: Here we have inserted elements inside the vector in which few elements were duplicated. In the above example “Geeks” is the only element inside Vector class being getting repeated so do we returned the first occurrence which is present at index so do we returned ‘0’ while if the element is not getting duplicated then simply its index will be returned."
},
{
"code": null,
"e": 2317,
"s": 2306,
"text": "Example 2:"
},
{
"code": null,
"e": 2322,
"s": 2317,
"text": "Java"
},
{
"code": "// Java Program to illustrate indexOf() Method// of Vector class // Importing required classesimport java.util.*; // Main class// VectorDemopublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(); // Adding elements in the Vector // using add() method vec_tor.add(1); vec_tor.add(2); vec_tor.add(3); vec_tor.add(1); vec_tor.add(5); // Print and display all elements of vector object System.out.println(\"Vector: \" + vec_tor); // Returning the 1st position of an element // using indexOf() method // Print and display commands System.out.println(\"The first occurrence of 1 is at index : \"+ vec_tor.indexOf(1)); System.out.println(\"The first occurrence of 3 is at index : \"+ vec_tor.indexOf(7)); }}",
"e": 3249,
"s": 2322,
"text": null
},
{
"code": null,
"e": 3358,
"s": 3249,
"text": "Vector: [1, 2, 3, 1, 5]\nThe first occurrence of 1 is at index : 0\nThe first occurrence of 3 is at index : -1"
},
{
"code": null,
"e": 3651,
"s": 3358,
"text": "Output Explanation: As we did above here we take integers in the case of strings where the here only thing that we plot differently is bypassing an element that does not exists then ‘-1’ will be returned because there do not exist any negative indexes in java so do we assign -1 in general. "
},
{
"code": null,
"e": 3665,
"s": 3651,
"text": "solankimayank"
},
{
"code": null,
"e": 3682,
"s": 3665,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3691,
"s": 3682,
"text": "sweetyty"
},
{
"code": null,
"e": 3711,
"s": 3691,
"text": "Java - util package"
},
{
"code": null,
"e": 3728,
"s": 3711,
"text": "Java-Collections"
},
{
"code": null,
"e": 3743,
"s": 3728,
"text": "Java-Functions"
},
{
"code": null,
"e": 3755,
"s": 3743,
"text": "Java-Vector"
},
{
"code": null,
"e": 3760,
"s": 3755,
"text": "Java"
},
{
"code": null,
"e": 3765,
"s": 3760,
"text": "Java"
},
{
"code": null,
"e": 3782,
"s": 3765,
"text": "Java-Collections"
},
{
"code": null,
"e": 3880,
"s": 3782,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3895,
"s": 3880,
"text": "Arrays in Java"
},
{
"code": null,
"e": 3939,
"s": 3895,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 3975,
"s": 3939,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 4026,
"s": 3975,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4051,
"s": 4026,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4073,
"s": 4051,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 4104,
"s": 4073,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4123,
"s": 4104,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4153,
"s": 4123,
"text": "HashMap in Java with Examples"
}
] |
Kotlin when expression | 03 Jan, 2022
In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to end of the when block and executes the code next to the when block. Unlike switch cases in java or any other programming language, we do not require a break statement at the end of each case. In Kotlin, when can be used in two ways:
when as a statement
when as an expression
when can be used as a statement with or without else branch. If it is used as a statement, the values of all individual branches are compared sequentially with the argument and execute the corresponding branch where the condition matches. If none of the branches is satisfied with the condition then it will execute the else branch.
Kotlin
import java.util.Scanner;fun main(args: Array<String>) { var reader = Scanner(System.`in`) print("Enter any largebody:") var lb = reader.next() when(lb) { "Sun" -> println("Sun is a Star") "Moon" -> println("Moon is a Satellite") "Earth" -> println("Earth is a planet") else -> println("I don't know anything about it") }}
Output:
Enter any largebody: Sun
Sun is a Star
Enter any largebody: Mars
I don't know anything about it
We can use when as a statement without else branch. If it is used as a statement, the values of all individual branches are compared sequentially with the argument and execute the corresponding branch where condition matches. If none of the branches are satisfied with the condition then it simply exits the block without printing anything to system output.
Kotlin
import java.util.Scanner;fun main(args: Array<String>) { var reader = Scanner(System.`in`) print("Enter name:") var lb = reader.next() when(lb) { "Sun" -> println("Sun is a Star") "Moon" -> println("Moon is a Satellite") "Earth" -> println("Earth is a planet") }}
Output:
Enter name: Mars
Process finished with exit code 0
If it is used as an expression, the value of the branch with which condition satisfied will be the value of overall expression. As an expression when returns a value with which the argument matches and we can store it in a variable or print directly.
Kotlin
import java.util.Scanner;fun main(args: Array<String>) { var reader = Scanner(System.`in`) print("Enter the month number:") var monthOfYear = reader.nextInt() var month = when(monthOfYear){ 1->"January" 2->"February" 3->"March" 4->"April" 5->"May" 6->"June" 7->"July" 8->"August" 9->"September" 10->"October" 11->"November" 12->"December" else -> { println("Not a month of year") } } println(month)}
Output:
Enter the month number:8
August
If none of the branch conditions are satisfied with the argument, the else branch is executed. As an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions. If we cannot use else branch it will give a compiler error.
Error:(6, 17) Kotlin: 'when' expression must be exhaustive, add necessary 'else' branch
Combine multiple branches in one using comma:
We can use multiple branches in a single one separated by a comma. When common logic is shared by some branches then we can combine them in a single branch. In the example below, we need to check the entered large body is a planet or not, so we combined all the names of planets in a single branch. Anything entered other than planet name will execute the else branch.
Kotlin
import java.util.Scanner;fun main(args: Array<String>) { var reader = Scanner(System.`in`) print("Enter name of planet: ") var name = reader.next() when(name) { "Mercury","Earth","Mars","Jupiter" ,"Neptune","Saturn","Venus","Uranus" -> println("Planet") else -> println("Neither planet nor star") }}
Output:
Enter name of planet: Earth
Planet
Check the input value in the range or not:
Using the in or !in operator, we can check the range of argument passed in when block. ‘in’ operator in Kotlin is used to check the existence of a particular variable or property in a range. If the argument lies in a particular range then in operator returns true and if the argument does not lie in a particular range then !in returns true.
Kotlin
import java.util.Scanner; fun main(args: Array<String>) { var reader = Scanner(System.`in`) print("Enter the month number of year: ") var num = reader.nextInt() when(num){ in 1..3 -> println("It is spring season") in 4..6 -> println("It is summer season") in 7..8 ->println("It is rainy season") in 9..10 -> println("It is autumn season") in 11..12 -> println("It is winter season") !in 1..12 ->println("Enter valid month of year") }}
Output:
Enter the month number of year: 5
It is summer season
Enter the month number of year: 14
Enter valid month of year
Check given variable is of a certain type or not:
Using is or !is operator we can check the type of variable passed as an argument in when block. If the variable is Integer type then is Int returns true else return false.
Kotlin
fun main(args: Array<String>) { var num: Any = "GeeksforGeeks" when(num){ is Int -> println("It is an Integer") is String -> println("It is a String") is Double -> println("It is a Double") }}
Output:
It is a String
Using when as a replacement for an if-else-if chain:
We can use when as a replacement for if-else-if. If no argument is supplied then the branch conditions are simply boolean expressions, and a branch is executed only when its condition is true:
Kotlin
fun isOdd(x: Int) = x % 2 != 0fun isEven(x: Int) = x % 2 == 0 fun main(args: Array<String>) { var num = 8 when{ isOdd(num) ->println("Odd") isEven(num) -> println("Even") else -> println("Neither even nor odd") }}
Output:
Even
Check that a string contains a particular prefix or suffix:
We can also check prefix or suffix in a given string by the below method. If the string contains the prefix or suffix then it will return the Boolean value true else return false.
Kotlin
fun hasPrefix(company: Any) = when (company) { is String -> company.startsWith("GeeksforGeeks") else -> false} fun main(args: Array<String>) { var company = "GeeksforGeeks a computer science portal" var result = hasPrefix(company) if(result) { println("Yes, string started with GeeksforGeeks") } else { println("No, String does not started with GeeksforGeeks") }}
Output:
Yes, string started with GeeksforGeeks
clintra
rajeev0719singh
mssoni916
Kotlin Control-flow
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Higher-Order Functions
Suspend Function In Kotlin Coroutines
How to Communicate Between Fragments in Android?
Android Menus
Spinner in Kotlin
MVP (Model View Presenter) Architecture Pattern in Android with Example
Kotlin extension function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 564,
"s": 28,
"text": "In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to end of the when block and executes the code next to the when block. Unlike switch cases in java or any other programming language, we do not require a break statement at the end of each case. In Kotlin, when can be used in two ways: "
},
{
"code": null,
"e": 584,
"s": 564,
"text": "when as a statement"
},
{
"code": null,
"e": 607,
"s": 584,
"text": "when as an expression "
},
{
"code": null,
"e": 942,
"s": 607,
"text": "when can be used as a statement with or without else branch. If it is used as a statement, the values of all individual branches are compared sequentially with the argument and execute the corresponding branch where the condition matches. If none of the branches is satisfied with the condition then it will execute the else branch. "
},
{
"code": null,
"e": 949,
"s": 942,
"text": "Kotlin"
},
{
"code": "import java.util.Scanner;fun main(args: Array<String>) { var reader = Scanner(System.`in`) print(\"Enter any largebody:\") var lb = reader.next() when(lb) { \"Sun\" -> println(\"Sun is a Star\") \"Moon\" -> println(\"Moon is a Satellite\") \"Earth\" -> println(\"Earth is a planet\") else -> println(\"I don't know anything about it\") }}",
"e": 1317,
"s": 949,
"text": null
},
{
"code": null,
"e": 1326,
"s": 1317,
"text": "Output: "
},
{
"code": null,
"e": 1423,
"s": 1326,
"text": "Enter any largebody: Sun\nSun is a Star\n\nEnter any largebody: Mars\nI don't know anything about it"
},
{
"code": null,
"e": 1782,
"s": 1423,
"text": "We can use when as a statement without else branch. If it is used as a statement, the values of all individual branches are compared sequentially with the argument and execute the corresponding branch where condition matches. If none of the branches are satisfied with the condition then it simply exits the block without printing anything to system output. "
},
{
"code": null,
"e": 1789,
"s": 1782,
"text": "Kotlin"
},
{
"code": "import java.util.Scanner;fun main(args: Array<String>) { var reader = Scanner(System.`in`) print(\"Enter name:\") var lb = reader.next() when(lb) { \"Sun\" -> println(\"Sun is a Star\") \"Moon\" -> println(\"Moon is a Satellite\") \"Earth\" -> println(\"Earth is a planet\") }}",
"e": 2090,
"s": 1789,
"text": null
},
{
"code": null,
"e": 2099,
"s": 2090,
"text": "Output: "
},
{
"code": null,
"e": 2150,
"s": 2099,
"text": "Enter name: Mars\nProcess finished with exit code 0"
},
{
"code": null,
"e": 2402,
"s": 2150,
"text": "If it is used as an expression, the value of the branch with which condition satisfied will be the value of overall expression. As an expression when returns a value with which the argument matches and we can store it in a variable or print directly. "
},
{
"code": null,
"e": 2409,
"s": 2402,
"text": "Kotlin"
},
{
"code": "import java.util.Scanner;fun main(args: Array<String>) { var reader = Scanner(System.`in`) print(\"Enter the month number:\") var monthOfYear = reader.nextInt() var month = when(monthOfYear){ 1->\"January\" 2->\"February\" 3->\"March\" 4->\"April\" 5->\"May\" 6->\"June\" 7->\"July\" 8->\"August\" 9->\"September\" 10->\"October\" 11->\"November\" 12->\"December\" else -> { println(\"Not a month of year\") } } println(month)}",
"e": 2936,
"s": 2409,
"text": null
},
{
"code": null,
"e": 2945,
"s": 2936,
"text": "Output: "
},
{
"code": null,
"e": 2977,
"s": 2945,
"text": "Enter the month number:8\nAugust"
},
{
"code": null,
"e": 3271,
"s": 2977,
"text": "If none of the branch conditions are satisfied with the argument, the else branch is executed. As an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions. If we cannot use else branch it will give a compiler error. "
},
{
"code": null,
"e": 3359,
"s": 3271,
"text": "Error:(6, 17) Kotlin: 'when' expression must be exhaustive, add necessary 'else' branch"
},
{
"code": null,
"e": 3405,
"s": 3359,
"text": "Combine multiple branches in one using comma:"
},
{
"code": null,
"e": 3776,
"s": 3405,
"text": "We can use multiple branches in a single one separated by a comma. When common logic is shared by some branches then we can combine them in a single branch. In the example below, we need to check the entered large body is a planet or not, so we combined all the names of planets in a single branch. Anything entered other than planet name will execute the else branch. "
},
{
"code": null,
"e": 3783,
"s": 3776,
"text": "Kotlin"
},
{
"code": "import java.util.Scanner;fun main(args: Array<String>) { var reader = Scanner(System.`in`) print(\"Enter name of planet: \") var name = reader.next() when(name) { \"Mercury\",\"Earth\",\"Mars\",\"Jupiter\" ,\"Neptune\",\"Saturn\",\"Venus\",\"Uranus\" -> println(\"Planet\") else -> println(\"Neither planet nor star\") }}",
"e": 4123,
"s": 3783,
"text": null
},
{
"code": null,
"e": 4132,
"s": 4123,
"text": "Output: "
},
{
"code": null,
"e": 4167,
"s": 4132,
"text": "Enter name of planet: Earth\nPlanet"
},
{
"code": null,
"e": 4210,
"s": 4167,
"text": "Check the input value in the range or not:"
},
{
"code": null,
"e": 4554,
"s": 4210,
"text": "Using the in or !in operator, we can check the range of argument passed in when block. ‘in’ operator in Kotlin is used to check the existence of a particular variable or property in a range. If the argument lies in a particular range then in operator returns true and if the argument does not lie in a particular range then !in returns true. "
},
{
"code": null,
"e": 4561,
"s": 4554,
"text": "Kotlin"
},
{
"code": "import java.util.Scanner; fun main(args: Array<String>) { var reader = Scanner(System.`in`) print(\"Enter the month number of year: \") var num = reader.nextInt() when(num){ in 1..3 -> println(\"It is spring season\") in 4..6 -> println(\"It is summer season\") in 7..8 ->println(\"It is rainy season\") in 9..10 -> println(\"It is autumn season\") in 11..12 -> println(\"It is winter season\") !in 1..12 ->println(\"Enter valid month of year\") }}",
"e": 5053,
"s": 4561,
"text": null
},
{
"code": null,
"e": 5062,
"s": 5053,
"text": "Output: "
},
{
"code": null,
"e": 5178,
"s": 5062,
"text": "Enter the month number of year: 5\nIt is summer season\n\nEnter the month number of year: 14\nEnter valid month of year"
},
{
"code": null,
"e": 5228,
"s": 5178,
"text": "Check given variable is of a certain type or not:"
},
{
"code": null,
"e": 5401,
"s": 5228,
"text": "Using is or !is operator we can check the type of variable passed as an argument in when block. If the variable is Integer type then is Int returns true else return false. "
},
{
"code": null,
"e": 5408,
"s": 5401,
"text": "Kotlin"
},
{
"code": "fun main(args: Array<String>) { var num: Any = \"GeeksforGeeks\" when(num){ is Int -> println(\"It is an Integer\") is String -> println(\"It is a String\") is Double -> println(\"It is a Double\") }}",
"e": 5631,
"s": 5408,
"text": null
},
{
"code": null,
"e": 5640,
"s": 5631,
"text": "Output: "
},
{
"code": null,
"e": 5655,
"s": 5640,
"text": "It is a String"
},
{
"code": null,
"e": 5708,
"s": 5655,
"text": "Using when as a replacement for an if-else-if chain:"
},
{
"code": null,
"e": 5902,
"s": 5708,
"text": "We can use when as a replacement for if-else-if. If no argument is supplied then the branch conditions are simply boolean expressions, and a branch is executed only when its condition is true: "
},
{
"code": null,
"e": 5909,
"s": 5902,
"text": "Kotlin"
},
{
"code": "fun isOdd(x: Int) = x % 2 != 0fun isEven(x: Int) = x % 2 == 0 fun main(args: Array<String>) { var num = 8 when{ isOdd(num) ->println(\"Odd\") isEven(num) -> println(\"Even\") else -> println(\"Neither even nor odd\") }}",
"e": 6153,
"s": 5909,
"text": null
},
{
"code": null,
"e": 6162,
"s": 6153,
"text": "Output: "
},
{
"code": null,
"e": 6167,
"s": 6162,
"text": "Even"
},
{
"code": null,
"e": 6227,
"s": 6167,
"text": "Check that a string contains a particular prefix or suffix:"
},
{
"code": null,
"e": 6408,
"s": 6227,
"text": "We can also check prefix or suffix in a given string by the below method. If the string contains the prefix or suffix then it will return the Boolean value true else return false. "
},
{
"code": null,
"e": 6415,
"s": 6408,
"text": "Kotlin"
},
{
"code": "fun hasPrefix(company: Any) = when (company) { is String -> company.startsWith(\"GeeksforGeeks\") else -> false} fun main(args: Array<String>) { var company = \"GeeksforGeeks a computer science portal\" var result = hasPrefix(company) if(result) { println(\"Yes, string started with GeeksforGeeks\") } else { println(\"No, String does not started with GeeksforGeeks\") }}",
"e": 6817,
"s": 6415,
"text": null
},
{
"code": null,
"e": 6826,
"s": 6817,
"text": "Output: "
},
{
"code": null,
"e": 6865,
"s": 6826,
"text": "Yes, string started with GeeksforGeeks"
},
{
"code": null,
"e": 6873,
"s": 6865,
"text": "clintra"
},
{
"code": null,
"e": 6889,
"s": 6873,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 6899,
"s": 6889,
"text": "mssoni916"
},
{
"code": null,
"e": 6919,
"s": 6899,
"text": "Kotlin Control-flow"
},
{
"code": null,
"e": 6926,
"s": 6919,
"text": "Kotlin"
},
{
"code": null,
"e": 7024,
"s": 6926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7093,
"s": 7024,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 7135,
"s": 7093,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 7154,
"s": 7135,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 7184,
"s": 7154,
"text": "Kotlin Higher-Order Functions"
},
{
"code": null,
"e": 7222,
"s": 7184,
"text": "Suspend Function In Kotlin Coroutines"
},
{
"code": null,
"e": 7271,
"s": 7222,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 7285,
"s": 7271,
"text": "Android Menus"
},
{
"code": null,
"e": 7303,
"s": 7285,
"text": "Spinner in Kotlin"
},
{
"code": null,
"e": 7375,
"s": 7303,
"text": "MVP (Model View Presenter) Architecture Pattern in Android with Example"
}
] |
How to Export SQL Server Data to a Text File Format? | 16 Nov, 2021
In this article, we will see how to export SQL Server data to a Flat file using three different techniques. Before we proceed let’s setup our database.
Step 1: Create a database
Query:
CREATE DATABASE geeks;
Step 2: Select the newly created database
USE geeks;
Step 3: Table Definition
We have the following brands in our geeks database.
Query:
CREATE TABLE brands(
brand_id INT PRIMARY KEY,
brand_name VARCHAR(30) NOT NULL);
Step 4: Inserting records
Query:
INSERT INTO brands VALUES
(1, 'Electra'),
(2, 'Haro'),
(3, 'Heller'),
(4, 'Pure Cycles'),
(5, 'Ritchey'),
(6, 'Strider'),
(7, 'Sun Bicycles'),
(8, 'Surly'),
(9, 'Trek');
Output:
Step 1: First, let’s have a look at our brand’s table.
Query:
SELECT * FROM brands;
Step 2: Write down the query onto the editor whose output needs to be saved. If you want to save the results in a flat file, you can do this in SSMS. Right Click on Editor > Results to > Results to File:
Query:
Select TOP (1000) [brand_id],[brand_name]
from [sample].[production].[brands];
Step 3: Execute the query. An option to specify the name and path will be displayed. Change the type to All Files and Save it with the .txt extension:
Step 4: Result.txt file looks like this:
Step 1: When we right-click a database in SSMS. It is possible to import or export data. Navigate to Tasks>Export Data:
Step 2: The SQL Server Import and Export wizard will be launched. We will export from SQL Server to a Flat file. Select the SQL Server Native Client 11.0 as the Data Source:
If necessary, specify the Server name and connection information:
Step 3: Select Flat File Destination from the destination drop-down menu and hit Browse to set the file name and path:
Step 4: The flat file name in our case would be Result.txt:
Step 5: Once we have determined the file name and path, proceed as follows:
Step 6: Choose “Copy data from one or more table or views” or select second option to specify our own query:
Step 7: To export the data instantly, choose Run immediately:
Step 8: The Result.txt file will contain the output:
The SQL Server Command Line tool is SQLCMD. This tool allows you to store the results in a file. When utilizing batch files to automate processes, this option comes in handy.
Step 1: Here’s how our SaveOutputToText.sql file look’s like:
Query:
SELECT TOP (1000) [brand_id]
,[brand_name]
FROM [sample].[production].[brands];
Step 2: Use the following command on your terminal to save the results of any query onto file:
Query:
sqlcmd -i SaveOutputToText.sql -o Result.txt
Step 3: The Result.txt file contains the output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 180,
"s": 28,
"text": "In this article, we will see how to export SQL Server data to a Flat file using three different techniques. Before we proceed let’s setup our database."
},
{
"code": null,
"e": 206,
"s": 180,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 213,
"s": 206,
"text": "Query:"
},
{
"code": null,
"e": 236,
"s": 213,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 278,
"s": 236,
"text": "Step 2: Select the newly created database"
},
{
"code": null,
"e": 289,
"s": 278,
"text": "USE geeks;"
},
{
"code": null,
"e": 314,
"s": 289,
"text": "Step 3: Table Definition"
},
{
"code": null,
"e": 366,
"s": 314,
"text": "We have the following brands in our geeks database."
},
{
"code": null,
"e": 373,
"s": 366,
"text": "Query:"
},
{
"code": null,
"e": 456,
"s": 373,
"text": "CREATE TABLE brands(\nbrand_id INT PRIMARY KEY, \nbrand_name VARCHAR(30) NOT NULL);"
},
{
"code": null,
"e": 482,
"s": 456,
"text": "Step 4: Inserting records"
},
{
"code": null,
"e": 489,
"s": 482,
"text": "Query:"
},
{
"code": null,
"e": 659,
"s": 489,
"text": "INSERT INTO brands VALUES\n(1, 'Electra'),\n(2, 'Haro'),\n(3, 'Heller'),\n(4, 'Pure Cycles'),\n(5, 'Ritchey'),\n(6, 'Strider'),\n(7, 'Sun Bicycles'),\n(8, 'Surly'),\n(9, 'Trek');"
},
{
"code": null,
"e": 667,
"s": 659,
"text": "Output:"
},
{
"code": null,
"e": 722,
"s": 667,
"text": "Step 1: First, let’s have a look at our brand’s table."
},
{
"code": null,
"e": 729,
"s": 722,
"text": "Query:"
},
{
"code": null,
"e": 751,
"s": 729,
"text": "SELECT * FROM brands;"
},
{
"code": null,
"e": 955,
"s": 751,
"text": "Step 2: Write down the query onto the editor whose output needs to be saved. If you want to save the results in a flat file, you can do this in SSMS. Right Click on Editor > Results to > Results to File:"
},
{
"code": null,
"e": 962,
"s": 955,
"text": "Query:"
},
{
"code": null,
"e": 1041,
"s": 962,
"text": "Select TOP (1000) [brand_id],[brand_name]\nfrom [sample].[production].[brands];"
},
{
"code": null,
"e": 1192,
"s": 1041,
"text": "Step 3: Execute the query. An option to specify the name and path will be displayed. Change the type to All Files and Save it with the .txt extension:"
},
{
"code": null,
"e": 1233,
"s": 1192,
"text": "Step 4: Result.txt file looks like this:"
},
{
"code": null,
"e": 1353,
"s": 1233,
"text": "Step 1: When we right-click a database in SSMS. It is possible to import or export data. Navigate to Tasks>Export Data:"
},
{
"code": null,
"e": 1527,
"s": 1353,
"text": "Step 2: The SQL Server Import and Export wizard will be launched. We will export from SQL Server to a Flat file. Select the SQL Server Native Client 11.0 as the Data Source:"
},
{
"code": null,
"e": 1593,
"s": 1527,
"text": "If necessary, specify the Server name and connection information:"
},
{
"code": null,
"e": 1712,
"s": 1593,
"text": "Step 3: Select Flat File Destination from the destination drop-down menu and hit Browse to set the file name and path:"
},
{
"code": null,
"e": 1772,
"s": 1712,
"text": "Step 4: The flat file name in our case would be Result.txt:"
},
{
"code": null,
"e": 1848,
"s": 1772,
"text": "Step 5: Once we have determined the file name and path, proceed as follows:"
},
{
"code": null,
"e": 1957,
"s": 1848,
"text": "Step 6: Choose “Copy data from one or more table or views” or select second option to specify our own query:"
},
{
"code": null,
"e": 2019,
"s": 1957,
"text": "Step 7: To export the data instantly, choose Run immediately:"
},
{
"code": null,
"e": 2072,
"s": 2019,
"text": "Step 8: The Result.txt file will contain the output:"
},
{
"code": null,
"e": 2247,
"s": 2072,
"text": "The SQL Server Command Line tool is SQLCMD. This tool allows you to store the results in a file. When utilizing batch files to automate processes, this option comes in handy."
},
{
"code": null,
"e": 2309,
"s": 2247,
"text": "Step 1: Here’s how our SaveOutputToText.sql file look’s like:"
},
{
"code": null,
"e": 2316,
"s": 2309,
"text": "Query:"
},
{
"code": null,
"e": 2404,
"s": 2316,
"text": "SELECT TOP (1000) [brand_id]\n ,[brand_name]\n FROM [sample].[production].[brands];"
},
{
"code": null,
"e": 2499,
"s": 2404,
"text": "Step 2: Use the following command on your terminal to save the results of any query onto file:"
},
{
"code": null,
"e": 2506,
"s": 2499,
"text": "Query:"
},
{
"code": null,
"e": 2551,
"s": 2506,
"text": "sqlcmd -i SaveOutputToText.sql -o Result.txt"
},
{
"code": null,
"e": 2600,
"s": 2551,
"text": "Step 3: The Result.txt file contains the output:"
},
{
"code": null,
"e": 2607,
"s": 2600,
"text": "Picked"
},
{
"code": null,
"e": 2618,
"s": 2607,
"text": "SQL-Server"
},
{
"code": null,
"e": 2622,
"s": 2618,
"text": "SQL"
},
{
"code": null,
"e": 2626,
"s": 2622,
"text": "SQL"
}
] |
Primary and secondary prompt in Python | 10 May, 2020
The ">>>" sign seen on the Python’s interactive shell is called a prompt. Python’s interactive shell, which appears after firing command “python3” (if we are working on python version 3) on the terminal, has two such prompts.
">>>" - Primary prompt
"..." - Secondary prompt
When we fire command ‘python3’ on terminal, >>> sign is immediately seen on screen. This “>>>” sign is nothing but the primary prompt.
Whenever cursor is blinking next to a primary prompt on terminal, it means interpreter will take ‘one and only one’ instruction and execute it immediately if the instruction is found valid
Example:
Firstly interpreter will immediately execute a = 10 while doing so it will create an integer object, store 10 inside that integer object and bind that particular object to a variable called ‘a’
After executing the first instruction, the interpreter moves to the next instruction b = 20 and immediately executes it, just like it executed a = 10, and finally prints the output.
However, once we get to see a secondary prompt that is “...”, it means that now we have entered a block, that block can be if block, else block, elif block, while, for or any other block. Once inside a block, ‘...’ signifies, all the instructions of the block, entered in front of “...” will be executed by interpreter together “as a series of instructions”.
Example:
Hereafter writing if statement, naturally interpreter enters in if block and starts showing “...”(secondary prompt) to indicate that now the interpreter is ready to take ‘series of instructions’, which will be executed altogether as a group if, ‘if’ statement is found valid.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 254,
"s": 28,
"text": "The \">>>\" sign seen on the Python’s interactive shell is called a prompt. Python’s interactive shell, which appears after firing command “python3” (if we are working on python version 3) on the terminal, has two such prompts."
},
{
"code": null,
"e": 302,
"s": 254,
"text": "\">>>\" - Primary prompt\n\"...\" - Secondary prompt"
},
{
"code": null,
"e": 437,
"s": 302,
"text": "When we fire command ‘python3’ on terminal, >>> sign is immediately seen on screen. This “>>>” sign is nothing but the primary prompt."
},
{
"code": null,
"e": 626,
"s": 437,
"text": "Whenever cursor is blinking next to a primary prompt on terminal, it means interpreter will take ‘one and only one’ instruction and execute it immediately if the instruction is found valid"
},
{
"code": null,
"e": 635,
"s": 626,
"text": "Example:"
},
{
"code": null,
"e": 829,
"s": 635,
"text": "Firstly interpreter will immediately execute a = 10 while doing so it will create an integer object, store 10 inside that integer object and bind that particular object to a variable called ‘a’"
},
{
"code": null,
"e": 1011,
"s": 829,
"text": "After executing the first instruction, the interpreter moves to the next instruction b = 20 and immediately executes it, just like it executed a = 10, and finally prints the output."
},
{
"code": null,
"e": 1370,
"s": 1011,
"text": "However, once we get to see a secondary prompt that is “...”, it means that now we have entered a block, that block can be if block, else block, elif block, while, for or any other block. Once inside a block, ‘...’ signifies, all the instructions of the block, entered in front of “...” will be executed by interpreter together “as a series of instructions”."
},
{
"code": null,
"e": 1379,
"s": 1370,
"text": "Example:"
},
{
"code": null,
"e": 1655,
"s": 1379,
"text": "Hereafter writing if statement, naturally interpreter enters in if block and starts showing “...”(secondary prompt) to indicate that now the interpreter is ready to take ‘series of instructions’, which will be executed altogether as a group if, ‘if’ statement is found valid."
},
{
"code": null,
"e": 1669,
"s": 1655,
"text": "python-basics"
},
{
"code": null,
"e": 1676,
"s": 1669,
"text": "Python"
}
] |
CSS | Pulse animation | 12 Jun, 2020
CSS Pulse Animation Effect provides a pulsating effect to an element that changes its shape and opacity. As per the time and need, different @keyframes are used to achieve this animation. The simple yet powerful effect makes the website more vibrant, colorful, and attractive. This animation is completely implemented without using JavaScript.
Example 1: The below example shows an outward pulse block that stretches itself and shrinks back when it reaches its highest size, starts with a circle, and ends with a square shape with different colors coming out each time when it changes its shape.
<!DOCTYPE html><html> <head> <title> CSS | Pulse animation </title> <style> .element { height: 250px; width: 250px; margin: 0 auto; background-color: lime; animation-name: stretch; animation-duration: 2.0s; animation-timing-function: ease-out; animation-direction: alternate; animation-iteration-count: infinite; animation-play-state: running; } @keyframes stretch { 0% { transform: scale(.5); background-color: green; border-radius: 100%; } 50% { background-color: orange; } 100% { transform: scale(2.0); background-color: red; } } body, html { height: 100%; } body { display: flex; align-items: center; justify-content: center; } </style></head> <body> <div class="element"></div></body> </html>
Output:
Example 2: The below examples show an inward or reverse pulse generating animation effect on a circle that gives inward circular pulse after the completion of the effect. It expands back to its original state and the effect continues to happen.
<!DOCTYPE html><html> <head> <title>Reverse Pulse </title> <link rel="stylesheet" type="text/css" href="style.css"> <style> .pulse { position: absolute; top: 35%; left: 40%; transform: translate(-505, -50%); width: 100px; height: 100px; background: #33ff00; border: 2px solid #33ff00; border-radius: 50%; box-sizing: border-box; box-shadow: 0 0 0 36px #45237a, 0 0 0 40px #56ff00; } .pulse:before, .pulse:after { content: ''; position: absolute; left: -30px; top: -30px; right: -30px; bottom: -30px; border: 2px solid #33ff00; border-radius: 50%; animation: animate 2s linear infinite } .pulse:after { animation-delay: 1s; } @keyframes animate { 0% { transform: scale(2.0); } 100% { transform: scale(0.7); } } } </style></head> <body> <div class="pulse"></div></body> </html>
Output:
CSS-Misc
HTML-Misc
Picked
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": "\n12 Jun, 2020"
},
{
"code": null,
"e": 372,
"s": 28,
"text": "CSS Pulse Animation Effect provides a pulsating effect to an element that changes its shape and opacity. As per the time and need, different @keyframes are used to achieve this animation. The simple yet powerful effect makes the website more vibrant, colorful, and attractive. This animation is completely implemented without using JavaScript."
},
{
"code": null,
"e": 624,
"s": 372,
"text": "Example 1: The below example shows an outward pulse block that stretches itself and shrinks back when it reaches its highest size, starts with a circle, and ends with a square shape with different colors coming out each time when it changes its shape."
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS | Pulse animation </title> <style> .element { height: 250px; width: 250px; margin: 0 auto; background-color: lime; animation-name: stretch; animation-duration: 2.0s; animation-timing-function: ease-out; animation-direction: alternate; animation-iteration-count: infinite; animation-play-state: running; } @keyframes stretch { 0% { transform: scale(.5); background-color: green; border-radius: 100%; } 50% { background-color: orange; } 100% { transform: scale(2.0); background-color: red; } } body, html { height: 100%; } body { display: flex; align-items: center; justify-content: center; } </style></head> <body> <div class=\"element\"></div></body> </html>",
"e": 1736,
"s": 624,
"text": null
},
{
"code": null,
"e": 1744,
"s": 1736,
"text": "Output:"
},
{
"code": null,
"e": 1989,
"s": 1744,
"text": "Example 2: The below examples show an inward or reverse pulse generating animation effect on a circle that gives inward circular pulse after the completion of the effect. It expands back to its original state and the effect continues to happen."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Reverse Pulse </title> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"> <style> .pulse { position: absolute; top: 35%; left: 40%; transform: translate(-505, -50%); width: 100px; height: 100px; background: #33ff00; border: 2px solid #33ff00; border-radius: 50%; box-sizing: border-box; box-shadow: 0 0 0 36px #45237a, 0 0 0 40px #56ff00; } .pulse:before, .pulse:after { content: ''; position: absolute; left: -30px; top: -30px; right: -30px; bottom: -30px; border: 2px solid #33ff00; border-radius: 50%; animation: animate 2s linear infinite } .pulse:after { animation-delay: 1s; } @keyframes animate { 0% { transform: scale(2.0); } 100% { transform: scale(0.7); } } } </style></head> <body> <div class=\"pulse\"></div></body> </html>",
"e": 3203,
"s": 1989,
"text": null
},
{
"code": null,
"e": 3211,
"s": 3203,
"text": "Output:"
},
{
"code": null,
"e": 3220,
"s": 3211,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3230,
"s": 3220,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3237,
"s": 3230,
"text": "Picked"
},
{
"code": null,
"e": 3241,
"s": 3237,
"text": "CSS"
},
{
"code": null,
"e": 3246,
"s": 3241,
"text": "HTML"
},
{
"code": null,
"e": 3263,
"s": 3246,
"text": "Web Technologies"
},
{
"code": null,
"e": 3290,
"s": 3263,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3295,
"s": 3290,
"text": "HTML"
}
] |
SQL - CREATE Database | The SQL CREATE DATABASE statement is used to create a new SQL database.
The basic syntax of this CREATE DATABASE statement is as follows −
CREATE DATABASE DatabaseName;
Always the database name should be unique within the RDBMS.
If you want to create a new database <testDB>, then the CREATE DATABASE statement would be as shown below −
SQL> CREATE DATABASE testDB;
Make sure you have the admin privilege before creating any database. Once a database is created, you can check it in the list of databases as follows −
SQL> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+--------------------+
7 rows in set (0.00 sec)
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2525,
"s": 2453,
"text": "The SQL CREATE DATABASE statement is used to create a new SQL database."
},
{
"code": null,
"e": 2592,
"s": 2525,
"text": "The basic syntax of this CREATE DATABASE statement is as follows −"
},
{
"code": null,
"e": 2623,
"s": 2592,
"text": "CREATE DATABASE DatabaseName;\n"
},
{
"code": null,
"e": 2683,
"s": 2623,
"text": "Always the database name should be unique within the RDBMS."
},
{
"code": null,
"e": 2791,
"s": 2683,
"text": "If you want to create a new database <testDB>, then the CREATE DATABASE statement would be as shown below −"
},
{
"code": null,
"e": 2820,
"s": 2791,
"text": "SQL> CREATE DATABASE testDB;"
},
{
"code": null,
"e": 2972,
"s": 2820,
"text": "Make sure you have the admin privilege before creating any database. Once a database is created, you can check it in the list of databases as follows −"
},
{
"code": null,
"e": 3272,
"s": 2972,
"text": "SQL> SHOW DATABASES;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| AMROOD |\n| TUTORIALSPOINT |\n| mysql |\n| orig |\n| test |\n| testDB |\n+--------------------+\n7 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 3305,
"s": 3272,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3319,
"s": 3305,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3352,
"s": 3319,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3366,
"s": 3352,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3401,
"s": 3366,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3415,
"s": 3401,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3448,
"s": 3415,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3470,
"s": 3448,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3505,
"s": 3470,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3559,
"s": 3505,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 3592,
"s": 3559,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3620,
"s": 3592,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3627,
"s": 3620,
"text": " Print"
},
{
"code": null,
"e": 3638,
"s": 3627,
"text": " Add Notes"
}
] |
JavaScript | Remove the last item from an array - GeeksforGeeks | 18 May, 2019
The task is to remove the last item from the array. Here are a few of the most preferred methods discussed.First few functions to understand.
JavaScript Array splice() methodThis method adds/deletes items to/from the array, and returns the deleted item(s).Syntax:array.splice(index, number, item1, ....., itemN)
Parameters:index: This parameter is required. It specifies the integer at what position to add/remove items, Negative values are used to specify the position from the end of the array.number: This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove.item1, ....., itemN: This parameter is optional. This specifies the new item(s) to be added tothe array.Return value:Returns a new Array, having the removed items.
array.splice(index, number, item1, ....., itemN)
Parameters:
index: This parameter is required. It specifies the integer at what position to add/remove items, Negative values are used to specify the position from the end of the array.
number: This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove.
item1, ....., itemN: This parameter is optional. This specifies the new item(s) to be added tothe array.
Return value:Returns a new Array, having the removed items.
JavaScript Array slice() MethodThis method returns a new array containing the selected elements.This method selects the elements starts from the given start argument and ends at, but excluding the given end argument.Syntax:array.slice(start, end)
Parameters:start: This parameter is optional. It specifies the integer from where to start the selection (first element is at index 0). Negative numbers are used to select from the end of the array. If not used, it acts like “0”end: This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of array will be included in selection. Negative numbers are used to select from the end.Return value:Returns a new Array, having the selected items.
JavaScript Array slice() MethodThis method returns a new array containing the selected elements.This method selects the elements starts from the given start argument and ends at, but excluding the given end argument.Syntax:
array.slice(start, end)
Parameters:
start: This parameter is optional. It specifies the integer from where to start the selection (first element is at index 0). Negative numbers are used to select from the end of the array. If not used, it acts like “0”
end: This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of array will be included in selection. Negative numbers are used to select from the end.
Return value:Returns a new Array, having the selected items.
JavaScript Array pop() MethodThis method deletes the last element of an array and returns the element.Syntax:array.pop()
Return value:It returns the removed array item. An array item can be a string, a number, an array, a boolean, or any other object types that are applicable in an array.Example 1: This example removes the last item from the array using splice() method.<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> remove </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" + array + "]"; function gfg_Run() { array.splice(-1, 1); el_down.innerHTML = "Remaining array = [" + array + "]"; } </script></body> </html>Output:Before clicking on the button:After clicking on the button:Example 2: This example removes the last item from the array using pop() method.<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> remove </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" + array + "]"; function gfg_Run() { array.pop(); el_down.innerHTML = "Remaining array = [" + array + "]"; } </script></body> </html>Output:Before clicking on the button:After clicking on the button:Example 3: This example does not remove the last item from the array but returns a new array in which the item is removed, using splice() method.<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> remove </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" + array + "]"; function gfg_Run() { el_down.innerHTML = "Remaining array = [" + array.slice(0, -1) + "]"; } </script></body> </html>Output:Before clicking on the button:After clicking on the button:My Personal Notes
arrow_drop_upSave
JavaScript Array pop() MethodThis method deletes the last element of an array and returns the element.Syntax:
array.pop()
Return value:It returns the removed array item. An array item can be a string, a number, an array, a boolean, or any other object types that are applicable in an array.
Example 1: This example removes the last item from the array using splice() method.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> remove </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" + array + "]"; function gfg_Run() { array.splice(-1, 1); el_down.innerHTML = "Remaining array = [" + array + "]"; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example removes the last item from the array using pop() method.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> remove </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" + array + "]"; function gfg_Run() { array.pop(); el_down.innerHTML = "Remaining array = [" + array + "]"; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 3: This example does not remove the last item from the array but returns a new array in which the item is removed, using splice() method.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> remove </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" + array + "]"; function gfg_Run() { el_down.innerHTML = "Remaining array = [" + array.slice(0, -1) + "]"; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-array
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 25434,
"s": 25406,
"text": "\n18 May, 2019"
},
{
"code": null,
"e": 25576,
"s": 25434,
"text": "The task is to remove the last item from the array. Here are a few of the most preferred methods discussed.First few functions to understand."
},
{
"code": null,
"e": 26205,
"s": 25576,
"text": "JavaScript Array splice() methodThis method adds/deletes items to/from the array, and returns the deleted item(s).Syntax:array.splice(index, number, item1, ....., itemN)\nParameters:index: This parameter is required. It specifies the integer at what position to add/remove items, Negative values are used to specify the position from the end of the array.number: This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove.item1, ....., itemN: This parameter is optional. This specifies the new item(s) to be added tothe array.Return value:Returns a new Array, having the removed items."
},
{
"code": null,
"e": 26255,
"s": 26205,
"text": "array.splice(index, number, item1, ....., itemN)\n"
},
{
"code": null,
"e": 26267,
"s": 26255,
"text": "Parameters:"
},
{
"code": null,
"e": 26441,
"s": 26267,
"text": "index: This parameter is required. It specifies the integer at what position to add/remove items, Negative values are used to specify the position from the end of the array."
},
{
"code": null,
"e": 26553,
"s": 26441,
"text": "number: This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove."
},
{
"code": null,
"e": 26658,
"s": 26553,
"text": "item1, ....., itemN: This parameter is optional. This specifies the new item(s) to be added tothe array."
},
{
"code": null,
"e": 26718,
"s": 26658,
"text": "Return value:Returns a new Array, having the removed items."
},
{
"code": null,
"e": 27486,
"s": 26718,
"text": "JavaScript Array slice() MethodThis method returns a new array containing the selected elements.This method selects the elements starts from the given start argument and ends at, but excluding the given end argument.Syntax:array.slice(start, end)\nParameters:start: This parameter is optional. It specifies the integer from where to start the selection (first element is at index 0). Negative numbers are used to select from the end of the array. If not used, it acts like “0”end: This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of array will be included in selection. Negative numbers are used to select from the end.Return value:Returns a new Array, having the selected items."
},
{
"code": null,
"e": 27710,
"s": 27486,
"text": "JavaScript Array slice() MethodThis method returns a new array containing the selected elements.This method selects the elements starts from the given start argument and ends at, but excluding the given end argument.Syntax:"
},
{
"code": null,
"e": 27735,
"s": 27710,
"text": "array.slice(start, end)\n"
},
{
"code": null,
"e": 27747,
"s": 27735,
"text": "Parameters:"
},
{
"code": null,
"e": 27965,
"s": 27747,
"text": "start: This parameter is optional. It specifies the integer from where to start the selection (first element is at index 0). Negative numbers are used to select from the end of the array. If not used, it acts like “0”"
},
{
"code": null,
"e": 28198,
"s": 27965,
"text": "end: This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of array will be included in selection. Negative numbers are used to select from the end."
},
{
"code": null,
"e": 28259,
"s": 28198,
"text": "Return value:Returns a new Array, having the selected items."
},
{
"code": null,
"e": 31715,
"s": 28259,
"text": "JavaScript Array pop() MethodThis method deletes the last element of an array and returns the element.Syntax:array.pop()\nReturn value:It returns the removed array item. An array item can be a string, a number, an array, a boolean, or any other object types that are applicable in an array.Example 1: This example removes the last item from the array using splice() method.<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> remove </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [34, 24, 31, 48]; el_up.innerHTML = \"Array = [\" + array + \"]\"; function gfg_Run() { array.splice(-1, 1); el_down.innerHTML = \"Remaining array = [\" + array + \"]\"; } </script></body> </html>Output:Before clicking on the button:After clicking on the button:Example 2: This example removes the last item from the array using pop() method.<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> remove </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [34, 24, 31, 48]; el_up.innerHTML = \"Array = [\" + array + \"]\"; function gfg_Run() { array.pop(); el_down.innerHTML = \"Remaining array = [\" + array + \"]\"; } </script></body> </html>Output:Before clicking on the button:After clicking on the button:Example 3: This example does not remove the last item from the array but returns a new array in which the item is removed, using splice() method.<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> remove </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [34, 24, 31, 48]; el_up.innerHTML = \"Array = [\" + array + \"]\"; function gfg_Run() { el_down.innerHTML = \"Remaining array = [\" + array.slice(0, -1) + \"]\"; } </script></body> </html>Output:Before clicking on the button:After clicking on the button:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 31825,
"s": 31715,
"text": "JavaScript Array pop() MethodThis method deletes the last element of an array and returns the element.Syntax:"
},
{
"code": null,
"e": 31838,
"s": 31825,
"text": "array.pop()\n"
},
{
"code": null,
"e": 32007,
"s": 31838,
"text": "Return value:It returns the removed array item. An array item can be a string, a number, an array, a boolean, or any other object types that are applicable in an array."
},
{
"code": null,
"e": 32091,
"s": 32007,
"text": "Example 1: This example removes the last item from the array using splice() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> remove </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [34, 24, 31, 48]; el_up.innerHTML = \"Array = [\" + array + \"]\"; function gfg_Run() { array.splice(-1, 1); el_down.innerHTML = \"Remaining array = [\" + array + \"]\"; } </script></body> </html>",
"e": 32982,
"s": 32091,
"text": null
},
{
"code": null,
"e": 32990,
"s": 32982,
"text": "Output:"
},
{
"code": null,
"e": 33021,
"s": 32990,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 33051,
"s": 33021,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 33132,
"s": 33051,
"text": "Example 2: This example removes the last item from the array using pop() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> remove </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [34, 24, 31, 48]; el_up.innerHTML = \"Array = [\" + array + \"]\"; function gfg_Run() { array.pop(); el_down.innerHTML = \"Remaining array = [\" + array + \"]\"; } </script></body> </html>",
"e": 34018,
"s": 33132,
"text": null
},
{
"code": null,
"e": 34026,
"s": 34018,
"text": "Output:"
},
{
"code": null,
"e": 34057,
"s": 34026,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 34087,
"s": 34057,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 34233,
"s": 34087,
"text": "Example 3: This example does not remove the last item from the array but returns a new array in which the item is removed, using splice() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Remove last item from array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> remove </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [34, 24, 31, 48]; el_up.innerHTML = \"Array = [\" + array + \"]\"; function gfg_Run() { el_down.innerHTML = \"Remaining array = [\" + array.slice(0, -1) + \"]\"; } </script></body> </html>",
"e": 35084,
"s": 34233,
"text": null
},
{
"code": null,
"e": 35092,
"s": 35084,
"text": "Output:"
},
{
"code": null,
"e": 35123,
"s": 35092,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 35153,
"s": 35123,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 35170,
"s": 35153,
"text": "javascript-array"
},
{
"code": null,
"e": 35181,
"s": 35170,
"text": "JavaScript"
},
{
"code": null,
"e": 35198,
"s": 35181,
"text": "Web Technologies"
},
{
"code": null,
"e": 35296,
"s": 35198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35341,
"s": 35296,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35402,
"s": 35341,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35474,
"s": 35402,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 35515,
"s": 35474,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 35561,
"s": 35515,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 35603,
"s": 35561,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 35636,
"s": 35603,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35679,
"s": 35636,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 35729,
"s": 35679,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Calculation of TCP Checksum - GeeksforGeeks | 19 Nov, 2021
In this article, we will learn a good concept of how the TCP/UDP checksum is calculated.
When we receive data from the application it is broken into smaller data parts as the whole data from the application cannot be sent through the network to the receiver host.
The protocol we use in OSI in the Transport layer is TCP. So, after breaking the data from the application layer into smaller parts. This broken part form the body of the TCP.
The TCP header usually varies from 20 Bytes(with no bits of option fields being used) to 60 Bytes(with all bits of options field being used).
It has fields like Source and Destination Port addresses, urgent pointer, Checksum, etc.
In this article, we are only concerned about the CheckSum field of the TCP.
The CheckSum of the TCP is calculated by taking into account the TCP Header, TCP body and Pseudo IP header.
Now, the main ambiguity that arises that what is how can checksum be calculated on IP header as IP comes into the picture in the layer below the Transport Layer.
In simple terms, it means that we are in Transport Layer and the IP data packet is created in Network Layer.
Then how can we estimate the size of the IP header from the Transport because the guess/estimation would be definitely wrong and thus there would be no point in calculating the checksum on a field which is wrong at the beginning itself?
The error checking capability of TCP/UDP in Transport Layer takes help from the network layer for proper error detection.
But the important concept to note here is that we actually don’t use the IP header rather we use a part of the IP header.
To overcome all these errors and increase error checking capability we use Pseudo IP header.
Pseudo IP header: The pseudo-header is not an IP header rather it is a part of the IP header. We directly don’t use the IP header because in IP header there are many which would be continuously changing when then packets move along the network . Thus a part of the IP header is taken into account which don’t change as the IP packet moves in the network.
The Fields of the Pseudo IP header are:-
IP of the Source IP of the Destination TCP/UDP segment Length Protocol (stating the type of the protocol used) Fixed of 8-bits
IP of the Source
IP of the Destination
TCP/UDP segment Length
Protocol (stating the type of the protocol used)
Fixed of 8-bits
So, the total size of the pseudo header(12 Bytes) = IP of the Source (32 bits) + IP of the Destination (32 bits) +TCP/UDP segment Length(16 bit) + Protocol(8 bits) + Fixed 8 bits
An important concept should be noted that this Pseudo header is created in the Transport layer for calculation and after the calculation is done the Pseudo header is discarded. And the checksum is calculated by using the usual checksum method.
So, this Pseudo Header is not transported across the network, rather the actual IP header which is formed in Network Layer is transported.
So, the TCP checksum includes the:-
1. Pseudo IP header
2. TCP header
3. TCP body
After the calculation of the checksum using the above 3 fields, the checksum result is placed in the checksum field of the TCP header.
As it is already stated that the Pseudo header is discarded and is not transported to the destination host then how does the Destination host check if the data is received correctly or not. Thus, the pseudo-header is once again created in the Transport layer of the Destination host and then again the checksum is calculated in the Transport Layer of Destination Host and finally, the checksum is calculated by the usual method of checksum and is confirmed if the data received is correct or not.
Why IP header error checking two times is needed ?
The IP header is checked two times the first time in the Transport layer and second time in Network Layer. The IP header is checked two times because double checking ensures that any error in the IP header can be detected with proper accuracy.
ayushidubeyhere
gulshankumarar231
Transport Layer
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Multiple Access Protocols in Computer Network
Intrusion Detection System (IDS)
GSM in Wireless Communication
Cryptography and its Types
ACID Properties in DBMS
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Normal Forms in DBMS
Semaphores in Process Synchronization | [
{
"code": null,
"e": 24535,
"s": 24507,
"text": "\n19 Nov, 2021"
},
{
"code": null,
"e": 24625,
"s": 24535,
"text": "In this article, we will learn a good concept of how the TCP/UDP checksum is calculated. "
},
{
"code": null,
"e": 24801,
"s": 24625,
"text": "When we receive data from the application it is broken into smaller data parts as the whole data from the application cannot be sent through the network to the receiver host. "
},
{
"code": null,
"e": 24978,
"s": 24801,
"text": "The protocol we use in OSI in the Transport layer is TCP. So, after breaking the data from the application layer into smaller parts. This broken part form the body of the TCP. "
},
{
"code": null,
"e": 25121,
"s": 24978,
"text": "The TCP header usually varies from 20 Bytes(with no bits of option fields being used) to 60 Bytes(with all bits of options field being used). "
},
{
"code": null,
"e": 25211,
"s": 25121,
"text": "It has fields like Source and Destination Port addresses, urgent pointer, Checksum, etc. "
},
{
"code": null,
"e": 25288,
"s": 25211,
"text": "In this article, we are only concerned about the CheckSum field of the TCP. "
},
{
"code": null,
"e": 25397,
"s": 25288,
"text": "The CheckSum of the TCP is calculated by taking into account the TCP Header, TCP body and Pseudo IP header. "
},
{
"code": null,
"e": 25560,
"s": 25397,
"text": "Now, the main ambiguity that arises that what is how can checksum be calculated on IP header as IP comes into the picture in the layer below the Transport Layer. "
},
{
"code": null,
"e": 25670,
"s": 25560,
"text": "In simple terms, it means that we are in Transport Layer and the IP data packet is created in Network Layer. "
},
{
"code": null,
"e": 25908,
"s": 25670,
"text": "Then how can we estimate the size of the IP header from the Transport because the guess/estimation would be definitely wrong and thus there would be no point in calculating the checksum on a field which is wrong at the beginning itself? "
},
{
"code": null,
"e": 26031,
"s": 25908,
"text": "The error checking capability of TCP/UDP in Transport Layer takes help from the network layer for proper error detection. "
},
{
"code": null,
"e": 26154,
"s": 26031,
"text": "But the important concept to note here is that we actually don’t use the IP header rather we use a part of the IP header. "
},
{
"code": null,
"e": 26248,
"s": 26154,
"text": "To overcome all these errors and increase error checking capability we use Pseudo IP header. "
},
{
"code": null,
"e": 26604,
"s": 26248,
"text": "Pseudo IP header: The pseudo-header is not an IP header rather it is a part of the IP header. We directly don’t use the IP header because in IP header there are many which would be continuously changing when then packets move along the network . Thus a part of the IP header is taken into account which don’t change as the IP packet moves in the network. "
},
{
"code": null,
"e": 26647,
"s": 26604,
"text": "The Fields of the Pseudo IP header are:- "
},
{
"code": null,
"e": 26780,
"s": 26647,
"text": "IP of the Source IP of the Destination TCP/UDP segment Length Protocol (stating the type of the protocol used) Fixed of 8-bits "
},
{
"code": null,
"e": 26799,
"s": 26780,
"text": "IP of the Source "
},
{
"code": null,
"e": 26823,
"s": 26799,
"text": "IP of the Destination "
},
{
"code": null,
"e": 26848,
"s": 26823,
"text": "TCP/UDP segment Length "
},
{
"code": null,
"e": 26899,
"s": 26848,
"text": "Protocol (stating the type of the protocol used) "
},
{
"code": null,
"e": 26917,
"s": 26899,
"text": "Fixed of 8-bits "
},
{
"code": null,
"e": 27098,
"s": 26917,
"text": "So, the total size of the pseudo header(12 Bytes) = IP of the Source (32 bits) + IP of the Destination (32 bits) +TCP/UDP segment Length(16 bit) + Protocol(8 bits) + Fixed 8 bits "
},
{
"code": null,
"e": 27343,
"s": 27098,
"text": "An important concept should be noted that this Pseudo header is created in the Transport layer for calculation and after the calculation is done the Pseudo header is discarded. And the checksum is calculated by using the usual checksum method. "
},
{
"code": null,
"e": 27483,
"s": 27343,
"text": "So, this Pseudo Header is not transported across the network, rather the actual IP header which is formed in Network Layer is transported. "
},
{
"code": null,
"e": 27521,
"s": 27483,
"text": "So, the TCP checksum includes the:- "
},
{
"code": null,
"e": 27568,
"s": 27521,
"text": "1. Pseudo IP header \n2. TCP header\n3. TCP body"
},
{
"code": null,
"e": 27706,
"s": 27570,
"text": "After the calculation of the checksum using the above 3 fields, the checksum result is placed in the checksum field of the TCP header. "
},
{
"code": null,
"e": 28204,
"s": 27706,
"text": "As it is already stated that the Pseudo header is discarded and is not transported to the destination host then how does the Destination host check if the data is received correctly or not. Thus, the pseudo-header is once again created in the Transport layer of the Destination host and then again the checksum is calculated in the Transport Layer of Destination Host and finally, the checksum is calculated by the usual method of checksum and is confirmed if the data received is correct or not. "
},
{
"code": null,
"e": 28256,
"s": 28204,
"text": "Why IP header error checking two times is needed ? "
},
{
"code": null,
"e": 28501,
"s": 28256,
"text": "The IP header is checked two times the first time in the Transport layer and second time in Network Layer. The IP header is checked two times because double checking ensures that any error in the IP header can be detected with proper accuracy. "
},
{
"code": null,
"e": 28517,
"s": 28501,
"text": "ayushidubeyhere"
},
{
"code": null,
"e": 28535,
"s": 28517,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 28551,
"s": 28535,
"text": "Transport Layer"
},
{
"code": null,
"e": 28569,
"s": 28551,
"text": "Computer Networks"
},
{
"code": null,
"e": 28577,
"s": 28569,
"text": "GATE CS"
},
{
"code": null,
"e": 28595,
"s": 28577,
"text": "Computer Networks"
},
{
"code": null,
"e": 28693,
"s": 28595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28728,
"s": 28693,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 28774,
"s": 28728,
"text": "Multiple Access Protocols in Computer Network"
},
{
"code": null,
"e": 28807,
"s": 28774,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 28837,
"s": 28807,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 28864,
"s": 28837,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 28888,
"s": 28864,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 28937,
"s": 28888,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 28964,
"s": 28937,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 28985,
"s": 28964,
"text": "Normal Forms in DBMS"
}
] |
ByteArrayInputStream available() method in Java with Examples - GeeksforGeeks | 13 Sep, 2021
The available() method is a built-in method of the Java.io.ByteArrayInputStream returns the number of remaining bytes that can be read (or skipped over) from this input stream. It tells the total no. of bytes from the Input Stream to be read.
Syntax:
public int available()
Parameters: The function does not accept any parameter.Return Value: The function returns the total no of bytes from the Input Stream to be read.
Below is the implementation of the above function:
Program 1:
Java
// Java program to implement// the above functionimport java.io.*; public class Main { public static void main(String[] args) throws Exception { // Array byte[] buffer = { 71, 69, 69, 75, 83 }; // Create InputStream ByteArrayInputStream geek = new ByteArrayInputStream(buffer); // Use the function to get the number // of available int number = geek.available(); // Print System.out.println("Use of available() method : " + number); }}
Use of available() method : 5
Program 2:
Java
// Java program to implement// the above functionimport java.io.*; public class Main { public static void main(String[] args) throws Exception { // Array byte[] buffer = { 1, 2, 3, 4 }; // Create InputStream ByteArrayInputStream geek = new ByteArrayInputStream(buffer); // Use the function to get the number // of available int number = geek.available(); // Print System.out.println("Use of available() method : " + number); }}
Use of available() method : 4
Reference: https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayInputStream.html#available()
avtarkumar719
Java-ByteArrayInputStream
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java | [
{
"code": null,
"e": 24560,
"s": 24532,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 24804,
"s": 24560,
"text": "The available() method is a built-in method of the Java.io.ByteArrayInputStream returns the number of remaining bytes that can be read (or skipped over) from this input stream. It tells the total no. of bytes from the Input Stream to be read. "
},
{
"code": null,
"e": 24813,
"s": 24804,
"text": "Syntax: "
},
{
"code": null,
"e": 24836,
"s": 24813,
"text": "public int available()"
},
{
"code": null,
"e": 24983,
"s": 24836,
"text": "Parameters: The function does not accept any parameter.Return Value: The function returns the total no of bytes from the Input Stream to be read. "
},
{
"code": null,
"e": 25034,
"s": 24983,
"text": "Below is the implementation of the above function:"
},
{
"code": null,
"e": 25047,
"s": 25034,
"text": "Program 1: "
},
{
"code": null,
"e": 25052,
"s": 25047,
"text": "Java"
},
{
"code": "// Java program to implement// the above functionimport java.io.*; public class Main { public static void main(String[] args) throws Exception { // Array byte[] buffer = { 71, 69, 69, 75, 83 }; // Create InputStream ByteArrayInputStream geek = new ByteArrayInputStream(buffer); // Use the function to get the number // of available int number = geek.available(); // Print System.out.println(\"Use of available() method : \" + number); }}",
"e": 25601,
"s": 25052,
"text": null
},
{
"code": null,
"e": 25631,
"s": 25601,
"text": "Use of available() method : 5"
},
{
"code": null,
"e": 25645,
"s": 25633,
"text": "Program 2: "
},
{
"code": null,
"e": 25650,
"s": 25645,
"text": "Java"
},
{
"code": "// Java program to implement// the above functionimport java.io.*; public class Main { public static void main(String[] args) throws Exception { // Array byte[] buffer = { 1, 2, 3, 4 }; // Create InputStream ByteArrayInputStream geek = new ByteArrayInputStream(buffer); // Use the function to get the number // of available int number = geek.available(); // Print System.out.println(\"Use of available() method : \" + number); }}",
"e": 26191,
"s": 25650,
"text": null
},
{
"code": null,
"e": 26221,
"s": 26191,
"text": "Use of available() method : 4"
},
{
"code": null,
"e": 26324,
"s": 26223,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayInputStream.html#available() "
},
{
"code": null,
"e": 26338,
"s": 26324,
"text": "avtarkumar719"
},
{
"code": null,
"e": 26364,
"s": 26338,
"text": "Java-ByteArrayInputStream"
},
{
"code": null,
"e": 26379,
"s": 26364,
"text": "Java-Functions"
},
{
"code": null,
"e": 26395,
"s": 26379,
"text": "Java-IO package"
},
{
"code": null,
"e": 26400,
"s": 26395,
"text": "Java"
},
{
"code": null,
"e": 26405,
"s": 26400,
"text": "Java"
},
{
"code": null,
"e": 26503,
"s": 26405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26535,
"s": 26503,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26586,
"s": 26535,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26616,
"s": 26586,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26635,
"s": 26616,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26653,
"s": 26635,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26684,
"s": 26653,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26716,
"s": 26684,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26736,
"s": 26716,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26751,
"s": 26736,
"text": "Stream In Java"
}
] |
Tryit Editor v3.7 | HTML Computer Code
Tryit: HTML code element | [
{
"code": null,
"e": 29,
"s": 10,
"text": "HTML Computer Code"
}
] |
What is a sealed class in C#? | Sealed class in C# with the sealed keyword cannot be inherited. In the same way, the sealed keyword can be added to the method.
When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.
Let us see an example of sealed class in C# −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class Program {
static void Main(string[] args) {
Result ob = new Result();
string str = ob.Display();
Console.WriteLine(str);
Console.ReadLine();
}
}
public sealed class Result {
public string Display() {
return "Passed";
}
}
}
To access the members of the sealed class, we need to create the object. The method created inside the sealed class cannot be inherited −
public sealed class Result {
public string Display() {
return "Passed";
}
} | [
{
"code": null,
"e": 1190,
"s": 1062,
"text": "Sealed class in C# with the sealed keyword cannot be inherited. In the same way, the sealed keyword can be added to the method."
},
{
"code": null,
"e": 1390,
"s": 1190,
"text": "When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method."
},
{
"code": null,
"e": 1436,
"s": 1390,
"text": "Let us see an example of sealed class in C# −"
},
{
"code": null,
"e": 1852,
"s": 1436,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n Result ob = new Result();\n string str = ob.Display();\n\n Console.WriteLine(str);\n Console.ReadLine();\n }\n }\n\n public sealed class Result {\n public string Display() {\n return \"Passed\";\n }\n }\n}"
},
{
"code": null,
"e": 1990,
"s": 1852,
"text": "To access the members of the sealed class, we need to create the object. The method created inside the sealed class cannot be inherited −"
},
{
"code": null,
"e": 2078,
"s": 1990,
"text": "public sealed class Result {\n public string Display() {\n return \"Passed\";\n }\n}"
}
] |
Apache Pig - PluckTuple() | After performing operations like join to differentiate the columns of the two schemas, we use the function PluckTuple(). To use this function, first of all, we have to define a string Prefix and we have to filter for the columns in a relation that begin with that prefix.
Given below is the syntax of the PluckTuple() function.
DEFINE pluck PluckTuple(expression1)
DEFINE pluck PluckTuple(expression1,expression3)
pluck(expression2)
Assume that we have two files namely emp_sales.txt and emp_bonus.txt in the HDFS directory /pig_data/. The emp_sales.txt contains the details of the employees of the sales department and the emp_bonus.txt contains the employee details who got bonus.
emp_sales.txt
1,Robin,22,25000,sales
2,BOB,23,30000,sales
3,Maya,23,25000,sales
4,Sara,25,40000,sales
5,David,23,45000,sales
6,Maggy,22,35000,sales
emp_bonus.txt
1,Robin,22,25000,sales
2,Jaya,23,20000,admin
3,Maya,23,25000,sales
4,Alia,25,50000,admin
5,David,23,45000,sales
6,Omar,30,30000,admin
And we have loaded these files into Pig, with the relation names emp_sales and emp_bonus respectively.
grunt> emp_sales = LOAD 'hdfs://localhost:9000/pig_data/emp_sales.txt' USING PigStorage(',')
as (sno:int, name:chararray, age:int, salary:int, dept:chararray);
grunt> emp_bonus = LOAD 'hdfs://localhost:9000/pig_data/emp_bonus.txt' USING PigStorage(',')
as (sno:int, name:chararray, age:int, salary:int, dept:chararray);
Join these two relations using the join operator as shown below.
grunt> join_data = join emp_sales by sno, emp_bonus by sno;
Verify the relation join_data using the Dump operator.
grunt> Dump join_data;
(1,Robin,22,25000,sales,1,Robin,22,25000,sales)
(2,BOB,23,30000,sales,2,Jaya,23,20000,admin)
(3,Maya,23,25000,sales,3,Maya,23,25000,sales)
(4,Sara,25,40000,sales,4,Alia,25,50000,admin)
(5,David,23,45000,sales,5,David,23,45000,sales)
(6,Maggy,22,35000,sales,6,Omar,30,30000,admin)
Now, define the required expression by which you want to differentiate the columns using PluckTupe() function.
grunt> DEFINE pluck PluckTuple('a::');
Filter the columns in the join_data relation as shown below.
grunt> data = foreach join_data generate FLATTEN(pluck(*));
Describe the relation named data as shown below.
grunt> Describe data;
data: {emp_sales::sno: int, emp_sales::name: chararray, emp_sales::age: int,
emp_sales::salary: int, emp_sales::dept: chararray, emp_bonus::sno: int,
emp_bonus::name: chararray, emp_bonus::age: int, emp_bonus::salary: int,
emp_bonus::dept: chararray}
Since we have defined the expression as “a::”, the columns of the emp_sales schema are plucked as emp_sales::column name and the columns of the emp_bonus schema are plucked as emp_bonus::column name
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2956,
"s": 2684,
"text": "After performing operations like join to differentiate the columns of the two schemas, we use the function PluckTuple(). To use this function, first of all, we have to define a string Prefix and we have to filter for the columns in a relation that begin with that prefix."
},
{
"code": null,
"e": 3012,
"s": 2956,
"text": "Given below is the syntax of the PluckTuple() function."
},
{
"code": null,
"e": 3120,
"s": 3012,
"text": "DEFINE pluck PluckTuple(expression1) \nDEFINE pluck PluckTuple(expression1,expression3) \npluck(expression2)\n"
},
{
"code": null,
"e": 3370,
"s": 3120,
"text": "Assume that we have two files namely emp_sales.txt and emp_bonus.txt in the HDFS directory /pig_data/. The emp_sales.txt contains the details of the employees of the sales department and the emp_bonus.txt contains the employee details who got bonus."
},
{
"code": null,
"e": 3384,
"s": 3370,
"text": "emp_sales.txt"
},
{
"code": null,
"e": 3524,
"s": 3384,
"text": "1,Robin,22,25000,sales \n2,BOB,23,30000,sales \n3,Maya,23,25000,sales \n4,Sara,25,40000,sales \n5,David,23,45000,sales \n6,Maggy,22,35000,sales\n"
},
{
"code": null,
"e": 3538,
"s": 3524,
"text": "emp_bonus.txt"
},
{
"code": null,
"e": 3677,
"s": 3538,
"text": "1,Robin,22,25000,sales \n2,Jaya,23,20000,admin \n3,Maya,23,25000,sales \n4,Alia,25,50000,admin \n5,David,23,45000,sales\n6,Omar,30,30000,admin\n"
},
{
"code": null,
"e": 3780,
"s": 3677,
"text": "And we have loaded these files into Pig, with the relation names emp_sales and emp_bonus respectively."
},
{
"code": null,
"e": 4108,
"s": 3780,
"text": "grunt> emp_sales = LOAD 'hdfs://localhost:9000/pig_data/emp_sales.txt' USING PigStorage(',')\n as (sno:int, name:chararray, age:int, salary:int, dept:chararray);\n\t\ngrunt> emp_bonus = LOAD 'hdfs://localhost:9000/pig_data/emp_bonus.txt' USING PigStorage(',')\n as (sno:int, name:chararray, age:int, salary:int, dept:chararray);"
},
{
"code": null,
"e": 4173,
"s": 4108,
"text": "Join these two relations using the join operator as shown below."
},
{
"code": null,
"e": 4233,
"s": 4173,
"text": "grunt> join_data = join emp_sales by sno, emp_bonus by sno;"
},
{
"code": null,
"e": 4288,
"s": 4233,
"text": "Verify the relation join_data using the Dump operator."
},
{
"code": null,
"e": 4596,
"s": 4288,
"text": "grunt> Dump join_data;\n \n(1,Robin,22,25000,sales,1,Robin,22,25000,sales)\n(2,BOB,23,30000,sales,2,Jaya,23,20000,admin)\n(3,Maya,23,25000,sales,3,Maya,23,25000,sales)\n(4,Sara,25,40000,sales,4,Alia,25,50000,admin) \n(5,David,23,45000,sales,5,David,23,45000,sales) \n(6,Maggy,22,35000,sales,6,Omar,30,30000,admin)\n"
},
{
"code": null,
"e": 4707,
"s": 4596,
"text": "Now, define the required expression by which you want to differentiate the columns using PluckTupe() function."
},
{
"code": null,
"e": 4746,
"s": 4707,
"text": "grunt> DEFINE pluck PluckTuple('a::');"
},
{
"code": null,
"e": 4807,
"s": 4746,
"text": "Filter the columns in the join_data relation as shown below."
},
{
"code": null,
"e": 4867,
"s": 4807,
"text": "grunt> data = foreach join_data generate FLATTEN(pluck(*));"
},
{
"code": null,
"e": 4916,
"s": 4867,
"text": "Describe the relation named data as shown below."
},
{
"code": null,
"e": 5201,
"s": 4916,
"text": "grunt> Describe data;\n \ndata: {emp_sales::sno: int, emp_sales::name: chararray, emp_sales::age: int,\n emp_sales::salary: int, emp_sales::dept: chararray, emp_bonus::sno: int,\n emp_bonus::name: chararray, emp_bonus::age: int, emp_bonus::salary: int,\n emp_bonus::dept: chararray}\n"
},
{
"code": null,
"e": 5401,
"s": 5201,
"text": "Since we have defined the expression as “a::”, the columns of the emp_sales schema are plucked as emp_sales::column name and the columns of the emp_bonus schema are plucked as emp_bonus::column name"
},
{
"code": null,
"e": 5436,
"s": 5401,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5455,
"s": 5436,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5490,
"s": 5455,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5511,
"s": 5490,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5544,
"s": 5511,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5557,
"s": 5544,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5592,
"s": 5557,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5610,
"s": 5592,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5643,
"s": 5610,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5661,
"s": 5643,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5694,
"s": 5661,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5712,
"s": 5694,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5719,
"s": 5712,
"text": " Print"
},
{
"code": null,
"e": 5730,
"s": 5719,
"text": " Add Notes"
}
] |
Set characters at a specific position within the string in Arduino | In case you don’t want to overwrite a string, but just change a character at a specific position, Arduino provides the setCharAt() function exactly for that.
String1.setCharAt(ind, new_char);
String 1 is the string to modify. ind is the index where the character needs to be set. new_char is the value of the new character that needs to be set.
This function returns nothing, and modifies the string in place.
The following example illustrates the use of this function.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
String string1 = "Hello World!";
Serial.println(string1);
string1.setCharAt(4,'p');
Serial.println(string1);
string1.setCharAt(11,'y');
Serial.println(string1);
string1.setCharAt(12,'i');
Serial.println(string1);
}
void loop() {
// put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, in the first two cases, we set characters within the length of the string, and they got set at the correct indices (string index starts at 0). When we tried to set a character outside the length of the string, it had no effect on the string. Thus, this experiment also shows that this function cannot be used to extend the length of a string. You should only set characters within the existing length of a string. | [
{
"code": null,
"e": 1220,
"s": 1062,
"text": "In case you don’t want to overwrite a string, but just change a character at a specific position, Arduino provides the setCharAt() function exactly for that."
},
{
"code": null,
"e": 1254,
"s": 1220,
"text": "String1.setCharAt(ind, new_char);"
},
{
"code": null,
"e": 1407,
"s": 1254,
"text": "String 1 is the string to modify. ind is the index where the character needs to be set. new_char is the value of the new character that needs to be set."
},
{
"code": null,
"e": 1472,
"s": 1407,
"text": "This function returns nothing, and modifies the string in place."
},
{
"code": null,
"e": 1532,
"s": 1472,
"text": "The following example illustrates the use of this function."
},
{
"code": null,
"e": 1943,
"s": 1532,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n String string1 = \"Hello World!\";\n Serial.println(string1);\n string1.setCharAt(4,'p');\n Serial.println(string1);\n string1.setCharAt(11,'y');\n Serial.println(string1);\n string1.setCharAt(12,'i');\n Serial.println(string1);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 1986,
"s": 1943,
"text": "The Serial Monitor output is shown below −"
},
{
"code": null,
"e": 2416,
"s": 1986,
"text": "As you can see, in the first two cases, we set characters within the length of the string, and they got set at the correct indices (string index starts at 0). When we tried to set a character outside the length of the string, it had no effect on the string. Thus, this experiment also shows that this function cannot be used to extend the length of a string. You should only set characters within the existing length of a string."
}
] |
Pygame – Surface | 29 Dec, 2021
When using Pygame, surfaces are generally used to represent the appearance of the object and its position on the screen. All the objects, text, images that we create in Pygame are created using surfaces.
Creating surfaces in pygame is quite easy. We just have to pass the height and the width with a tuple to pygame.Surface() method. We can use various methods to format our surface as we want. For example, we can use pygame.draw() to draw shapes, we can use surface.fill() method to fill on the surface. Now, the implementation of these functions. Let’s discuss syntax and parameters.
Syntax: pygame.surface()
It takes 4 arguments a tuple of width and height, flags, depth, mask.
It is used to draw an object, shape.
Syntax: Surface.rect(surface, color, rect)
The code for drawing a rectangle using the pygame.draw.rect() method is below:
Python
# Importing the libraryimport pygameimport time # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # Choosing red color for the rectanglecolor = (255,255,0) # Drawing Rectanglepygame.draw.rect(sample_surface, color, pygame.Rect(30, 30, 60, 60)) # The pygame.display.flip() method is used# to update content on the display screenpygame.display.flip()
Output:
pygame.Surface.fill: It is used for filling color in the surface.
Syntax:pygame.Surface.fill(color, rect=None, special_flags=0)
The code for filling color in the surface using the surface_name.fill() method is:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # Choosing yellow color to fillcolor = (255,255,0) # filling color to the surfacesample_surface.fill(color) # updating the displaypygame.display.flip()
Output:
Although we can draw shapes and fill out colors on the surface, we still need to have a picture on the surface. We can make such a surface easily with pygame.image.load() method. This method takes the image path relative or absolute as an input.
Syntax: pygame.image.load(img)
Code:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display# surfacedisplay_surface.blit(image,(100,100)) # updating the displaypygame.display.flip()
Output:
For a surface to be displayed it needs to blitted on the screen. Blitting can be thought of as copying the pixels of one surface to another. We can blit by using the surface.blit() method which takes a surface that needs to be blit as the first argument and the tuple of coordinates as a second coordinate.
Syntax: pygame.Surface.blit(source, dest, area=None, special_flags=0)
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the first image surfaceimage1 = pygame.image.load('gfg_logo.png') # Creating the second image surfaceimage2 = pygame.image.load('gfg_logo.png') # putting our first image surface on# display surfacedisplay_surface.blit(image1,(0,0)) # putting our second image surface on# display surfacedisplay_surface.blit(image1,(300,300)) # updating the displaypygame.display.flip()
Output:
Now that we have already discussed some surface functions like .blit(), .fill(), etc. Let us discuss some more important functions of pygame screens.
pygame.Surface.convert: It makes a copy of the surface with pixel format changed. The new pixel format can be determined from an existing surface or depth, flags, and masks arguments can be used.
Syntax: pygame.Surface.convert(Surface=None)
Code:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # changing the pixel format of an imagepygame.Surface.convert(sample_surface) # updating the displaypygame.display.flip()
Output:
pygame.Surface.convert_alpha: It creates a new copy of the surface with the desired pixel format. The new surface will be in a format suited for quick blitting to the given format with per-pixel alpha. If no surface is given, the new surface will be optimized for blitting to the current display.
Syntax: pygame.Surface.convert_alpha(Surface)
Code:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # changing the pixel format# of an image including per pixel alphaspygame.Surface.convert_alpha(sample_surface) # updating the displaypygame.display.flip()
Output:
pygame.Surface.copy: It creates a new copy of the surface. The duplicate surface will have the same pixel formats, color palettes, transparency settings, and class as the original.
Syntax: pygame.Surface.copy()
Code:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # creating a copy of sample_surface# and naming it as copied_surfacecopied_surface=pygame.Surface.copy(sample_surface) # updating the displaypygame.display.flip()
Output:
pygame.Surface.set_colorkey: Set the current color key for the surface. When blitting this surface onto a destination, any pixels that have the same color as the colorkey will be transparent.
Syntax: set_colorkey(Color, flags=0)
Code:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surface# making the white colored part# of the surface as transparentpygame.Surface.set_colorkey (image, [255,255,255]) display_surface.blit(image,(100,100)) # updating the displaypygame.display.flip()
Output:
The output of the above code will be geeksforgeeks logo on a black surface with white-colored pixel changed to transparent.
pygame.Surface.get_colorkey: It returns the current color key value for the Surface. If the color key is not set, then None is returned.
Syntax: get_colorkey()
Code:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500)) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surface# making the white colored part of the surface# as transparentpygame.Surface.set_colorkey(image, [255, 255, 255]) # printing the colorkey value for the surfaceprint(pygame.Surface.get_colorkey(image)) display_surface.blit(image, (100, 100)) # updating the displaypygame.display.flip()
Output:
The output of the above code will be a window showing various surfaces as seen in the get_colorkey example as well as the colorkey value will also be printed.
pygame.Surface.set_alpha: The alpha value set for the full surface image. Pass 0 for invisible and 255 for fully opaque.
Syntax: set_alpha(value, flags=0) or set_alpha(None)
Code:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surface# making the alpha value of surface as 100pygame.Surface.set_alpha(image, 100) display_surface.blit(image,(100,100)) # updating the displaypygame.display.flip()
Output:
The output of the above code will be, geeksforgeeks logo, which will be slightly transparent as we have changed its alpha value to 100.
pygame.Surface.get_alpha: It returns the current alpha value for the surface.
Syntax: get_alpha()
Code:
Python
# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surface# making alpha value of image surface to 100pygame.Surface.set_alpha(image, 100) # printing the alpha value of the surfaceprint(pygame.Surface.get_alpha(image)) display_surface.blit(image,(100,100)) # updating the displaypygame.display.flip()
Output:
The output of the above code will be a window showing various surfaces as seen in the set_alpha example as well as the alpha value will also be printed.
akshaysingh98088
simmytarika5
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "When using Pygame, surfaces are generally used to represent the appearance of the object and its position on the screen. All the objects, text, images that we create in Pygame are created using surfaces."
},
{
"code": null,
"e": 615,
"s": 232,
"text": "Creating surfaces in pygame is quite easy. We just have to pass the height and the width with a tuple to pygame.Surface() method. We can use various methods to format our surface as we want. For example, we can use pygame.draw() to draw shapes, we can use surface.fill() method to fill on the surface. Now, the implementation of these functions. Let’s discuss syntax and parameters."
},
{
"code": null,
"e": 640,
"s": 615,
"text": "Syntax: pygame.surface()"
},
{
"code": null,
"e": 710,
"s": 640,
"text": "It takes 4 arguments a tuple of width and height, flags, depth, mask."
},
{
"code": null,
"e": 747,
"s": 710,
"text": "It is used to draw an object, shape."
},
{
"code": null,
"e": 790,
"s": 747,
"text": "Syntax: Surface.rect(surface, color, rect)"
},
{
"code": null,
"e": 869,
"s": 790,
"text": "The code for drawing a rectangle using the pygame.draw.rect() method is below:"
},
{
"code": null,
"e": 876,
"s": 869,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygameimport time # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # Choosing red color for the rectanglecolor = (255,255,0) # Drawing Rectanglepygame.draw.rect(sample_surface, color, pygame.Rect(30, 30, 60, 60)) # The pygame.display.flip() method is used# to update content on the display screenpygame.display.flip()",
"e": 1308,
"s": 876,
"text": null
},
{
"code": null,
"e": 1316,
"s": 1308,
"text": "Output:"
},
{
"code": null,
"e": 1382,
"s": 1316,
"text": "pygame.Surface.fill: It is used for filling color in the surface."
},
{
"code": null,
"e": 1444,
"s": 1382,
"text": "Syntax:pygame.Surface.fill(color, rect=None, special_flags=0)"
},
{
"code": null,
"e": 1527,
"s": 1444,
"text": "The code for filling color in the surface using the surface_name.fill() method is:"
},
{
"code": null,
"e": 1534,
"s": 1527,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # Choosing yellow color to fillcolor = (255,255,0) # filling color to the surfacesample_surface.fill(color) # updating the displaypygame.display.flip()",
"e": 1838,
"s": 1534,
"text": null
},
{
"code": null,
"e": 1846,
"s": 1838,
"text": "Output:"
},
{
"code": null,
"e": 2092,
"s": 1846,
"text": "Although we can draw shapes and fill out colors on the surface, we still need to have a picture on the surface. We can make such a surface easily with pygame.image.load() method. This method takes the image path relative or absolute as an input."
},
{
"code": null,
"e": 2124,
"s": 2092,
"text": "Syntax: pygame.image.load(img) "
},
{
"code": null,
"e": 2130,
"s": 2124,
"text": "Code:"
},
{
"code": null,
"e": 2137,
"s": 2130,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display# surfacedisplay_surface.blit(image,(100,100)) # updating the displaypygame.display.flip()",
"e": 2494,
"s": 2137,
"text": null
},
{
"code": null,
"e": 2502,
"s": 2494,
"text": "Output:"
},
{
"code": null,
"e": 2809,
"s": 2502,
"text": "For a surface to be displayed it needs to blitted on the screen. Blitting can be thought of as copying the pixels of one surface to another. We can blit by using the surface.blit() method which takes a surface that needs to be blit as the first argument and the tuple of coordinates as a second coordinate."
},
{
"code": null,
"e": 2879,
"s": 2809,
"text": "Syntax: pygame.Surface.blit(source, dest, area=None, special_flags=0)"
},
{
"code": null,
"e": 2886,
"s": 2879,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the first image surfaceimage1 = pygame.image.load('gfg_logo.png') # Creating the second image surfaceimage2 = pygame.image.load('gfg_logo.png') # putting our first image surface on# display surfacedisplay_surface.blit(image1,(0,0)) # putting our second image surface on# display surfacedisplay_surface.blit(image1,(300,300)) # updating the displaypygame.display.flip()",
"e": 3423,
"s": 2886,
"text": null
},
{
"code": null,
"e": 3431,
"s": 3423,
"text": "Output:"
},
{
"code": null,
"e": 3581,
"s": 3431,
"text": "Now that we have already discussed some surface functions like .blit(), .fill(), etc. Let us discuss some more important functions of pygame screens."
},
{
"code": null,
"e": 3777,
"s": 3581,
"text": "pygame.Surface.convert: It makes a copy of the surface with pixel format changed. The new pixel format can be determined from an existing surface or depth, flags, and masks arguments can be used."
},
{
"code": null,
"e": 3823,
"s": 3777,
"text": "Syntax: pygame.Surface.convert(Surface=None) "
},
{
"code": null,
"e": 3829,
"s": 3823,
"text": "Code:"
},
{
"code": null,
"e": 3836,
"s": 3829,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # changing the pixel format of an imagepygame.Surface.convert(sample_surface) # updating the displaypygame.display.flip()",
"e": 4108,
"s": 3836,
"text": null
},
{
"code": null,
"e": 4116,
"s": 4108,
"text": "Output:"
},
{
"code": null,
"e": 4413,
"s": 4116,
"text": "pygame.Surface.convert_alpha: It creates a new copy of the surface with the desired pixel format. The new surface will be in a format suited for quick blitting to the given format with per-pixel alpha. If no surface is given, the new surface will be optimized for blitting to the current display."
},
{
"code": null,
"e": 4460,
"s": 4413,
"text": "Syntax: pygame.Surface.convert_alpha(Surface) "
},
{
"code": null,
"e": 4466,
"s": 4460,
"text": "Code:"
},
{
"code": null,
"e": 4473,
"s": 4466,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # changing the pixel format# of an image including per pixel alphaspygame.Surface.convert_alpha(sample_surface) # updating the displaypygame.display.flip()",
"e": 4779,
"s": 4473,
"text": null
},
{
"code": null,
"e": 4787,
"s": 4779,
"text": "Output:"
},
{
"code": null,
"e": 4968,
"s": 4787,
"text": "pygame.Surface.copy: It creates a new copy of the surface. The duplicate surface will have the same pixel formats, color palettes, transparency settings, and class as the original."
},
{
"code": null,
"e": 4998,
"s": 4968,
"text": "Syntax: pygame.Surface.copy()"
},
{
"code": null,
"e": 5004,
"s": 4998,
"text": "Code:"
},
{
"code": null,
"e": 5011,
"s": 5004,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Creating the surfacesample_surface = pygame.display.set_mode((400,300)) # creating a copy of sample_surface# and naming it as copied_surfacecopied_surface=pygame.Surface.copy(sample_surface) # updating the displaypygame.display.flip()",
"e": 5324,
"s": 5011,
"text": null
},
{
"code": null,
"e": 5332,
"s": 5324,
"text": "Output:"
},
{
"code": null,
"e": 5524,
"s": 5332,
"text": "pygame.Surface.set_colorkey: Set the current color key for the surface. When blitting this surface onto a destination, any pixels that have the same color as the colorkey will be transparent."
},
{
"code": null,
"e": 5563,
"s": 5524,
"text": "Syntax: set_colorkey(Color, flags=0) "
},
{
"code": null,
"e": 5570,
"s": 5563,
"text": "Code: "
},
{
"code": null,
"e": 5577,
"s": 5570,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surface# making the white colored part# of the surface as transparentpygame.Surface.set_colorkey (image, [255,255,255]) display_surface.blit(image,(100,100)) # updating the displaypygame.display.flip()",
"e": 6045,
"s": 5577,
"text": null
},
{
"code": null,
"e": 6055,
"s": 6045,
"text": " Output:"
},
{
"code": null,
"e": 6182,
"s": 6057,
"text": "The output of the above code will be geeksforgeeks logo on a black surface with white-colored pixel changed to transparent. "
},
{
"code": null,
"e": 6319,
"s": 6182,
"text": "pygame.Surface.get_colorkey: It returns the current color key value for the Surface. If the color key is not set, then None is returned."
},
{
"code": null,
"e": 6342,
"s": 6319,
"text": "Syntax: get_colorkey()"
},
{
"code": null,
"e": 6349,
"s": 6342,
"text": "Code: "
},
{
"code": null,
"e": 6356,
"s": 6349,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500)) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surface# making the white colored part of the surface# as transparentpygame.Surface.set_colorkey(image, [255, 255, 255]) # printing the colorkey value for the surfaceprint(pygame.Surface.get_colorkey(image)) display_surface.blit(image, (100, 100)) # updating the displaypygame.display.flip()",
"e": 6913,
"s": 6356,
"text": null
},
{
"code": null,
"e": 6921,
"s": 6913,
"text": "Output:"
},
{
"code": null,
"e": 7080,
"s": 6921,
"text": "The output of the above code will be a window showing various surfaces as seen in the get_colorkey example as well as the colorkey value will also be printed."
},
{
"code": null,
"e": 7202,
"s": 7080,
"text": "pygame.Surface.set_alpha: The alpha value set for the full surface image. Pass 0 for invisible and 255 for fully opaque."
},
{
"code": null,
"e": 7255,
"s": 7202,
"text": "Syntax: set_alpha(value, flags=0) or set_alpha(None)"
},
{
"code": null,
"e": 7261,
"s": 7255,
"text": "Code:"
},
{
"code": null,
"e": 7268,
"s": 7261,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surface# making the alpha value of surface as 100pygame.Surface.set_alpha(image, 100) display_surface.blit(image,(100,100)) # updating the displaypygame.display.flip()",
"e": 7702,
"s": 7268,
"text": null
},
{
"code": null,
"e": 7710,
"s": 7702,
"text": "Output:"
},
{
"code": null,
"e": 7848,
"s": 7712,
"text": "The output of the above code will be, geeksforgeeks logo, which will be slightly transparent as we have changed its alpha value to 100."
},
{
"code": null,
"e": 7926,
"s": 7848,
"text": "pygame.Surface.get_alpha: It returns the current alpha value for the surface."
},
{
"code": null,
"e": 7946,
"s": 7926,
"text": "Syntax: get_alpha()"
},
{
"code": null,
"e": 7953,
"s": 7946,
"text": " Code:"
},
{
"code": null,
"e": 7960,
"s": 7953,
"text": "Python"
},
{
"code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # creating the display surfacedisplay_surface = pygame.display.set_mode((500, 500 )) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surface# making alpha value of image surface to 100pygame.Surface.set_alpha(image, 100) # printing the alpha value of the surfaceprint(pygame.Surface.get_alpha(image)) display_surface.blit(image,(100,100)) # updating the displaypygame.display.flip()",
"e": 8476,
"s": 7960,
"text": null
},
{
"code": null,
"e": 8485,
"s": 8476,
"text": "Output: "
},
{
"code": null,
"e": 8638,
"s": 8485,
"text": "The output of the above code will be a window showing various surfaces as seen in the set_alpha example as well as the alpha value will also be printed."
},
{
"code": null,
"e": 8655,
"s": 8638,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 8668,
"s": 8655,
"text": "simmytarika5"
},
{
"code": null,
"e": 8675,
"s": 8668,
"text": "Picked"
},
{
"code": null,
"e": 8689,
"s": 8675,
"text": "Python-PyGame"
},
{
"code": null,
"e": 8696,
"s": 8689,
"text": "Python"
}
] |
CSS | Text Formatting | 02 Jun, 2022
CSS text formatting properties is used to format text and style text.CSS text formatting include following properties:1.Text-color2.Text-alignment3.Text-decoration4.Text-transformation5.Text-indentation6.Letter spacing7.Line height8.Text-direction9.Text-shadow10.Word spacing
1.TEXT COLORText-color property is used to set the color of the text.Text-color can be set by using the name “red”, hex value “#ff0000” or by its RGB value“rgb(255, 0, 0).
Syntax:
body
{
color:color name;
}
Example:
<!DOCTYPE html><html><head><style>h1{color:red;}h2{color:green;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>TEXT FORMATTING</h2></body></html>
OUTPUT:
2.TEXT ALIGNMENTText alignment property is used to set the horizontal alignment of the text.The text can be set to left, right, centered and justified alignment.In justified alignment, line is stretched such that left and right margins are straight.
Syntax:
body
{
text-align:alignment type;
}
Example:
<!DOCTYPE html><html><head><style>h1{color:red;text-align:center;}h2{color:green;text-align:left;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>TEXT FORMATTING</h2></body></html>
OUTPUT:
3.TEXT DECORATIONText decoration is used to add or remove decorations from the text.Text decoration can be underline, overline, line-through or none.
Syntax:
body
{
text-decoration:decoration type;
}
Example:
<!DOCTYPE html><html><head><style>h1{color:red;text-decoration:underline;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>TEXT FORMATTING</h2></body></html>
OUTPUT:
4.TEXT TRANSFORMATIONText transformation property is used to change the case of text, uppercase or lowercase.Text transformation can be uppercase, lowercase or capitalise.Capitalise is used to change the first letter of each word to uppercase.
Syntax:
body
{
text-transform:type;
}
Example:
<!DOCTYPE html><html><head><style>h2{text-transform:lowercase;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>TEXT FORMATTING</h2></body></html>
OUTPUT:
5.TEXT INDENTATIONText indentation property is used to indent the first line of the paragraph.The size can be in px, cm, pt.
Syntax:
body
{
text-indent:size;
}
Example:
<!DOCTYPE html><html><head><style>h2{text-indent:80px;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.<br>Text indentation property is used to indent the first line of the paragraph.</h2></body></html>
OUTPUT:
6.LETTER SPACINGThis property is used to specify the space between the characters of the text.The size can be given in px.
Syntax:
body
{
letter-spacing:size;
}
Example:
<!DOCTYPE html><html><head><style>h2{letter-spacing:4px;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.</h2></body></html>
OUTPUT:
7.LINE HEIGHTThis property is used to set the space between the lines.
Syntax:
body
{
line-height:size;
}
Example:
<!DOCTYPE html><html><head><style>h2{line-height:40px;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.<br>This property is used to set the space between the lines.</h2></body></html>
OUTPUT:
8.TEXT DIRECTIONText direction property is used to set the direction of the text.The direction can be set by using rtl : right to left .Left to right is the default direction of the text.
Syntax:
body
{
direction:rtl;
}
Example:
<!DOCTYPE html><html><head><style>h2{direction: rtl;text-align:center;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2><bdo dir="rtl">This is text formatting properties.</bdo></h2></body></html>
OUTPUT:
9.TEXT SHADOWText shadow property is used to add shadow to the text.You can specify the horizontal size, vertical size and shadow color for the text.
Syntax:
body
{
text-shadow:horizontal size vertical size color name;
}
Example:
<!DOCTYPE html><html><head><style>h1{text-shadow:3px 1px blue;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.</h2></body></html>
OUTPUT:
10.WORD SPACINGWord spacing is used to specify the space between the words of the line.The size can be given in px.
Syntax:
body
{
word-spacing:size;
}
Example:
<!DOCTYPE html><html><head><style>h2{word-spacing:15px;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.</h2></body></html>
OUTPUT:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
ysachin2314
rkbhola5
CSS-Basics
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Node.js fs.readFileSync() Method
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 328,
"s": 52,
"text": "CSS text formatting properties is used to format text and style text.CSS text formatting include following properties:1.Text-color2.Text-alignment3.Text-decoration4.Text-transformation5.Text-indentation6.Letter spacing7.Line height8.Text-direction9.Text-shadow10.Word spacing"
},
{
"code": null,
"e": 500,
"s": 328,
"text": "1.TEXT COLORText-color property is used to set the color of the text.Text-color can be set by using the name “red”, hex value “#ff0000” or by its RGB value“rgb(255, 0, 0)."
},
{
"code": null,
"e": 536,
"s": 500,
"text": "Syntax:\nbody\n{\ncolor:color name;\n}\n"
},
{
"code": null,
"e": 545,
"s": 536,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h1{color:red;}h2{color:green;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>TEXT FORMATTING</h2></body></html>",
"e": 693,
"s": 545,
"text": null
},
{
"code": null,
"e": 704,
"s": 693,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 954,
"s": 704,
"text": "2.TEXT ALIGNMENTText alignment property is used to set the horizontal alignment of the text.The text can be set to left, right, centered and justified alignment.In justified alignment, line is stretched such that left and right margins are straight."
},
{
"code": null,
"e": 999,
"s": 954,
"text": "Syntax:\nbody\n{\ntext-align:alignment type;\n}\n"
},
{
"code": null,
"e": 1008,
"s": 999,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h1{color:red;text-align:center;}h2{color:green;text-align:left;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>TEXT FORMATTING</h2></body></html>",
"e": 1190,
"s": 1008,
"text": null
},
{
"code": null,
"e": 1201,
"s": 1190,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 1351,
"s": 1201,
"text": "3.TEXT DECORATIONText decoration is used to add or remove decorations from the text.Text decoration can be underline, overline, line-through or none."
},
{
"code": null,
"e": 1402,
"s": 1351,
"text": "Syntax:\nbody\n{\ntext-decoration:decoration type;\n}\n"
},
{
"code": null,
"e": 1411,
"s": 1402,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h1{color:red;text-decoration:underline;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>TEXT FORMATTING</h2></body></html>",
"e": 1569,
"s": 1411,
"text": null
},
{
"code": null,
"e": 1580,
"s": 1569,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 1824,
"s": 1580,
"text": "4.TEXT TRANSFORMATIONText transformation property is used to change the case of text, uppercase or lowercase.Text transformation can be uppercase, lowercase or capitalise.Capitalise is used to change the first letter of each word to uppercase."
},
{
"code": null,
"e": 1863,
"s": 1824,
"text": "Syntax:\nbody\n{\ntext-transform:type;\n}\n"
},
{
"code": null,
"e": 1872,
"s": 1863,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h2{text-transform:lowercase;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>TEXT FORMATTING</h2></body></html>",
"e": 2019,
"s": 1872,
"text": null
},
{
"code": null,
"e": 2030,
"s": 2019,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 2155,
"s": 2030,
"text": "5.TEXT INDENTATIONText indentation property is used to indent the first line of the paragraph.The size can be in px, cm, pt."
},
{
"code": null,
"e": 2191,
"s": 2155,
"text": "Syntax:\nbody\n{\ntext-indent:size;\n}\n"
},
{
"code": null,
"e": 2200,
"s": 2191,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h2{text-indent:80px;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.<br>Text indentation property is used to indent the first line of the paragraph.</h2></body></html>",
"e": 2439,
"s": 2200,
"text": null
},
{
"code": null,
"e": 2450,
"s": 2439,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 2573,
"s": 2450,
"text": "6.LETTER SPACINGThis property is used to specify the space between the characters of the text.The size can be given in px."
},
{
"code": null,
"e": 2612,
"s": 2573,
"text": "Syntax:\nbody\n{\nletter-spacing:size;\n}\n"
},
{
"code": null,
"e": 2621,
"s": 2612,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h2{letter-spacing:4px;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.</h2></body></html>",
"e": 2782,
"s": 2621,
"text": null
},
{
"code": null,
"e": 2793,
"s": 2782,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 2864,
"s": 2793,
"text": "7.LINE HEIGHTThis property is used to set the space between the lines."
},
{
"code": null,
"e": 2900,
"s": 2864,
"text": "Syntax:\nbody\n{\nline-height:size;\n}\n"
},
{
"code": null,
"e": 2909,
"s": 2900,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h2{line-height:40px;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.<br>This property is used to set the space between the lines.</h2></body></html>",
"e": 3129,
"s": 2909,
"text": null
},
{
"code": null,
"e": 3140,
"s": 3129,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 3328,
"s": 3140,
"text": "8.TEXT DIRECTIONText direction property is used to set the direction of the text.The direction can be set by using rtl : right to left .Left to right is the default direction of the text."
},
{
"code": null,
"e": 3361,
"s": 3328,
"text": "Syntax:\nbody\n{\ndirection:rtl;\n}\n"
},
{
"code": null,
"e": 3370,
"s": 3361,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h2{direction: rtl;text-align:center;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2><bdo dir=\"rtl\">This is text formatting properties.</bdo></h2></body></html>",
"e": 3566,
"s": 3370,
"text": null
},
{
"code": null,
"e": 3577,
"s": 3566,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 3727,
"s": 3577,
"text": "9.TEXT SHADOWText shadow property is used to add shadow to the text.You can specify the horizontal size, vertical size and shadow color for the text."
},
{
"code": null,
"e": 3799,
"s": 3727,
"text": "Syntax:\nbody\n{\ntext-shadow:horizontal size vertical size color name;\n}\n"
},
{
"code": null,
"e": 3808,
"s": 3799,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h1{text-shadow:3px 1px blue;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.</h2></body></html>",
"e": 3975,
"s": 3808,
"text": null
},
{
"code": null,
"e": 3986,
"s": 3975,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 4102,
"s": 3986,
"text": "10.WORD SPACINGWord spacing is used to specify the space between the words of the line.The size can be given in px."
},
{
"code": null,
"e": 4139,
"s": 4102,
"text": "Syntax:\nbody\n{\nword-spacing:size;\n}\n"
},
{
"code": null,
"e": 4148,
"s": 4139,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head><style>h2{word-spacing:15px;}</style></head><body><h1>GEEKS FOR GEEKS</h1><h2>This is text formatting properties.</h2></body></html>",
"e": 4308,
"s": 4148,
"text": null
},
{
"code": null,
"e": 4319,
"s": 4308,
"text": "\nOUTPUT:\n\n"
},
{
"code": null,
"e": 4338,
"s": 4319,
"text": "Supported Browser:"
},
{
"code": null,
"e": 4352,
"s": 4338,
"text": "Google Chrome"
},
{
"code": null,
"e": 4370,
"s": 4352,
"text": "Internet Explorer"
},
{
"code": null,
"e": 4378,
"s": 4370,
"text": "Firefox"
},
{
"code": null,
"e": 4384,
"s": 4378,
"text": "Opera"
},
{
"code": null,
"e": 4391,
"s": 4384,
"text": "Safari"
},
{
"code": null,
"e": 4577,
"s": 4391,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 4589,
"s": 4577,
"text": "ysachin2314"
},
{
"code": null,
"e": 4598,
"s": 4589,
"text": "rkbhola5"
},
{
"code": null,
"e": 4609,
"s": 4598,
"text": "CSS-Basics"
},
{
"code": null,
"e": 4613,
"s": 4609,
"text": "CSS"
},
{
"code": null,
"e": 4630,
"s": 4613,
"text": "Web Technologies"
},
{
"code": null,
"e": 4728,
"s": 4630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4776,
"s": 4728,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4838,
"s": 4776,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4888,
"s": 4838,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4925,
"s": 4888,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 4964,
"s": 4925,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4997,
"s": 4964,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5059,
"s": 4997,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5109,
"s": 5059,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5142,
"s": 5109,
"text": "Node.js fs.readFileSync() Method"
}
] |
How to set character encoding for document in HTML5 ? | 01 Apr, 2021
Character encoding is a method of defining a mapping between bytes and text. To display an HTML document correctly, we must choose a proper character encoding.
The different types of character encoding include:
ASCII Character Set: It is the first ever character encoding standard. The major disadvantage with ASCII is that it contained only a limited range of characters (128 characters).
ANSI Character Set: This standard was an extended version of standard ASCII character set. It supports 256 characters.
ISO-8859-1 Character Set: It is the default character encoding in HTML 2.0. It is also an extension of ASCII standard with International characters. This used full bytes (8-bits) to show characters.
UTF-8 Character Set: This standard covers almost all of the characters and symbols in the world. The limitations of ANSI and ISO-8859-1 were satisfied by the UTF-8 Character Set. The default character encoding for HTML5 is UTF-8.
The HTML5 specification encourages developers to use the UTF-8 character set.
A character can be 1-4 bytes long in the UTF-8 Encoding Standard. This is also the most preferred encoding for email and web pages.
Character encoding can be specified in the meta tag in HTML.
The meta tag is used for specifying metadata about the webpage and will not be displayed in the web pages.
The meta tag helps search engines to understand what a web page is about.
The meta tag should be placed with the head tag in HTML.
Syntax:
1. For HTML4
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
2. For HTML5
The default character encoding for HTML5 is UTF-8, but you can still specify this to be extra cautious.
<meta charset="UTF-8">
Example:
HTML
<!DOCTYPE html><html> <head> <!-- NOTE: <meta charset="UTF-8"> is also applicable. --> <meta charset="utf-8"> <title>Page Title</title></head> <body> <h2>Welcome To GFG</h2> <p> Default code has been loaded into the Editor. </p></body> </html>
HTML-Questions
HTML-Tags
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Make a div horizontally scrollable using CSS
DOM (Document Object Model)
How to get values from html input array using JavaScript ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How do you run JavaScript script through the Terminal?
Node.js fs.readFileSync() Method
How to set space between the flexbox ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "Character encoding is a method of defining a mapping between bytes and text. To display an HTML document correctly, we must choose a proper character encoding. "
},
{
"code": null,
"e": 241,
"s": 190,
"text": "The different types of character encoding include:"
},
{
"code": null,
"e": 420,
"s": 241,
"text": "ASCII Character Set: It is the first ever character encoding standard. The major disadvantage with ASCII is that it contained only a limited range of characters (128 characters)."
},
{
"code": null,
"e": 539,
"s": 420,
"text": "ANSI Character Set: This standard was an extended version of standard ASCII character set. It supports 256 characters."
},
{
"code": null,
"e": 738,
"s": 539,
"text": "ISO-8859-1 Character Set: It is the default character encoding in HTML 2.0. It is also an extension of ASCII standard with International characters. This used full bytes (8-bits) to show characters."
},
{
"code": null,
"e": 968,
"s": 738,
"text": "UTF-8 Character Set: This standard covers almost all of the characters and symbols in the world. The limitations of ANSI and ISO-8859-1 were satisfied by the UTF-8 Character Set. The default character encoding for HTML5 is UTF-8."
},
{
"code": null,
"e": 1046,
"s": 968,
"text": "The HTML5 specification encourages developers to use the UTF-8 character set."
},
{
"code": null,
"e": 1178,
"s": 1046,
"text": "A character can be 1-4 bytes long in the UTF-8 Encoding Standard. This is also the most preferred encoding for email and web pages."
},
{
"code": null,
"e": 1239,
"s": 1178,
"text": "Character encoding can be specified in the meta tag in HTML."
},
{
"code": null,
"e": 1346,
"s": 1239,
"text": "The meta tag is used for specifying metadata about the webpage and will not be displayed in the web pages."
},
{
"code": null,
"e": 1420,
"s": 1346,
"text": "The meta tag helps search engines to understand what a web page is about."
},
{
"code": null,
"e": 1477,
"s": 1420,
"text": "The meta tag should be placed with the head tag in HTML."
},
{
"code": null,
"e": 1485,
"s": 1477,
"text": "Syntax:"
},
{
"code": null,
"e": 1498,
"s": 1485,
"text": "1. For HTML4"
},
{
"code": null,
"e": 1566,
"s": 1498,
"text": "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"> "
},
{
"code": null,
"e": 1579,
"s": 1566,
"text": "2. For HTML5"
},
{
"code": null,
"e": 1684,
"s": 1579,
"text": "The default character encoding for HTML5 is UTF-8, but you can still specify this to be extra cautious. "
},
{
"code": null,
"e": 1709,
"s": 1684,
"text": "<meta charset=\"UTF-8\"> "
},
{
"code": null,
"e": 1718,
"s": 1709,
"text": "Example:"
},
{
"code": null,
"e": 1723,
"s": 1718,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- NOTE: <meta charset=\"UTF-8\"> is also applicable. --> <meta charset=\"utf-8\"> <title>Page Title</title></head> <body> <h2>Welcome To GFG</h2> <p> Default code has been loaded into the Editor. </p></body> </html>",
"e": 2013,
"s": 1723,
"text": null
},
{
"code": null,
"e": 2028,
"s": 2013,
"text": "HTML-Questions"
},
{
"code": null,
"e": 2038,
"s": 2028,
"text": "HTML-Tags"
},
{
"code": null,
"e": 2044,
"s": 2038,
"text": "HTML5"
},
{
"code": null,
"e": 2051,
"s": 2044,
"text": "Picked"
},
{
"code": null,
"e": 2056,
"s": 2051,
"text": "HTML"
},
{
"code": null,
"e": 2073,
"s": 2056,
"text": "Web Technologies"
},
{
"code": null,
"e": 2078,
"s": 2073,
"text": "HTML"
},
{
"code": null,
"e": 2176,
"s": 2078,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2200,
"s": 2176,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2239,
"s": 2200,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2284,
"s": 2239,
"text": "Make a div horizontally scrollable using CSS"
},
{
"code": null,
"e": 2312,
"s": 2284,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 2371,
"s": 2312,
"text": "How to get values from html input array using JavaScript ?"
},
{
"code": null,
"e": 2404,
"s": 2371,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2462,
"s": 2404,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 2517,
"s": 2462,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 2550,
"s": 2517,
"text": "Node.js fs.readFileSync() Method"
}
] |
How to merge the first index of an array with the first index of second array? | 08 Jun, 2020
The task is to merge the first index of an array with the first index of another array. Suppose, an array is array1 = {a, b, c} and another array is array2 = {c, d, e} if we perform the task on these arrays then the output will be
result array
{
[0]=> array(2)
{
[0]=> string(1) "a"
[1]=> string(1) "c"
}
[1]=> array(2)
{
[0]=> string(1) "b"
[1]=> string(1) "d"
}
[2]=> array(2)
{
[0]=> string(1) "c"
[1]=> string(1) "e"
}
}
Most people think array_merge() function can resolve the above requirement the following code shows how this isn’t the way to achieve it:
Example 1: Using the array_merge() function will give you the desired result.
php
<?php $array1=array("a","b","c"); $array2=array("c","d","e"); $result=array_merge($array1,$array2); var_dump($result);?>
Output:
array(6) { [0]=> string(1) "a"
[1]=> string(1) "b"
[2]=> string(1) "c"
[3]=> string(1) "c"
[4]=> string(1) "d"
[5]=> string(1) "e"
}
In order to combine the two arrays by indices, we have to loop through them and merge as we go. Such that the first index of the first and second array together form the first index of the resultant array.
Example 2: Program to merge 2 simple arrays
php
<?php $array1=array("a","b","c"); $array2=array("c","d","e"); $result=array(); foreach($array1 as $key=>$value ){ $val=$array2[$key]; $result[$key]=array($value,$val); } var_dump($result);?>
Output:
array(3) {
[0]=> array(2)
{
[0]=> string(1) "a"
[1]=> string(1) "c"
}
[1]=> array(2)
{
[0]=> string(1) "b"
[1]=> string(1) "d"
}
[2]=> array(2)
{
[0]=> string(1) "c"
[1]=> string(1) "e"
}
}
Example 3: Program to merge 2 complex arrays
php
<?php $array1=array(array("a","b"),array("c","d")); $array2=array(array("z","y"),array("x","w")); $result=array(); foreach($array1 as $key=>$value ){ $val=$array2[$key]; $result[$key]=array($value,$val); } var_dump($result);?>
Output:
array(2) {
[0]=> array(2)
{
[0]=> array(2)
{
[0]=> string(1) "a"
[1]=> string(1) "b"
}
[1]=> array(2)
{
[0]=> string(1) "z"
[1]=> string(1) "y"
}
}
[1]=> array(2)
{
[0]=> array(2)
{
[0]=> string(1) "c"
[1]=> string(1) "d"
}
[1]=> array(2)
{
[0]=> string(1) "x"
[1]=> string(1) "w"
}
}
}
PHP-array
Picked
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 260,
"s": 28,
"text": "The task is to merge the first index of an array with the first index of another array. Suppose, an array is array1 = {a, b, c} and another array is array2 = {c, d, e} if we perform the task on these arrays then the output will be "
},
{
"code": null,
"e": 603,
"s": 260,
"text": "result array\n { \n [0]=> array(2) \n { \n [0]=> string(1) \"a\" \n [1]=> string(1) \"c\" \n } \n [1]=> array(2) \n { \n [0]=> string(1) \"b\" \n [1]=> string(1) \"d\" \n } \n [2]=> array(2) \n { \n [0]=> string(1) \"c\" \n [1]=> string(1) \"e\" \n } \n }\n"
},
{
"code": null,
"e": 742,
"s": 603,
"text": "Most people think array_merge() function can resolve the above requirement the following code shows how this isn’t the way to achieve it: "
},
{
"code": null,
"e": 820,
"s": 742,
"text": "Example 1: Using the array_merge() function will give you the desired result."
},
{
"code": null,
"e": 824,
"s": 820,
"text": "php"
},
{
"code": "<?php $array1=array(\"a\",\"b\",\"c\"); $array2=array(\"c\",\"d\",\"e\"); $result=array_merge($array1,$array2); var_dump($result);?>",
"e": 957,
"s": 824,
"text": null
},
{
"code": null,
"e": 966,
"s": 957,
"text": "Output: "
},
{
"code": null,
"e": 1171,
"s": 966,
"text": "array(6) { [0]=> string(1) \"a\" \n [1]=> string(1) \"b\" \n [2]=> string(1) \"c\" \n [3]=> string(1) \"c\" \n [4]=> string(1) \"d\" \n [5]=> string(1) \"e\" \n }\n\n"
},
{
"code": null,
"e": 1377,
"s": 1171,
"text": "In order to combine the two arrays by indices, we have to loop through them and merge as we go. Such that the first index of the first and second array together form the first index of the resultant array."
},
{
"code": null,
"e": 1422,
"s": 1377,
"text": "Example 2: Program to merge 2 simple arrays "
},
{
"code": null,
"e": 1426,
"s": 1422,
"text": "php"
},
{
"code": "<?php $array1=array(\"a\",\"b\",\"c\"); $array2=array(\"c\",\"d\",\"e\"); $result=array(); foreach($array1 as $key=>$value ){ $val=$array2[$key]; $result[$key]=array($value,$val); } var_dump($result);?>",
"e": 1647,
"s": 1426,
"text": null
},
{
"code": null,
"e": 1656,
"s": 1647,
"text": "Output: "
},
{
"code": null,
"e": 1992,
"s": 1656,
"text": "array(3) { \n [0]=> array(2) \n { \n [0]=> string(1) \"a\" \n [1]=> string(1) \"c\" \n } \n [1]=> array(2) \n { \n [0]=> string(1) \"b\" \n [1]=> string(1) \"d\" \n } \n [2]=> array(2) \n { \n [0]=> string(1) \"c\" \n [1]=> string(1) \"e\" \n } \n }\n\n"
},
{
"code": null,
"e": 2038,
"s": 1992,
"text": "Example 3: Program to merge 2 complex arrays "
},
{
"code": null,
"e": 2042,
"s": 2038,
"text": "php"
},
{
"code": "<?php $array1=array(array(\"a\",\"b\"),array(\"c\",\"d\")); $array2=array(array(\"z\",\"y\"),array(\"x\",\"w\")); $result=array(); foreach($array1 as $key=>$value ){ $val=$array2[$key]; $result[$key]=array($value,$val); } var_dump($result);?>",
"e": 2299,
"s": 2042,
"text": null
},
{
"code": null,
"e": 2308,
"s": 2299,
"text": "Output: "
},
{
"code": null,
"e": 2891,
"s": 2308,
"text": "array(2) { \n [0]=> array(2) \n { \n [0]=> array(2) \n { \n [0]=> string(1) \"a\" \n [1]=> string(1) \"b\" \n } \n [1]=> array(2) \n { \n [0]=> string(1) \"z\" \n [1]=> string(1) \"y\" \n } \n } \n [1]=> array(2) \n {\n [0]=> array(2) \n { \n [0]=> string(1) \"c\" \n [1]=> string(1) \"d\" \n } \n [1]=> array(2) \n { \n [0]=> string(1) \"x\" \n [1]=> string(1) \"w\" \n } \n } \n }\n\n"
},
{
"code": null,
"e": 2903,
"s": 2893,
"text": "PHP-array"
},
{
"code": null,
"e": 2910,
"s": 2903,
"text": "Picked"
},
{
"code": null,
"e": 2914,
"s": 2910,
"text": "PHP"
},
{
"code": null,
"e": 2931,
"s": 2914,
"text": "Web Technologies"
},
{
"code": null,
"e": 2958,
"s": 2931,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2962,
"s": 2958,
"text": "PHP"
},
{
"code": null,
"e": 3060,
"s": 2962,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3142,
"s": 3060,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 3187,
"s": 3142,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 3238,
"s": 3187,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 3268,
"s": 3238,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 3291,
"s": 3268,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 3353,
"s": 3291,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3386,
"s": 3353,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3447,
"s": 3386,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3497,
"s": 3447,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
CSS Child vs Descendant selectors | 10 Jun, 2022
Child Selector: Child Selector is used to match all the elements which are children of a specified element. It gives the relation between two elements. The element > element selector selects those elements which are the children of the specific parent. The operand on the left side of > is the parent and the operand on the right is the children element.
Syntax:
element > element {
// CSS Property
}
Example: Match all <p> element that are child of only <div> element.
html
<!DOCTYPE html><html> <head> <title> CSS child Selector </title> <style> div > p { color:white; background: green; padding:2px; } </style> </head> <body style = "text-align: center;"> <div> <h2 style = "color:green;"> CSS Child Selector </h2> <p> A computer science portal for geeks. </p> </div> <p>Geeks Classes is a quick course to cover algorithms questions.</p> <p>This paragraph will not be styled.</p> </body></html>
Output:
Descendant selector: Descendant selector is used to select all the elements which are child of the element (not a specific element). It selects the elements inside the elements i.e it combines two selectors such that elements matched by the second selector are selected if they have an ancestor element matching the first selector.
Syntax:
element element {
// CSS Property
}
Example: It selects all the <h2> elements which are child element of <div>.
html
<!DOCTYPE html><html> <head> <title> CSS Descendant Selector </title> <style> div h2 { font-size:26px; } </style></head> <body style = "text-align:center;"> <div> <h2 style = "color:green;" > GeeksForGeeks </h2> <div> <h2>GeeksForGeeks</h2> </div> </div> <p> GeeksforGeeks in green color is example of child Selector <br>other GeekforGeeks is example of descendant Selector </p></body> </html>
Output:
user282
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
CSS | :not(:last-child):after Selector
Create a Responsive Navbar using ReactJS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 409,
"s": 53,
"text": "Child Selector: Child Selector is used to match all the elements which are children of a specified element. It gives the relation between two elements. The element > element selector selects those elements which are the children of the specific parent. The operand on the left side of > is the parent and the operand on the right is the children element. "
},
{
"code": null,
"e": 418,
"s": 409,
"text": "Syntax: "
},
{
"code": null,
"e": 460,
"s": 418,
"text": "element > element {\n // CSS Property\n}"
},
{
"code": null,
"e": 530,
"s": 460,
"text": "Example: Match all <p> element that are child of only <div> element. "
},
{
"code": null,
"e": 535,
"s": 530,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS child Selector </title> <style> div > p { color:white; background: green; padding:2px; } </style> </head> <body style = \"text-align: center;\"> <div> <h2 style = \"color:green;\"> CSS Child Selector </h2> <p> A computer science portal for geeks. </p> </div> <p>Geeks Classes is a quick course to cover algorithms questions.</p> <p>This paragraph will not be styled.</p> </body></html>",
"e": 1221,
"s": 535,
"text": null
},
{
"code": null,
"e": 1229,
"s": 1221,
"text": "Output:"
},
{
"code": null,
"e": 1565,
"s": 1232,
"text": "Descendant selector: Descendant selector is used to select all the elements which are child of the element (not a specific element). It selects the elements inside the elements i.e it combines two selectors such that elements matched by the second selector are selected if they have an ancestor element matching the first selector. "
},
{
"code": null,
"e": 1574,
"s": 1565,
"text": "Syntax: "
},
{
"code": null,
"e": 1614,
"s": 1574,
"text": "element element {\n // CSS Property\n}"
},
{
"code": null,
"e": 1691,
"s": 1614,
"text": "Example: It selects all the <h2> elements which are child element of <div>. "
},
{
"code": null,
"e": 1696,
"s": 1691,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS Descendant Selector </title> <style> div h2 { font-size:26px; } </style></head> <body style = \"text-align:center;\"> <div> <h2 style = \"color:green;\" > GeeksForGeeks </h2> <div> <h2>GeeksForGeeks</h2> </div> </div> <p> GeeksforGeeks in green color is example of child Selector <br>other GeekforGeeks is example of descendant Selector </p></body> </html> ",
"e": 2262,
"s": 1696,
"text": null
},
{
"code": null,
"e": 2270,
"s": 2262,
"text": "Output:"
},
{
"code": null,
"e": 2280,
"s": 2272,
"text": "user282"
},
{
"code": null,
"e": 2289,
"s": 2280,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2296,
"s": 2289,
"text": "Picked"
},
{
"code": null,
"e": 2300,
"s": 2296,
"text": "CSS"
},
{
"code": null,
"e": 2305,
"s": 2300,
"text": "HTML"
},
{
"code": null,
"e": 2322,
"s": 2305,
"text": "Web Technologies"
},
{
"code": null,
"e": 2327,
"s": 2322,
"text": "HTML"
},
{
"code": null,
"e": 2425,
"s": 2327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2464,
"s": 2425,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2503,
"s": 2464,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2542,
"s": 2503,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2581,
"s": 2542,
"text": "CSS | :not(:last-child):after Selector"
},
{
"code": null,
"e": 2622,
"s": 2581,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 2646,
"s": 2622,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2699,
"s": 2646,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2759,
"s": 2699,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2820,
"s": 2759,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Node.js Chalk Module | 07 Oct, 2021
Chalk module in Node.js is the third-party module that is used for styling the format of text and allows us to create our own themes in the node.js project.
Advantages of Chalk Module:
It helps to customize the color of the output of the command-line outputIt helps to improve the quality of the output by providing several color options like for warning message red color and many more
It helps to customize the color of the output of the command-line output
It helps to improve the quality of the output by providing several color options like for warning message red color and many more
Chalk Module: https://www.npmjs.com/package/chalk
Installing Module:
npm install chalk
Project Structure:
Example 1:
index.js
// Importing moduleconst chalk=require("chalk"); // Printing the textconsole.log(chalk.red("aayush"))console.log(chalk.red.underline("aayush"))console.log(chalk.red.underline.bold("GFG"))
Run index.js file using below command:
node index.js
Output: This will be the console output.
Example 2: Defining own themes.
index.js
// Importing chalk moduleconst chalk=require("chalk"); // Creating themeconst warning=chalk.red; // Printing theme textconsole.log(warning("Restricted Zone"));const welcome=chalk.greenconsole.log(welcome("GFG"))
Run index.js file using below command:
node index.js
Output: This will be the console output.
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 185,
"s": 28,
"text": "Chalk module in Node.js is the third-party module that is used for styling the format of text and allows us to create our own themes in the node.js project."
},
{
"code": null,
"e": 213,
"s": 185,
"text": "Advantages of Chalk Module:"
},
{
"code": null,
"e": 415,
"s": 213,
"text": "It helps to customize the color of the output of the command-line outputIt helps to improve the quality of the output by providing several color options like for warning message red color and many more"
},
{
"code": null,
"e": 488,
"s": 415,
"text": "It helps to customize the color of the output of the command-line output"
},
{
"code": null,
"e": 618,
"s": 488,
"text": "It helps to improve the quality of the output by providing several color options like for warning message red color and many more"
},
{
"code": null,
"e": 668,
"s": 618,
"text": "Chalk Module: https://www.npmjs.com/package/chalk"
},
{
"code": null,
"e": 687,
"s": 668,
"text": "Installing Module:"
},
{
"code": null,
"e": 705,
"s": 687,
"text": "npm install chalk"
},
{
"code": null,
"e": 724,
"s": 705,
"text": "Project Structure:"
},
{
"code": null,
"e": 735,
"s": 724,
"text": "Example 1:"
},
{
"code": null,
"e": 744,
"s": 735,
"text": "index.js"
},
{
"code": "// Importing moduleconst chalk=require(\"chalk\"); // Printing the textconsole.log(chalk.red(\"aayush\"))console.log(chalk.red.underline(\"aayush\"))console.log(chalk.red.underline.bold(\"GFG\"))",
"e": 933,
"s": 744,
"text": null
},
{
"code": null,
"e": 972,
"s": 933,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 986,
"s": 972,
"text": "node index.js"
},
{
"code": null,
"e": 1027,
"s": 986,
"text": "Output: This will be the console output."
},
{
"code": null,
"e": 1059,
"s": 1027,
"text": "Example 2: Defining own themes."
},
{
"code": null,
"e": 1068,
"s": 1059,
"text": "index.js"
},
{
"code": "// Importing chalk moduleconst chalk=require(\"chalk\"); // Creating themeconst warning=chalk.red; // Printing theme textconsole.log(warning(\"Restricted Zone\"));const welcome=chalk.greenconsole.log(welcome(\"GFG\"))",
"e": 1282,
"s": 1068,
"text": null
},
{
"code": null,
"e": 1321,
"s": 1282,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 1335,
"s": 1321,
"text": "node index.js"
},
{
"code": null,
"e": 1376,
"s": 1335,
"text": "Output: This will be the console output."
},
{
"code": null,
"e": 1383,
"s": 1376,
"text": "Picked"
},
{
"code": null,
"e": 1407,
"s": 1383,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1415,
"s": 1407,
"text": "Node.js"
},
{
"code": null,
"e": 1434,
"s": 1415,
"text": "Technical Scripter"
}
] |
How to convert string to char array in C++? | This is a C++ program to convert string to char array in C++. This can be done in multiple different ways
Begin
Assign a string value to a char array variable m.
Define and string variable str
For i = 0 to sizeof(m)
Copy character by character from m to str.
Print character by character from str.
End
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char m[]="Tutorialspoint";
string str;
int i;
for(i=0;i<sizeof(m);i++)
{
str[i]=m[i];
cout<<str[i];
}
return 0;
}
We can simply call strcpy() function to copy the string to char array.
Begin
Assign value to string s.
Copying the contents of the string to char array using strcpy() .
End
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string str = "Tutorialspoint";
char c[str.size() + 1];
strcpy(c, str.c_str());
cout << c << '\n';
return 0;
}
Tutorialspoint
We can avoid using strcpy() which is basically used in c by std::string::copy instead.
Begin
Assign value to string s.
Copying the contents of the string to char array using copy().
End
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Tutorialspoint";
char c[str.size() + 1];
str.copy(c, str.size() + 1);
c[str.size()] = '\0';
cout << c << '\n';
return 0;
}
Tutorialspoint | [
{
"code": null,
"e": 1293,
"s": 1187,
"text": "This is a C++ program to convert string to char array in C++. This can be done in multiple different ways"
},
{
"code": null,
"e": 1510,
"s": 1293,
"text": "Begin\n Assign a string value to a char array variable m.\n Define and string variable str\n For i = 0 to sizeof(m)\n Copy character by character from m to str.\n Print character by character from str.\nEnd"
},
{
"code": null,
"e": 1729,
"s": 1510,
"text": "#include<iostream>\n#include<string.h>\nusing namespace std;\nint main()\n{\n char m[]=\"Tutorialspoint\";\n string str;\n int i;\n for(i=0;i<sizeof(m);i++)\n {\n str[i]=m[i];\n cout<<str[i];\n }\n return 0;\n}"
},
{
"code": null,
"e": 1800,
"s": 1729,
"text": "We can simply call strcpy() function to copy the string to char array."
},
{
"code": null,
"e": 1908,
"s": 1800,
"text": "Begin\n Assign value to string s.\n Copying the contents of the string to char array using strcpy() .\nEnd"
},
{
"code": null,
"e": 2124,
"s": 1908,
"text": "#include <iostream>\n#include <string>\n#include <cstring>\nusing namespace std;\nint main()\n{\n string str = \"Tutorialspoint\";\n char c[str.size() + 1];\n strcpy(c, str.c_str());\n cout << c << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 2139,
"s": 2124,
"text": "Tutorialspoint"
},
{
"code": null,
"e": 2226,
"s": 2139,
"text": "We can avoid using strcpy() which is basically used in c by std::string::copy instead."
},
{
"code": null,
"e": 2331,
"s": 2226,
"text": "Begin\n Assign value to string s.\n Copying the contents of the string to char array using copy().\nEnd"
},
{
"code": null,
"e": 2558,
"s": 2331,
"text": "#include <iostream>\n#include <string>\nusing namespace std;\nint main()\n{\n string str = \"Tutorialspoint\";\n char c[str.size() + 1];\n str.copy(c, str.size() + 1);\n c[str.size()] = '\\0';\n cout << c << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 2573,
"s": 2558,
"text": "Tutorialspoint"
}
] |
Interactive visualization of data using Bokeh | 28 Mar, 2022
Bokeh is a Python library for creating interactive data visualizations in a web browser. It offers human-readable and fast presentation of data in an visually pleasing manner. If you’ve worked with visualization in Python before, it’s likely that you have used matplotlib. But Bokeh differs from matplotlib.
To install Bokeh type the below command in the terminal.
pip install bokeh
The intended uses of matplotlib and Bokeh are quite different. Matplotlib creates static graphics that are useful for quick and simple visualizations, or for creating publication-quality images. Bokeh creates visualizations for display on the web (whether locally or embedded in a webpage) and most importantly, the visualizations are meant to be highly interactive. Matplotlib does not offer either of these features.
If would you like to visually interact with your data or you would like to distribute interactive visual data to a web audience, Bokeh is the library for you! If your main interest is producing finalized visualizations for publication, matplotlib may be better, although Bokeh does offer a way to create static graphics.
For this example we will be using one of the built-in dataset, i.e flowers data set. we can use circle() method to plot each data points as a circle on graph, we can also specify custom attributes like:
first two elements has to be data on x-axis and y-axis respectively.
color: to assign color dynamically as shown.
fill_alpha: to assign opacity for circles.
size: to assign size of each circle.
Example:
Python
from bokeh.plotting import figure, output_file, showfrom bokeh.sampledata.iris import flowers # assign custom colors to represent each# class of data in a dictionary formatcolormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] # title for the graphp = figure(title="Iris Morphology") # label on x-axisp.xaxis.axis_label = 'Petal Length' # label on y-axisp.yaxis.axis_label = 'Petal Width' # plot each datapoint as a circle# with custom attributes.p.circle(flowers["petal_length"], flowers["petal_width"], color=colors, fill_alpha=0.3, size=15) # you can save the output as an# interactive html fileoutput_file("iris1.html", title="iris.py example") # display the generated plot of graphshow(p)
Output:
In the above example, output_file() function is used to save the output generated as an html file as bokeh uses web format to provide interactive display. Finally show() function is used to display the generated output.
Note:
Red color = Setosa, Green = Versicolor, Blue = Virginica
On top right of every visualization, there are interactive functions provided by bokeh. it allows 1. Pan across plot, 2. Zoom using box selection, 3. Zoom using scroll wheel, 4. Save, 5. Reset, 6. Help
For this example we will be using custom created data set using list in code itself, i.e fruits data set. output_file() function is used to save the output generated as an html file as bokeh uses web format. we can use ColumnDataSource() function to map the custom data set (two lists) created with each other as a dictionary format. figure() function is used to initialize the graph figure so that data can be plotted on it with various parameters such as:
x_range: defines data on x-axis.
plot_width, plot_height: defines width and height of graph.
toolbar_location: defines location of toolbar.
title: defines title of graph.
Here we are using simple vertical bars to represent data hence we use vbar() method and to assign various attributes to vertical bars we pass in different parameters inside it, like:
x: data in x-axis direction
top: data in y-axis direction
width: defines width of each bar
source: source of data
legend_field: display list of classes present in data
line_color: defines color for lines in graph
fill_color: define different colors for data classes
There are many more parameters that can be passed here. Some other properties that can be used are:
y_range.start: used to define lower limit of data on y-axis.
y_range.end: used to define upper most limit of data on y-axis.
legend.orientation: defines orientation of legend bar.
legend.location: defines location of legend bar.
Finally show() function is used to display the generated output.
Example:
Python
from bokeh.io import output_file, showfrom bokeh.models import ColumnDataSourcefrom bokeh.palettes import Spectral10from bokeh.plotting import figurefrom bokeh.transform import factor_cmap output_file("fruits_bar_chart.html") #output save file name # creating custom datafruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries', 'bananas','berries','pineapples','litchi']counts = [51, 34, 4, 28, 119, 79, 15, 68, 26, 88] # mapping counts with classes as a dictionarysource = ColumnDataSource(data=dict(fruits=fruits, counts=counts)) # initializing the figurep = figure(x_range=fruits, plot_width=800, plot_height=350, toolbar_location=None, title="Fruit Counts") # assigning various attributes to plotp.vbar(x='fruits', top='counts', width=1, source=source, legend_field="fruits", line_color='white', fill_color=factor_cmap('fruits', palette=Spectral10, factors=fruits)) p.xgrid.grid_line_color = Nonep.y_range.start = 0p.y_range.end = 150p.legend.orientation = "horizontal"p.legend.location = "top_center" # display outputshow(p)
Output:
Note: This is a static graph which is also provided by bokeh similar to matplotlib.
rkbhola5
Python-Bokeh
python-modules
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 336,
"s": 28,
"text": "Bokeh is a Python library for creating interactive data visualizations in a web browser. It offers human-readable and fast presentation of data in an visually pleasing manner. If you’ve worked with visualization in Python before, it’s likely that you have used matplotlib. But Bokeh differs from matplotlib."
},
{
"code": null,
"e": 393,
"s": 336,
"text": "To install Bokeh type the below command in the terminal."
},
{
"code": null,
"e": 411,
"s": 393,
"text": "pip install bokeh"
},
{
"code": null,
"e": 830,
"s": 411,
"text": "The intended uses of matplotlib and Bokeh are quite different. Matplotlib creates static graphics that are useful for quick and simple visualizations, or for creating publication-quality images. Bokeh creates visualizations for display on the web (whether locally or embedded in a webpage) and most importantly, the visualizations are meant to be highly interactive. Matplotlib does not offer either of these features."
},
{
"code": null,
"e": 1151,
"s": 830,
"text": "If would you like to visually interact with your data or you would like to distribute interactive visual data to a web audience, Bokeh is the library for you! If your main interest is producing finalized visualizations for publication, matplotlib may be better, although Bokeh does offer a way to create static graphics."
},
{
"code": null,
"e": 1354,
"s": 1151,
"text": "For this example we will be using one of the built-in dataset, i.e flowers data set. we can use circle() method to plot each data points as a circle on graph, we can also specify custom attributes like:"
},
{
"code": null,
"e": 1423,
"s": 1354,
"text": "first two elements has to be data on x-axis and y-axis respectively."
},
{
"code": null,
"e": 1468,
"s": 1423,
"text": "color: to assign color dynamically as shown."
},
{
"code": null,
"e": 1511,
"s": 1468,
"text": "fill_alpha: to assign opacity for circles."
},
{
"code": null,
"e": 1548,
"s": 1511,
"text": "size: to assign size of each circle."
},
{
"code": null,
"e": 1557,
"s": 1548,
"text": "Example:"
},
{
"code": null,
"e": 1564,
"s": 1557,
"text": "Python"
},
{
"code": "from bokeh.plotting import figure, output_file, showfrom bokeh.sampledata.iris import flowers # assign custom colors to represent each# class of data in a dictionary formatcolormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] # title for the graphp = figure(title=\"Iris Morphology\") # label on x-axisp.xaxis.axis_label = 'Petal Length' # label on y-axisp.yaxis.axis_label = 'Petal Width' # plot each datapoint as a circle# with custom attributes.p.circle(flowers[\"petal_length\"], flowers[\"petal_width\"], color=colors, fill_alpha=0.3, size=15) # you can save the output as an# interactive html fileoutput_file(\"iris1.html\", title=\"iris.py example\") # display the generated plot of graphshow(p)",
"e": 2373,
"s": 1564,
"text": null
},
{
"code": null,
"e": 2381,
"s": 2373,
"text": "Output:"
},
{
"code": null,
"e": 2601,
"s": 2381,
"text": "In the above example, output_file() function is used to save the output generated as an html file as bokeh uses web format to provide interactive display. Finally show() function is used to display the generated output."
},
{
"code": null,
"e": 2608,
"s": 2601,
"text": "Note: "
},
{
"code": null,
"e": 2665,
"s": 2608,
"text": "Red color = Setosa, Green = Versicolor, Blue = Virginica"
},
{
"code": null,
"e": 2868,
"s": 2665,
"text": "On top right of every visualization, there are interactive functions provided by bokeh. it allows 1. Pan across plot, 2. Zoom using box selection, 3. Zoom using scroll wheel, 4. Save, 5. Reset, 6. Help "
},
{
"code": null,
"e": 3327,
"s": 2868,
"text": "For this example we will be using custom created data set using list in code itself, i.e fruits data set. output_file() function is used to save the output generated as an html file as bokeh uses web format. we can use ColumnDataSource() function to map the custom data set (two lists) created with each other as a dictionary format. figure() function is used to initialize the graph figure so that data can be plotted on it with various parameters such as:"
},
{
"code": null,
"e": 3360,
"s": 3327,
"text": "x_range: defines data on x-axis."
},
{
"code": null,
"e": 3420,
"s": 3360,
"text": "plot_width, plot_height: defines width and height of graph."
},
{
"code": null,
"e": 3467,
"s": 3420,
"text": "toolbar_location: defines location of toolbar."
},
{
"code": null,
"e": 3498,
"s": 3467,
"text": "title: defines title of graph."
},
{
"code": null,
"e": 3681,
"s": 3498,
"text": "Here we are using simple vertical bars to represent data hence we use vbar() method and to assign various attributes to vertical bars we pass in different parameters inside it, like:"
},
{
"code": null,
"e": 3709,
"s": 3681,
"text": "x: data in x-axis direction"
},
{
"code": null,
"e": 3739,
"s": 3709,
"text": "top: data in y-axis direction"
},
{
"code": null,
"e": 3772,
"s": 3739,
"text": "width: defines width of each bar"
},
{
"code": null,
"e": 3795,
"s": 3772,
"text": "source: source of data"
},
{
"code": null,
"e": 3849,
"s": 3795,
"text": "legend_field: display list of classes present in data"
},
{
"code": null,
"e": 3894,
"s": 3849,
"text": "line_color: defines color for lines in graph"
},
{
"code": null,
"e": 3947,
"s": 3894,
"text": "fill_color: define different colors for data classes"
},
{
"code": null,
"e": 4047,
"s": 3947,
"text": "There are many more parameters that can be passed here. Some other properties that can be used are:"
},
{
"code": null,
"e": 4108,
"s": 4047,
"text": "y_range.start: used to define lower limit of data on y-axis."
},
{
"code": null,
"e": 4172,
"s": 4108,
"text": "y_range.end: used to define upper most limit of data on y-axis."
},
{
"code": null,
"e": 4227,
"s": 4172,
"text": "legend.orientation: defines orientation of legend bar."
},
{
"code": null,
"e": 4276,
"s": 4227,
"text": "legend.location: defines location of legend bar."
},
{
"code": null,
"e": 4341,
"s": 4276,
"text": "Finally show() function is used to display the generated output."
},
{
"code": null,
"e": 4350,
"s": 4341,
"text": "Example:"
},
{
"code": null,
"e": 4357,
"s": 4350,
"text": "Python"
},
{
"code": "from bokeh.io import output_file, showfrom bokeh.models import ColumnDataSourcefrom bokeh.palettes import Spectral10from bokeh.plotting import figurefrom bokeh.transform import factor_cmap output_file(\"fruits_bar_chart.html\") #output save file name # creating custom datafruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries', 'bananas','berries','pineapples','litchi']counts = [51, 34, 4, 28, 119, 79, 15, 68, 26, 88] # mapping counts with classes as a dictionarysource = ColumnDataSource(data=dict(fruits=fruits, counts=counts)) # initializing the figurep = figure(x_range=fruits, plot_width=800, plot_height=350, toolbar_location=None, title=\"Fruit Counts\") # assigning various attributes to plotp.vbar(x='fruits', top='counts', width=1, source=source, legend_field=\"fruits\", line_color='white', fill_color=factor_cmap('fruits', palette=Spectral10, factors=fruits)) p.xgrid.grid_line_color = Nonep.y_range.start = 0p.y_range.end = 150p.legend.orientation = \"horizontal\"p.legend.location = \"top_center\" # display outputshow(p)",
"e": 5584,
"s": 4357,
"text": null
},
{
"code": null,
"e": 5592,
"s": 5584,
"text": "Output:"
},
{
"code": null,
"e": 5676,
"s": 5592,
"text": "Note: This is a static graph which is also provided by bokeh similar to matplotlib."
},
{
"code": null,
"e": 5685,
"s": 5676,
"text": "rkbhola5"
},
{
"code": null,
"e": 5698,
"s": 5685,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 5713,
"s": 5698,
"text": "python-modules"
},
{
"code": null,
"e": 5720,
"s": 5713,
"text": "Python"
},
{
"code": null,
"e": 5818,
"s": 5720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5836,
"s": 5818,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5878,
"s": 5836,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5900,
"s": 5878,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5935,
"s": 5900,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5967,
"s": 5935,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5996,
"s": 5967,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 6023,
"s": 5996,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6053,
"s": 6023,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 6089,
"s": 6053,
"text": "Convert integer to string in Python"
}
] |
JavaBean class in Java | 14 Sep, 2017
JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a java class that should follow following conventions:
Must implement Serializable.It should have a public no-arg constructor.All properties in java bean must be private with public getters and setter methods.
Must implement Serializable.
It should have a public no-arg constructor.
All properties in java bean must be private with public getters and setter methods.
// Java program to illustrate the// structure of JavaBean classpublic class TestBean {private String name;public void setName(String name) { this.name = name; }public String getName() { return name; }}
Syntax for setter methods:
It should be public in nature.The return-type should be void.The setter method should be prefixed with set.It should take some argument i.e. it should not be no-arg method.
It should be public in nature.
The return-type should be void.
The setter method should be prefixed with set.
It should take some argument i.e. it should not be no-arg method.
Syntax for getter methods:
It should be public in nature.The return-type should not be void i.e. according to our requirement we have to give return-type.The getter method should be prefixed with get.It should not take any argument.
It should be public in nature.
The return-type should not be void i.e. according to our requirement we have to give return-type.
The getter method should be prefixed with get.
It should not take any argument.
For Boolean properties getter method name can be prefixed with either “get” or “is”. But recommended to use “is”.
// Java program to illustrate the// getName() method on boolean type attributepublic class Test {private boolean empty;public boolean getName() { return empty; }public boolean isempty() { return empty; }}
Implementation
// Java Program of JavaBean classpackage geeks;public class Student implements java.io.Serializable{private int id;private String name;public Student() { }public void setId(int id) { this.id = id; }public int getId() { return id; }public void setName(String name) { this.name = name; }public String getName() { return name; }}
// Java program to access JavaBean classpackage geeks;public class Test {public static void main(String args[]) { Student s = new Student(); // object is created s.setName("GFG"); // setting value to the object System.out.println(s.getName()); }}
Output:
GFG
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Class and Object
Java
Java-Class and Object
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Sep, 2017"
},
{
"code": null,
"e": 198,
"s": 52,
"text": "JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a java class that should follow following conventions:"
},
{
"code": null,
"e": 353,
"s": 198,
"text": "Must implement Serializable.It should have a public no-arg constructor.All properties in java bean must be private with public getters and setter methods."
},
{
"code": null,
"e": 382,
"s": 353,
"text": "Must implement Serializable."
},
{
"code": null,
"e": 426,
"s": 382,
"text": "It should have a public no-arg constructor."
},
{
"code": null,
"e": 510,
"s": 426,
"text": "All properties in java bean must be private with public getters and setter methods."
},
{
"code": "// Java program to illustrate the// structure of JavaBean classpublic class TestBean {private String name;public void setName(String name) { this.name = name; }public String getName() { return name; }}",
"e": 738,
"s": 510,
"text": null
},
{
"code": null,
"e": 765,
"s": 738,
"text": "Syntax for setter methods:"
},
{
"code": null,
"e": 938,
"s": 765,
"text": "It should be public in nature.The return-type should be void.The setter method should be prefixed with set.It should take some argument i.e. it should not be no-arg method."
},
{
"code": null,
"e": 969,
"s": 938,
"text": "It should be public in nature."
},
{
"code": null,
"e": 1001,
"s": 969,
"text": "The return-type should be void."
},
{
"code": null,
"e": 1048,
"s": 1001,
"text": "The setter method should be prefixed with set."
},
{
"code": null,
"e": 1114,
"s": 1048,
"text": "It should take some argument i.e. it should not be no-arg method."
},
{
"code": null,
"e": 1141,
"s": 1114,
"text": "Syntax for getter methods:"
},
{
"code": null,
"e": 1347,
"s": 1141,
"text": "It should be public in nature.The return-type should not be void i.e. according to our requirement we have to give return-type.The getter method should be prefixed with get.It should not take any argument."
},
{
"code": null,
"e": 1378,
"s": 1347,
"text": "It should be public in nature."
},
{
"code": null,
"e": 1476,
"s": 1378,
"text": "The return-type should not be void i.e. according to our requirement we have to give return-type."
},
{
"code": null,
"e": 1523,
"s": 1476,
"text": "The getter method should be prefixed with get."
},
{
"code": null,
"e": 1556,
"s": 1523,
"text": "It should not take any argument."
},
{
"code": null,
"e": 1670,
"s": 1556,
"text": "For Boolean properties getter method name can be prefixed with either “get” or “is”. But recommended to use “is”."
},
{
"code": "// Java program to illustrate the// getName() method on boolean type attributepublic class Test {private boolean empty;public boolean getName() { return empty; }public boolean isempty() { return empty; }}",
"e": 1901,
"s": 1670,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1901,
"text": "Implementation"
},
{
"code": "// Java Program of JavaBean classpackage geeks;public class Student implements java.io.Serializable{private int id;private String name;public Student() { }public void setId(int id) { this.id = id; }public int getId() { return id; }public void setName(String name) { this.name = name; }public String getName() { return name; }}",
"e": 2301,
"s": 1916,
"text": null
},
{
"code": "// Java program to access JavaBean classpackage geeks;public class Test {public static void main(String args[]) { Student s = new Student(); // object is created s.setName(\"GFG\"); // setting value to the object System.out.println(s.getName()); }}",
"e": 2575,
"s": 2301,
"text": null
},
{
"code": null,
"e": 2583,
"s": 2575,
"text": "Output:"
},
{
"code": null,
"e": 2588,
"s": 2583,
"text": "GFG\n"
},
{
"code": null,
"e": 2894,
"s": 2588,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3019,
"s": 2894,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3041,
"s": 3019,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 3046,
"s": 3041,
"text": "Java"
},
{
"code": null,
"e": 3068,
"s": 3046,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 3073,
"s": 3068,
"text": "Java"
}
] |
Python Support for gzip files (gzip) | GZip application is used for compression and decompression of files. It is a part of GNU project. Python’s gzip module is the interface to GZip application. The gzip data compression algorithm itself is based on zlib module.
The gzip module contains definition of GzipFile class along with its methods. It also caontains convenience function open(), compress() and decompress().
Easiest way to achieve compression and decompression is by using above mentioned functions.
This function opens a gzip-compressed file in binary or text mode and returns a file like object, which may be physical file, a string or byte object. By default, the file is opened in ‘rb’ mode i.e. reading binary data, however, the mode parameter to this function can take other modes as listed below.
binary mode: 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x', 'xb'
text mode : 'rt', 'at', 'wt', or 'xt'
This function also defines compression level whose acceptable value is between 0 to 9. When the file is opened in text mode, the GzipFile object is wrapped in TextIOWrapper object.
This function applies compression on the data given to it as argument and returns compressed byte object. By default compression level is 9.
This function decompresses the byte object and returns uncompressed data.
Following example creates a gzip file by writing compressed data in it.
>>> import gzip
>>> data = b'Python - Batteries included'
>>> with gzip.open("test.txt.gz", "wb") as f:
f.write(data)
This will create “test.txt.gz” file in current directory. This gzip archive contains “test.txt” which you can verify using any unzipping utility.
To programmatically read this compressed file
>>> with gzip.open("test.txt.gz", "rb") as f:
data = f.read()
>>> data
b'Python - Batteries included'
To compress an existing file to a gzip archive, read text in it and convert it to a bytearray. This bytearray object is then written to a gzip file. In the example below, ‘zen.txt’ file is assumed to be present in current directory.
fp = open("zen.txt","rb")
>>> data = fp.read()
>>> bindata = bytearray(data)
>>> with gzip.open("zen.txt.gz", "wb") as f:
f.write(bindata)
To retrieve the uncompressed file from gzip archive
>>> fp = open("zen1.txt", "wb")
>>> with gzip.open("zen.txt.gz", "rb") as f:
bindata = f.read()
>>> fp.write(bindata)
>>> fp.close()
Above code will create ‘zen1.txt’ in current directory which contain same data as in ‘zen.txt’
In addition to these convenience functions, gzip module also has GzipFile class which defines the compress() and decompress() methods. The constructor of this class takes file, mode and compressionlevel arguments exactly with same meaning as above.
When mode parameter is given as ‘w’ or ‘wb’ or ‘wt’, the GipFile object will provide write() method to compress the given data and write to a gzip file.
>>> f = gzip.GzipFile("testnew.txt.gz","wb")
>>> data = b'Python - Batteries included'
>>> f.write(data)
>>> f.close()
This will create a testnew.txt.gz file. You can unzip it using any utility to see that it contains testnew.txt with ‘Python – Batteries included’ text in it.
To uncompress the gzip file using GzipFile object,create it with ‘rb’ value to mode parameter and read the uncompressed data by read() method
>>> f = gzip.GzipFile("testnew.txt.gz","rb")
>>> data = f.read()
>>> data
b'Python - Batteries included'
In this article we learned how gzip library can be implemented by Python’s gzip module. | [
{
"code": null,
"e": 1412,
"s": 1187,
"text": "GZip application is used for compression and decompression of files. It is a part of GNU project. Python’s gzip module is the interface to GZip application. The gzip data compression algorithm itself is based on zlib module."
},
{
"code": null,
"e": 1566,
"s": 1412,
"text": "The gzip module contains definition of GzipFile class along with its methods. It also caontains convenience function open(), compress() and decompress()."
},
{
"code": null,
"e": 1658,
"s": 1566,
"text": "Easiest way to achieve compression and decompression is by using above mentioned functions."
},
{
"code": null,
"e": 1962,
"s": 1658,
"text": "This function opens a gzip-compressed file in binary or text mode and returns a file like object, which may be physical file, a string or byte object. By default, the file is opened in ‘rb’ mode i.e. reading binary data, however, the mode parameter to this function can take other modes as listed below."
},
{
"code": null,
"e": 2056,
"s": 1962,
"text": "binary mode: 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x', 'xb'\ntext mode : 'rt', 'at', 'wt', or 'xt'"
},
{
"code": null,
"e": 2237,
"s": 2056,
"text": "This function also defines compression level whose acceptable value is between 0 to 9. When the file is opened in text mode, the GzipFile object is wrapped in TextIOWrapper object."
},
{
"code": null,
"e": 2378,
"s": 2237,
"text": "This function applies compression on the data given to it as argument and returns compressed byte object. By default compression level is 9."
},
{
"code": null,
"e": 2452,
"s": 2378,
"text": "This function decompresses the byte object and returns uncompressed data."
},
{
"code": null,
"e": 2524,
"s": 2452,
"text": "Following example creates a gzip file by writing compressed data in it."
},
{
"code": null,
"e": 2642,
"s": 2524,
"text": ">>> import gzip\n>>> data = b'Python - Batteries included'\n>>> with gzip.open(\"test.txt.gz\", \"wb\") as f:\nf.write(data)"
},
{
"code": null,
"e": 2788,
"s": 2642,
"text": "This will create “test.txt.gz” file in current directory. This gzip archive contains “test.txt” which you can verify using any unzipping utility."
},
{
"code": null,
"e": 2834,
"s": 2788,
"text": "To programmatically read this compressed file"
},
{
"code": null,
"e": 2936,
"s": 2834,
"text": ">>> with gzip.open(\"test.txt.gz\", \"rb\") as f:\ndata = f.read()\n>>> data\nb'Python - Batteries included'"
},
{
"code": null,
"e": 3169,
"s": 2936,
"text": "To compress an existing file to a gzip archive, read text in it and convert it to a bytearray. This bytearray object is then written to a gzip file. In the example below, ‘zen.txt’ file is assumed to be present in current directory."
},
{
"code": null,
"e": 3308,
"s": 3169,
"text": "fp = open(\"zen.txt\",\"rb\")\n>>> data = fp.read()\n>>> bindata = bytearray(data)\n>>> with gzip.open(\"zen.txt.gz\", \"wb\") as f:\nf.write(bindata)"
},
{
"code": null,
"e": 3360,
"s": 3308,
"text": "To retrieve the uncompressed file from gzip archive"
},
{
"code": null,
"e": 3493,
"s": 3360,
"text": ">>> fp = open(\"zen1.txt\", \"wb\")\n>>> with gzip.open(\"zen.txt.gz\", \"rb\") as f:\nbindata = f.read()\n>>> fp.write(bindata)\n>>> fp.close()"
},
{
"code": null,
"e": 3588,
"s": 3493,
"text": "Above code will create ‘zen1.txt’ in current directory which contain same data as in ‘zen.txt’"
},
{
"code": null,
"e": 3837,
"s": 3588,
"text": "In addition to these convenience functions, gzip module also has GzipFile class which defines the compress() and decompress() methods. The constructor of this class takes file, mode and compressionlevel arguments exactly with same meaning as above."
},
{
"code": null,
"e": 3990,
"s": 3837,
"text": "When mode parameter is given as ‘w’ or ‘wb’ or ‘wt’, the GipFile object will provide write() method to compress the given data and write to a gzip file."
},
{
"code": null,
"e": 4109,
"s": 3990,
"text": ">>> f = gzip.GzipFile(\"testnew.txt.gz\",\"wb\")\n>>> data = b'Python - Batteries included'\n>>> f.write(data)\n>>> f.close()"
},
{
"code": null,
"e": 4267,
"s": 4109,
"text": "This will create a testnew.txt.gz file. You can unzip it using any utility to see that it contains testnew.txt with ‘Python – Batteries included’ text in it."
},
{
"code": null,
"e": 4409,
"s": 4267,
"text": "To uncompress the gzip file using GzipFile object,create it with ‘rb’ value to mode parameter and read the uncompressed data by read() method"
},
{
"code": null,
"e": 4514,
"s": 4409,
"text": ">>> f = gzip.GzipFile(\"testnew.txt.gz\",\"rb\")\n>>> data = f.read()\n>>> data\nb'Python - Batteries included'"
},
{
"code": null,
"e": 4602,
"s": 4514,
"text": "In this article we learned how gzip library can be implemented by Python’s gzip module."
}
] |
Protractor - Protractor And Selenium Server | As discussed earlier, Protractor is an open source, end-to-end testing framework for Angular and AngularJS applications. It is Node.js program. On the other hand, Selenium is a browser automation framework that includes the Selenium Server, the WebDriver APIs and the WebDriver browser drivers.
If we talk about the conjunction of Protractor and Selenium, Protractor can work with Selenium server to provide an automated test infrastructure. The infrastructure can simulate user’s interaction with an angular application that is running in a browser or on mobile device. The conjunction of Protractor and Selenium can be divided into three partitions namely test, server and Browser, as shown in the following diagram −
As we have seen in the above diagram, a test using Selenium WebDriver involves the following three processes −
The test scripts
The server
The browser
In this section, let us discuss the communication between these three processes.
The communication between the first two processes - the test scripts and the server depends upon the working of Selenium Server. In other words, we can say that the way Selenium server is running will give the shape to the communication process between test scripts and server.
Selenium server can run locally on our machine as standalone Selenium Server (selenium-server-standalone.jar) or it can run remotely via a service (Sauce Labs). In case of standalone Selenium server, there would be an http communication between Node.js and selenium server.
As we know that the server is responsible for forwarding commands to the browser after interpreting the same from the test scripts. That is why server and the browser also require a communication medium and here the communication is done with the help of JSON WebDriver Wire Protocol. The browser extended with Browser Driver that is used to interpret the commands.
The above concept about Selenium WebDriver processes and their communication can be understood with the help of following diagram −
While working with Protractor, the very first process, that is test script is run using Node.js but before performing any action on the browser it will send an extra command to make it sure that the application being tested is stabilized.
Selenium Server acts like a proxy server in between our test script and the browser driver. It basically forwards the command from our test script to the WebDriver and returns the responses from the WebDriver to our test script. There are following options for setting up the Selenium server which are included in conf.js file of test script −
If we want to run the server on our local machine, we need to install standalone selenium server. The prerequisite to install standalone selenium server is JDK (Java Development Kit). We must have JDK installed on our local machine. We can check it by running the following command from command line −
java -version
Now, we have the option to install and start Selenium Server manually or from test script.
For installing and starting Selenium server manually, we need to use WebDriver-Manager command line tool that comes with Protractor. The steps for installing and starting Selenium server are as follows −
Step 1 − The first step is to install the Selenium server and ChromeDriver. It can be done with the help of running following command −
webdriver-manager update
Step 2 − Next, we need to start the server. It can be done with the help of running following command −
webdriver-manager start
Step 3 − At last we need to set seleniumAddress in config file to the address of the running server. The default address would be http://localhost:4444/wd/hub.
For starting Selenium server from a Test Script, we need to set the following options in our config file −
Location of jar file − We need to set the location of jar file for standalone Selenium server in config file by setting seleniumServerJar.
Location of jar file − We need to set the location of jar file for standalone Selenium server in config file by setting seleniumServerJar.
Specifying the port − We also need to specify the port to use to start the standalone Selenium Server. It can be specified in config file by setting seleniumPort. The default port is 4444.
Specifying the port − We also need to specify the port to use to start the standalone Selenium Server. It can be specified in config file by setting seleniumPort. The default port is 4444.
Array of command line options − We also need to set the array of command line options to pass to the server. It can be specified in config file by setting seleniumArgs. If you need full list of array of commands, then start the server with the -help flag.
Array of command line options − We also need to set the array of command line options to pass to the server. It can be specified in config file by setting seleniumArgs. If you need full list of array of commands, then start the server with the -help flag.
Another option for running our test is to use Selenium server remotely. The prerequisite for using server remotely is that we must have an account with a service that hosts the server. While working with Protractor we have the built-in support for the following services hosting the server −
For using TestObject as the remote Selenium Server, we need to set the testobjectUser, the user name of our TestObject account and testobjectKey, the API key of our TestObject account.
For using BrowserStack as the remote Selenium Server, we need to set the browserstackUser, the user name of our BrowserStack account and browserstackKey, the API key of our BrowserStack account.
For using Sauce Labs as the remote Selenium Server, we need to set the sauceUser, the user name of our Sauce Labs account and SauceKey, the API key of our Sauce Labs account.
For using Kobiton as the remote Selenium Server we need to set the kobitonUser, the user name of our Kobiton account and kobitonKey, the API key of our Kobiton account.
One more option for running our test is to connect to the Browser Driver directly without using Selenium server. Protractor can test directly, without the use of Selenium Server, against Chrome and Firefox by setting directConnect: true in config file.
Before configuring and setting up the browser, we need to know which browsers are supported by Protractor. The following is the list of browsers supported by Protractor −
ChromeDriver
FirefoxDriver
SafariDriver
IEDriver
Appium-iOS/Safari
Appium-Android/Chrome
Selendroid
PhantomJS
For setting and configuring the browser, we need to move to config file of Protractor because the browser setup is done within the capabilities object of config file.
For setting up the Chrome Browser, we need to set the capabilities object as follows
capabilities: {
'browserName': 'chrome'
}
We can also add Chrome-Specific options which are nested in the chromeOptions and its full list can be seen at https://sites.google.com/a/chromium.org/chromedriver/capabilities.
For example, if you want to add FPS-counter in the upper right, then it can be done as follows in the config file −
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['show-fps-counter=true']
}
},
For setting up the Firefox browser, we need to set the capabilities object as follows −
capabilities: {
'browserName': 'firefox'
}
We can also add Firefox-Specific options which are nested in the moz:firefoxOptions object and its full list can be seen at https://github.com/mozilla/geckodriver#firefox-capabilities.
For example, if you want to run your test on Firefox in safe mode then it can be done as follows in the config file −
capabilities: {
'browserName': 'firefox',
'moz:firefoxOptions': {
'args': ['—safe-mode']
}
},
For setting up any other browser than Chrome or Firefox, we need to install a separate binary from https://docs.seleniumhq.org/download/.
Actually, PhantomJS is no longer supported because of its crashing issues. Instead of that it is recommended to use headless Chrome or headless Firefox. They can be set up as follows −
For setting up headless Chrome, we need to start Chrome with the –headless flag as follows −
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': [“--headless”, “--disable-gpu”, “--window-size=800,600”]
}
},
For setting up headless Firefox, we need to start Firefox with the –headless flag as follows −
capabilities: {
'browserName': 'firefox',
'moz:firefoxOptions': {
'args': [“--headless”]
}
},
We can also test against multiple browsers. For this we need to use multiCapabilities configuration option as follows −
multiCapabilities: [{
'browserName': 'chrome'
},{
'browserName': 'firefox'
}]
Two BDD (Behavior driven development) test frameworks, Jasmine and Mocha are supported by Protractor. Both frameworks are based on JavaScript and Node.js. The syntax, report and scaffolding, required for writing and managing the tests, are provided by these frameworks.
Next, we see how we can install various frameworks −
It is the default test framework for Protractor. When you install Protractor, you will get Jasmine 2.x version with it. We do not need to get it installed separately.
Mocha is another JavaScript test framework basically running on Node.js. For using Mocha as our test framework, we need to use the BDD (Behavior driven development) interface and Chai assertions with Chai As Promised. The installation can be done with the help of following commands −
npm install -g mocha
npm install chai
npm install chai-as-promised
As you can see, -g option is used while installing mocha, it is because we have installed Protractor globally using the -g option. After installing it, we need to require and set up Chai inside our test files. It can be done as follows −
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
After this, we can use Chai As Promised as such −
expect(myElement.getText()).to.eventually.equal('some text');
Now, we need to set the framework property to mocha of config file by adding framework: ‘mocha’. The options like ‘reporter’ and ‘slow’ for mocha can be added in config file as follows −
mochaOpts: {
reporter: "spec", slow: 3000
}
For using Cucumber as our test framework, we need to integrate it with Protractor with framework option custom. The installation can be done with the help of following commands
npm install -g cucumber
npm install --save-dev protractor-cucumber-framework
As you can see, -g option is used while installing Cucumber, it is because we have installed Protractor globally i.e. with -g option. Next, we need to set the framework property to custom of config file by adding framework: ‘custom’ and frameworkPath: ‘Protractor-cucumber-framework’ to the config file named cucumberConf.js.
The sample code shown below is a basic cucumberConf.js file which can be used to run cucumber feature files with Protractor −
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
baseUrl: 'https://angularjs.org/',
capabilities: {
browserName:'Firefox'
},
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
specs: [
'./cucumber/*.feature'
],
// cucumber command line options
cucumberOpts: {
require: ['./cucumber/*.js'],
tags: [],
strict: true,
format: ["pretty"],
'dry-run': false,
compiler: []
},
onPrepare: function () { | [
{
"code": null,
"e": 2320,
"s": 2025,
"text": "As discussed earlier, Protractor is an open source, end-to-end testing framework for Angular and AngularJS applications. It is Node.js program. On the other hand, Selenium is a browser automation framework that includes the Selenium Server, the WebDriver APIs and the WebDriver browser drivers."
},
{
"code": null,
"e": 2745,
"s": 2320,
"text": "If we talk about the conjunction of Protractor and Selenium, Protractor can work with Selenium server to provide an automated test infrastructure. The infrastructure can simulate user’s interaction with an angular application that is running in a browser or on mobile device. The conjunction of Protractor and Selenium can be divided into three partitions namely test, server and Browser, as shown in the following diagram −"
},
{
"code": null,
"e": 2856,
"s": 2745,
"text": "As we have seen in the above diagram, a test using Selenium WebDriver involves the following three processes −"
},
{
"code": null,
"e": 2873,
"s": 2856,
"text": "The test scripts"
},
{
"code": null,
"e": 2884,
"s": 2873,
"text": "The server"
},
{
"code": null,
"e": 2896,
"s": 2884,
"text": "The browser"
},
{
"code": null,
"e": 2977,
"s": 2896,
"text": "In this section, let us discuss the communication between these three processes."
},
{
"code": null,
"e": 3255,
"s": 2977,
"text": "The communication between the first two processes - the test scripts and the server depends upon the working of Selenium Server. In other words, we can say that the way Selenium server is running will give the shape to the communication process between test scripts and server."
},
{
"code": null,
"e": 3529,
"s": 3255,
"text": "Selenium server can run locally on our machine as standalone Selenium Server (selenium-server-standalone.jar) or it can run remotely via a service (Sauce Labs). In case of standalone Selenium server, there would be an http communication between Node.js and selenium server."
},
{
"code": null,
"e": 3895,
"s": 3529,
"text": "As we know that the server is responsible for forwarding commands to the browser after interpreting the same from the test scripts. That is why server and the browser also require a communication medium and here the communication is done with the help of JSON WebDriver Wire Protocol. The browser extended with Browser Driver that is used to interpret the commands."
},
{
"code": null,
"e": 4027,
"s": 3895,
"text": "The above concept about Selenium WebDriver processes and their communication can be understood with the help of following diagram −"
},
{
"code": null,
"e": 4266,
"s": 4027,
"text": "While working with Protractor, the very first process, that is test script is run using Node.js but before performing any action on the browser it will send an extra command to make it sure that the application being tested is stabilized."
},
{
"code": null,
"e": 4610,
"s": 4266,
"text": "Selenium Server acts like a proxy server in between our test script and the browser driver. It basically forwards the command from our test script to the WebDriver and returns the responses from the WebDriver to our test script. There are following options for setting up the Selenium server which are included in conf.js file of test script −"
},
{
"code": null,
"e": 4912,
"s": 4610,
"text": "If we want to run the server on our local machine, we need to install standalone selenium server. The prerequisite to install standalone selenium server is JDK (Java Development Kit). We must have JDK installed on our local machine. We can check it by running the following command from command line −"
},
{
"code": null,
"e": 4927,
"s": 4912,
"text": "java -version\n"
},
{
"code": null,
"e": 5018,
"s": 4927,
"text": "Now, we have the option to install and start Selenium Server manually or from test script."
},
{
"code": null,
"e": 5222,
"s": 5018,
"text": "For installing and starting Selenium server manually, we need to use WebDriver-Manager command line tool that comes with Protractor. The steps for installing and starting Selenium server are as follows −"
},
{
"code": null,
"e": 5358,
"s": 5222,
"text": "Step 1 − The first step is to install the Selenium server and ChromeDriver. It can be done with the help of running following command −"
},
{
"code": null,
"e": 5384,
"s": 5358,
"text": "webdriver-manager update\n"
},
{
"code": null,
"e": 5488,
"s": 5384,
"text": "Step 2 − Next, we need to start the server. It can be done with the help of running following command −"
},
{
"code": null,
"e": 5513,
"s": 5488,
"text": "webdriver-manager start\n"
},
{
"code": null,
"e": 5673,
"s": 5513,
"text": "Step 3 − At last we need to set seleniumAddress in config file to the address of the running server. The default address would be http://localhost:4444/wd/hub."
},
{
"code": null,
"e": 5780,
"s": 5673,
"text": "For starting Selenium server from a Test Script, we need to set the following options in our config file −"
},
{
"code": null,
"e": 5919,
"s": 5780,
"text": "Location of jar file − We need to set the location of jar file for standalone Selenium server in config file by setting seleniumServerJar."
},
{
"code": null,
"e": 6058,
"s": 5919,
"text": "Location of jar file − We need to set the location of jar file for standalone Selenium server in config file by setting seleniumServerJar."
},
{
"code": null,
"e": 6247,
"s": 6058,
"text": "Specifying the port − We also need to specify the port to use to start the standalone Selenium Server. It can be specified in config file by setting seleniumPort. The default port is 4444."
},
{
"code": null,
"e": 6436,
"s": 6247,
"text": "Specifying the port − We also need to specify the port to use to start the standalone Selenium Server. It can be specified in config file by setting seleniumPort. The default port is 4444."
},
{
"code": null,
"e": 6692,
"s": 6436,
"text": "Array of command line options − We also need to set the array of command line options to pass to the server. It can be specified in config file by setting seleniumArgs. If you need full list of array of commands, then start the server with the -help flag."
},
{
"code": null,
"e": 6948,
"s": 6692,
"text": "Array of command line options − We also need to set the array of command line options to pass to the server. It can be specified in config file by setting seleniumArgs. If you need full list of array of commands, then start the server with the -help flag."
},
{
"code": null,
"e": 7240,
"s": 6948,
"text": "Another option for running our test is to use Selenium server remotely. The prerequisite for using server remotely is that we must have an account with a service that hosts the server. While working with Protractor we have the built-in support for the following services hosting the server −"
},
{
"code": null,
"e": 7425,
"s": 7240,
"text": "For using TestObject as the remote Selenium Server, we need to set the testobjectUser, the user name of our TestObject account and testobjectKey, the API key of our TestObject account."
},
{
"code": null,
"e": 7620,
"s": 7425,
"text": "For using BrowserStack as the remote Selenium Server, we need to set the browserstackUser, the user name of our BrowserStack account and browserstackKey, the API key of our BrowserStack account."
},
{
"code": null,
"e": 7795,
"s": 7620,
"text": "For using Sauce Labs as the remote Selenium Server, we need to set the sauceUser, the user name of our Sauce Labs account and SauceKey, the API key of our Sauce Labs account."
},
{
"code": null,
"e": 7964,
"s": 7795,
"text": "For using Kobiton as the remote Selenium Server we need to set the kobitonUser, the user name of our Kobiton account and kobitonKey, the API key of our Kobiton account."
},
{
"code": null,
"e": 8217,
"s": 7964,
"text": "One more option for running our test is to connect to the Browser Driver directly without using Selenium server. Protractor can test directly, without the use of Selenium Server, against Chrome and Firefox by setting directConnect: true in config file."
},
{
"code": null,
"e": 8388,
"s": 8217,
"text": "Before configuring and setting up the browser, we need to know which browsers are supported by Protractor. The following is the list of browsers supported by Protractor −"
},
{
"code": null,
"e": 8401,
"s": 8388,
"text": "ChromeDriver"
},
{
"code": null,
"e": 8415,
"s": 8401,
"text": "FirefoxDriver"
},
{
"code": null,
"e": 8428,
"s": 8415,
"text": "SafariDriver"
},
{
"code": null,
"e": 8437,
"s": 8428,
"text": "IEDriver"
},
{
"code": null,
"e": 8455,
"s": 8437,
"text": "Appium-iOS/Safari"
},
{
"code": null,
"e": 8477,
"s": 8455,
"text": "Appium-Android/Chrome"
},
{
"code": null,
"e": 8488,
"s": 8477,
"text": "Selendroid"
},
{
"code": null,
"e": 8498,
"s": 8488,
"text": "PhantomJS"
},
{
"code": null,
"e": 8665,
"s": 8498,
"text": "For setting and configuring the browser, we need to move to config file of Protractor because the browser setup is done within the capabilities object of config file."
},
{
"code": null,
"e": 8750,
"s": 8665,
"text": "For setting up the Chrome Browser, we need to set the capabilities object as follows"
},
{
"code": null,
"e": 8796,
"s": 8750,
"text": "capabilities: {\n 'browserName': 'chrome'\n}\n"
},
{
"code": null,
"e": 8974,
"s": 8796,
"text": "We can also add Chrome-Specific options which are nested in the chromeOptions and its full list can be seen at https://sites.google.com/a/chromium.org/chromedriver/capabilities."
},
{
"code": null,
"e": 9090,
"s": 8974,
"text": "For example, if you want to add FPS-counter in the upper right, then it can be done as follows in the config file −"
},
{
"code": null,
"e": 9204,
"s": 9090,
"text": "capabilities: {\n 'browserName': 'chrome',\n 'chromeOptions': {\n 'args': ['show-fps-counter=true']\n }\n},"
},
{
"code": null,
"e": 9292,
"s": 9204,
"text": "For setting up the Firefox browser, we need to set the capabilities object as follows −"
},
{
"code": null,
"e": 9339,
"s": 9292,
"text": "capabilities: {\n 'browserName': 'firefox'\n}\n"
},
{
"code": null,
"e": 9524,
"s": 9339,
"text": "We can also add Firefox-Specific options which are nested in the moz:firefoxOptions object and its full list can be seen at https://github.com/mozilla/geckodriver#firefox-capabilities."
},
{
"code": null,
"e": 9642,
"s": 9524,
"text": "For example, if you want to run your test on Firefox in safe mode then it can be done as follows in the config file −"
},
{
"code": null,
"e": 9750,
"s": 9642,
"text": "capabilities: {\n 'browserName': 'firefox',\n 'moz:firefoxOptions': {\n 'args': ['—safe-mode']\n }\n},"
},
{
"code": null,
"e": 9888,
"s": 9750,
"text": "For setting up any other browser than Chrome or Firefox, we need to install a separate binary from https://docs.seleniumhq.org/download/."
},
{
"code": null,
"e": 10073,
"s": 9888,
"text": "Actually, PhantomJS is no longer supported because of its crashing issues. Instead of that it is recommended to use headless Chrome or headless Firefox. They can be set up as follows −"
},
{
"code": null,
"e": 10166,
"s": 10073,
"text": "For setting up headless Chrome, we need to start Chrome with the –headless flag as follows −"
},
{
"code": null,
"e": 10311,
"s": 10166,
"text": "capabilities: {\n 'browserName': 'chrome',\n 'chromeOptions': {\n 'args': [“--headless”, “--disable-gpu”, “--window-size=800,600”]\n }\n},"
},
{
"code": null,
"e": 10406,
"s": 10311,
"text": "For setting up headless Firefox, we need to start Firefox with the –headless flag as follows −"
},
{
"code": null,
"e": 10515,
"s": 10406,
"text": "capabilities: {\n 'browserName': 'firefox',\n 'moz:firefoxOptions': {\n 'args': [“--headless”]\n }\n},"
},
{
"code": null,
"e": 10635,
"s": 10515,
"text": "We can also test against multiple browsers. For this we need to use multiCapabilities configuration option as follows −"
},
{
"code": null,
"e": 10719,
"s": 10635,
"text": "multiCapabilities: [{\n 'browserName': 'chrome'\n},{\n 'browserName': 'firefox'\n}]"
},
{
"code": null,
"e": 10989,
"s": 10719,
"text": "Two BDD (Behavior driven development) test frameworks, Jasmine and Mocha are supported by Protractor. Both frameworks are based on JavaScript and Node.js. The syntax, report and scaffolding, required for writing and managing the tests, are provided by these frameworks."
},
{
"code": null,
"e": 11042,
"s": 10989,
"text": "Next, we see how we can install various frameworks −"
},
{
"code": null,
"e": 11209,
"s": 11042,
"text": "It is the default test framework for Protractor. When you install Protractor, you will get Jasmine 2.x version with it. We do not need to get it installed separately."
},
{
"code": null,
"e": 11494,
"s": 11209,
"text": "Mocha is another JavaScript test framework basically running on Node.js. For using Mocha as our test framework, we need to use the BDD (Behavior driven development) interface and Chai assertions with Chai As Promised. The installation can be done with the help of following commands −"
},
{
"code": null,
"e": 11562,
"s": 11494,
"text": "npm install -g mocha\nnpm install chai\nnpm install chai-as-promised\n"
},
{
"code": null,
"e": 11800,
"s": 11562,
"text": "As you can see, -g option is used while installing mocha, it is because we have installed Protractor globally using the -g option. After installing it, we need to require and set up Chai inside our test files. It can be done as follows −"
},
{
"code": null,
"e": 11930,
"s": 11800,
"text": "var chai = require('chai');\nvar chaiAsPromised = require('chai-as-promised');\nchai.use(chaiAsPromised);\nvar expect = chai.expect;"
},
{
"code": null,
"e": 11980,
"s": 11930,
"text": "After this, we can use Chai As Promised as such −"
},
{
"code": null,
"e": 12043,
"s": 11980,
"text": "expect(myElement.getText()).to.eventually.equal('some text');\n"
},
{
"code": null,
"e": 12230,
"s": 12043,
"text": "Now, we need to set the framework property to mocha of config file by adding framework: ‘mocha’. The options like ‘reporter’ and ‘slow’ for mocha can be added in config file as follows −"
},
{
"code": null,
"e": 12278,
"s": 12230,
"text": "mochaOpts: {\n reporter: \"spec\", slow: 3000\n}\n"
},
{
"code": null,
"e": 12455,
"s": 12278,
"text": "For using Cucumber as our test framework, we need to integrate it with Protractor with framework option custom. The installation can be done with the help of following commands"
},
{
"code": null,
"e": 12533,
"s": 12455,
"text": "npm install -g cucumber\nnpm install --save-dev protractor-cucumber-framework\n"
},
{
"code": null,
"e": 12859,
"s": 12533,
"text": "As you can see, -g option is used while installing Cucumber, it is because we have installed Protractor globally i.e. with -g option. Next, we need to set the framework property to custom of config file by adding framework: ‘custom’ and frameworkPath: ‘Protractor-cucumber-framework’ to the config file named cucumberConf.js."
},
{
"code": null,
"e": 12985,
"s": 12859,
"text": "The sample code shown below is a basic cucumberConf.js file which can be used to run cucumber feature files with Protractor −"
}
] |
time.Time.Local() Function in Golang with Examples | 19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Local() function in Go language is used to find “t” with the location that is set to local time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) Local() Time
Here, “t” is the stated time.
Return Value: It returns “t” along with the location that is set to local time.
Example 1:
// Golang program to illustrate the usage of// Time.Local() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t parameter of Local method t := time.Date(2019, 2, 11, 10, 03, 00, 00, time.UTC) // Calling Local method local := t.Local() // Prints output fmt.Printf("%v\n", local)}
Output:
2019-02-11 10:03:00 +0000 UTC
Example 2:
// Golang program to illustrate the usage of// Time.Local() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining location using FixedZone method location := time.FixedZone("UTC-7", -6*56*34) // Defining t for calling Local method t := time.Date(2019, 2, 11, 10, 03, 00, 00, location) // Calling Local method local := t.Local() // Prints output fmt.Printf("%v\n", local)}
Output:
2019-02-11 13:13:24 +0000 UTC
Here, FixedZone() method is used in order to define the location parameter of the Date() method so the time in output is returned according to that location.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Loops in Go Language
Time Durations in Golang
Constants- Go Language
Strings in Golang
time.Parse() Function in Golang With Examples
Go Variables
Class and Object in Golang | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 364,
"s": 28,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Local() function in Go language is used to find “t” with the location that is set to local time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 372,
"s": 364,
"text": "Syntax:"
},
{
"code": null,
"e": 400,
"s": 372,
"text": "func (t Time) Local() Time\n"
},
{
"code": null,
"e": 430,
"s": 400,
"text": "Here, “t” is the stated time."
},
{
"code": null,
"e": 510,
"s": 430,
"text": "Return Value: It returns “t” along with the location that is set to local time."
},
{
"code": null,
"e": 521,
"s": 510,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Local() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t parameter of Local method t := time.Date(2019, 2, 11, 10, 03, 00, 00, time.UTC) // Calling Local method local := t.Local() // Prints output fmt.Printf(\"%v\\n\", local)}",
"e": 930,
"s": 521,
"text": null
},
{
"code": null,
"e": 938,
"s": 930,
"text": "Output:"
},
{
"code": null,
"e": 969,
"s": 938,
"text": "2019-02-11 10:03:00 +0000 UTC\n"
},
{
"code": null,
"e": 980,
"s": 969,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Local() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining location using FixedZone method location := time.FixedZone(\"UTC-7\", -6*56*34) // Defining t for calling Local method t := time.Date(2019, 2, 11, 10, 03, 00, 00, location) // Calling Local method local := t.Local() // Prints output fmt.Printf(\"%v\\n\", local)}",
"e": 1472,
"s": 980,
"text": null
},
{
"code": null,
"e": 1480,
"s": 1472,
"text": "Output:"
},
{
"code": null,
"e": 1511,
"s": 1480,
"text": "2019-02-11 13:13:24 +0000 UTC\n"
},
{
"code": null,
"e": 1669,
"s": 1511,
"text": "Here, FixedZone() method is used in order to define the location parameter of the Date() method so the time in output is returned according to that location."
},
{
"code": null,
"e": 1681,
"s": 1669,
"text": "GoLang-time"
},
{
"code": null,
"e": 1693,
"s": 1681,
"text": "Go Language"
},
{
"code": null,
"e": 1791,
"s": 1693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1820,
"s": 1791,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 1875,
"s": 1820,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 1896,
"s": 1875,
"text": "Structures in Golang"
},
{
"code": null,
"e": 1917,
"s": 1896,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 1942,
"s": 1917,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 1965,
"s": 1942,
"text": "Constants- Go Language"
},
{
"code": null,
"e": 1983,
"s": 1965,
"text": "Strings in Golang"
},
{
"code": null,
"e": 2029,
"s": 1983,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 2042,
"s": 2029,
"text": "Go Variables"
}
] |
Changing Nginx Port in Linux - GeeksforGeeks | 24 Feb, 2021
Nginx, written by Igor Sysoev and released on October 4th, 2003, is a fast, open-source multi-functional web server. It also acts as a reverse proxy and loads balancer, apart from being a web server, allowing it to handle large numbers of concurrent HTTP connections and is mostly preferred to Apache in the hosting of high-traffic enterprise websites. It is used in high-traffic websites such as Netflix and Dropbox to deliver their content in a quick, reliable, and secure manner.
By default, the Nginx HTTP server listens for inbound connections and connects to port 80, which is the default web port. However, the TLS configuration, which is not supported in Nginx by default, listens to port 443 for secure connections.
You need to look at a single directory to adjust Nginx’s default port number, unlike Apache2 this is Nginx’s default virtual host directory /etc/nginx/sites-available. This is where you can find individual virtual host configuration files in this directory.
Let’s change the port with stepwise implementation:
Step 1: First, run the commands below to open the port.conf file
$ sudo nano /etc/nginx/sites-available/default
Open config file
Step 2: Then change the Listen line from 80 to 8082
Change Nginx port
Now change the port number:
Change the port to 8082
Step 3: Now that you’ve changed the port number in the config files, run the commands below to restart Nginx.
$ sudo systemctl restart nginx.service
Restart Nginx
Step 4: Check the table of local network sockets with the netstat or ss command. Port 8082 should be shown on the local network table of your computer.
$ netstat -tlpn| grep nginx
OR
$ ss -tlpn| grep nginx
Check the port
Open a window and navigate to your server’s IP address or domain name on port 8082 to verify if the webserver can be accessed from the computers on your network. As seen in the screenshot below, you can see the default Nginx web page.
Check port in browser
Picked
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
scp command in Linux with Examples
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Basic Operators in Shell Scripting
SED command in Linux | Set 2
Docker - COPY Instruction
Named Pipe or FIFO with example C program | [
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 24889,
"s": 24406,
"text": "Nginx, written by Igor Sysoev and released on October 4th, 2003, is a fast, open-source multi-functional web server. It also acts as a reverse proxy and loads balancer, apart from being a web server, allowing it to handle large numbers of concurrent HTTP connections and is mostly preferred to Apache in the hosting of high-traffic enterprise websites. It is used in high-traffic websites such as Netflix and Dropbox to deliver their content in a quick, reliable, and secure manner."
},
{
"code": null,
"e": 25131,
"s": 24889,
"text": "By default, the Nginx HTTP server listens for inbound connections and connects to port 80, which is the default web port. However, the TLS configuration, which is not supported in Nginx by default, listens to port 443 for secure connections."
},
{
"code": null,
"e": 25389,
"s": 25131,
"text": "You need to look at a single directory to adjust Nginx’s default port number, unlike Apache2 this is Nginx’s default virtual host directory /etc/nginx/sites-available. This is where you can find individual virtual host configuration files in this directory."
},
{
"code": null,
"e": 25441,
"s": 25389,
"text": "Let’s change the port with stepwise implementation:"
},
{
"code": null,
"e": 25506,
"s": 25441,
"text": "Step 1: First, run the commands below to open the port.conf file"
},
{
"code": null,
"e": 25553,
"s": 25506,
"text": "$ sudo nano /etc/nginx/sites-available/default"
},
{
"code": null,
"e": 25570,
"s": 25553,
"text": "Open config file"
},
{
"code": null,
"e": 25622,
"s": 25570,
"text": "Step 2: Then change the Listen line from 80 to 8082"
},
{
"code": null,
"e": 25640,
"s": 25622,
"text": "Change Nginx port"
},
{
"code": null,
"e": 25668,
"s": 25640,
"text": "Now change the port number:"
},
{
"code": null,
"e": 25692,
"s": 25668,
"text": "Change the port to 8082"
},
{
"code": null,
"e": 25802,
"s": 25692,
"text": "Step 3: Now that you’ve changed the port number in the config files, run the commands below to restart Nginx."
},
{
"code": null,
"e": 25841,
"s": 25802,
"text": "$ sudo systemctl restart nginx.service"
},
{
"code": null,
"e": 25855,
"s": 25841,
"text": "Restart Nginx"
},
{
"code": null,
"e": 26007,
"s": 25855,
"text": "Step 4: Check the table of local network sockets with the netstat or ss command. Port 8082 should be shown on the local network table of your computer."
},
{
"code": null,
"e": 26061,
"s": 26007,
"text": "$ netstat -tlpn| grep nginx\nOR\n$ ss -tlpn| grep nginx"
},
{
"code": null,
"e": 26076,
"s": 26061,
"text": "Check the port"
},
{
"code": null,
"e": 26311,
"s": 26076,
"text": "Open a window and navigate to your server’s IP address or domain name on port 8082 to verify if the webserver can be accessed from the computers on your network. As seen in the screenshot below, you can see the default Nginx web page."
},
{
"code": null,
"e": 26333,
"s": 26311,
"text": "Check port in browser"
},
{
"code": null,
"e": 26340,
"s": 26333,
"text": "Picked"
},
{
"code": null,
"e": 26364,
"s": 26340,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26375,
"s": 26364,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26394,
"s": 26375,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26492,
"s": 26394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26501,
"s": 26492,
"text": "Comments"
},
{
"code": null,
"e": 26514,
"s": 26501,
"text": "Old Comments"
},
{
"code": null,
"e": 26540,
"s": 26514,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26577,
"s": 26540,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26612,
"s": 26577,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26649,
"s": 26612,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26689,
"s": 26649,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26723,
"s": 26689,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26758,
"s": 26723,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 26787,
"s": 26758,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26813,
"s": 26787,
"text": "Docker - COPY Instruction"
}
] |
How to create ACF plot in R? | The autocorrelation plot or ACF plot is a display of serial correlation in data that changes over time. The ACF plot can be easily created by using acf function.
For example, if we have a vector called V then we can create its autocorrelation plot by using the command given below −
acf(V)
Check out the below examples to understand how it can be done.
To create ACF plot in R, use the code given below −
x<-sample(1:9,10,replace=TRUE)
x
If you execute the above given code, it generates the following output −
[1] 2 5 6 7 1 7 9 3 9 7
To create ACF plot in R, add the following code to the above snippet −
x<-sample(1:9,10,replace=TRUE)
acf(x)
If you execute all the above given codes as a single program, it generates the following output −
To create ACF plot in R, use the code given below −
y<-rpois(10,5)
y
If you execute the above given code, it generates the following output −
[1] 7 5 2 4 7 3 2 6 8 5
To create ACF plot in R, add the following code to the above snippet −
y<-rpois(10,5)
acf(y)
If you execute all the above given codes as a single program, it generates the following output − | [
{
"code": null,
"e": 1224,
"s": 1062,
"text": "The autocorrelation plot or ACF plot is a display of serial correlation in data that changes over time. The ACF plot can be easily created by using acf function."
},
{
"code": null,
"e": 1345,
"s": 1224,
"text": "For example, if we have a vector called V then we can create its autocorrelation plot by using the command given below −"
},
{
"code": null,
"e": 1352,
"s": 1345,
"text": "acf(V)"
},
{
"code": null,
"e": 1415,
"s": 1352,
"text": "Check out the below examples to understand how it can be done."
},
{
"code": null,
"e": 1467,
"s": 1415,
"text": "To create ACF plot in R, use the code given below −"
},
{
"code": null,
"e": 1500,
"s": 1467,
"text": "x<-sample(1:9,10,replace=TRUE)\nx"
},
{
"code": null,
"e": 1573,
"s": 1500,
"text": "If you execute the above given code, it generates the following output −"
},
{
"code": null,
"e": 1598,
"s": 1573,
"text": "[1] 2 5 6 7 1 7 9 3 9 7\n"
},
{
"code": null,
"e": 1669,
"s": 1598,
"text": "To create ACF plot in R, add the following code to the above snippet −"
},
{
"code": null,
"e": 1707,
"s": 1669,
"text": "x<-sample(1:9,10,replace=TRUE)\nacf(x)"
},
{
"code": null,
"e": 1805,
"s": 1707,
"text": "If you execute all the above given codes as a single program, it generates the following output −"
},
{
"code": null,
"e": 1857,
"s": 1805,
"text": "To create ACF plot in R, use the code given below −"
},
{
"code": null,
"e": 1874,
"s": 1857,
"text": "y<-rpois(10,5)\ny"
},
{
"code": null,
"e": 1947,
"s": 1874,
"text": "If you execute the above given code, it generates the following output −"
},
{
"code": null,
"e": 1972,
"s": 1947,
"text": "[1] 7 5 2 4 7 3 2 6 8 5\n"
},
{
"code": null,
"e": 2043,
"s": 1972,
"text": "To create ACF plot in R, add the following code to the above snippet −"
},
{
"code": null,
"e": 2065,
"s": 2043,
"text": "y<-rpois(10,5)\nacf(y)"
},
{
"code": null,
"e": 2163,
"s": 2065,
"text": "If you execute all the above given codes as a single program, it generates the following output −"
}
] |
How to use onKeyPress event in ReactJS? - GeeksforGeeks | 25 Jan, 2021
The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers.
To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build an application that displays the key pressed in the input box.
Filename- App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useState } from 'react';
const App = () => {
const [state, setState] = useState('');
const handler = (event) => {
// changing the state to the name of the key
// which is pressed
setState(event.key);
};
return (
<div>
<h1>Hi Geeks!</h1>
<p>Key pressed is: {state}</p>
{/* Passing the key pressed to the handler function */}
<input type="text" onKeyPress={(e) => handler(e)} />
</div>
);
};
export default App;
Note: You can define your own styling in the App.css file.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Picked
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to redirect to another page in ReactJS ?
How to pass data from one component to other component in ReactJS ?
React-Router Hooks
Re-rendering Components in ReactJS
How to set background images in ReactJS ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24450,
"s": 24419,
"text": " \n25 Jan, 2021\n"
},
{
"code": null,
"e": 24610,
"s": 24450,
"text": "The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers."
},
{
"code": null,
"e": 24695,
"s": 24610,
"text": "To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method."
},
{
"code": null,
"e": 24723,
"s": 24695,
"text": "Creating React Application:"
},
{
"code": null,
"e": 24787,
"s": 24723,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 24821,
"s": 24787,
"text": "npx create-react-app functiondemo"
},
{
"code": null,
"e": 24923,
"s": 24821,
"text": "Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:"
},
{
"code": null,
"e": 24939,
"s": 24923,
"text": "cd functiondemo"
},
{
"code": null,
"e": 24991,
"s": 24939,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 25009,
"s": 24991,
"text": "Project Structure"
},
{
"code": null,
"e": 25120,
"s": 25009,
"text": "Example: In this example, we are going to build an application that displays the key pressed in the input box."
},
{
"code": null,
"e": 25259,
"s": 25120,
"text": "Filename- App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 25270,
"s": 25259,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\nimport React, { useState } from 'react'; \n \nconst App = () => { \n const [state, setState] = useState(''); \n \n const handler = (event) => { \n // changing the state to the name of the key \n // which is pressed \n setState(event.key); \n }; \n \n return ( \n <div> \n <h1>Hi Geeks!</h1> \n \n<p>Key pressed is: {state}</p> \n \n \n {/* Passing the key pressed to the handler function */} \n <input type=\"text\" onKeyPress={(e) => handler(e)} /> \n \n </div> \n ); \n}; \n \nexport default App; \n\n\n\n\n\n",
"e": 25833,
"s": 25280,
"text": null
},
{
"code": null,
"e": 25892,
"s": 25833,
"text": "Note: You can define your own styling in the App.css file."
},
{
"code": null,
"e": 26005,
"s": 25892,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 26015,
"s": 26005,
"text": "npm start"
},
{
"code": null,
"e": 26024,
"s": 26015,
"text": "Output: "
},
{
"code": null,
"e": 26033,
"s": 26024,
"text": "\nPicked\n"
},
{
"code": null,
"e": 26043,
"s": 26033,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 26062,
"s": 26043,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 26267,
"s": 26062,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26312,
"s": 26267,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 26380,
"s": 26312,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 26399,
"s": 26380,
"text": "React-Router Hooks"
},
{
"code": null,
"e": 26434,
"s": 26399,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 26476,
"s": 26434,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 26518,
"s": 26476,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26551,
"s": 26518,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26601,
"s": 26551,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26663,
"s": 26601,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Print stack trace in Java | In order to print the stack trace in Java, we use the java.lang.Throwable.printStackTrace() method. The printStackTrace() method prints the throwable and its backtrace in the standard error stream.
Declaration - The java.lang.Throwable.printStackTrace() method is declared as follows −
public void printStackTrace()
Let us see a program to print the stack trace in Java.
Live Demo
public class Example {
public static void main(String args[]) throws Throwable {
try {
int n = 3;
System.out.println(n/0);
} catch (ArithmeticException e) {
System.out.println("Printing stack trace...");
e.printStackTrace(); // prints the stack trace
}
}
}
Printing stack trace...
java.lang.ArithmeticException: / by zero
at Example.main(Example.java:8) | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "In order to print the stack trace in Java, we use the java.lang.Throwable.printStackTrace() method. The printStackTrace() method prints the throwable and its backtrace in the standard error stream."
},
{
"code": null,
"e": 1348,
"s": 1260,
"text": "Declaration - The java.lang.Throwable.printStackTrace() method is declared as follows −"
},
{
"code": null,
"e": 1378,
"s": 1348,
"text": "public void printStackTrace()"
},
{
"code": null,
"e": 1433,
"s": 1378,
"text": "Let us see a program to print the stack trace in Java."
},
{
"code": null,
"e": 1444,
"s": 1433,
"text": " Live Demo"
},
{
"code": null,
"e": 1761,
"s": 1444,
"text": "public class Example {\n public static void main(String args[]) throws Throwable {\n try {\n int n = 3;\n System.out.println(n/0);\n } catch (ArithmeticException e) {\n System.out.println(\"Printing stack trace...\");\n e.printStackTrace(); // prints the stack trace\n }\n }\n}"
},
{
"code": null,
"e": 1858,
"s": 1761,
"text": "Printing stack trace...\njava.lang.ArithmeticException: / by zero\nat Example.main(Example.java:8)"
}
] |
How can we modify a MySQL view with CREATE OR REPLACE VIEW statement? | As we know that we can modify a view by using ALTER VIEW statement but other than that we can also use CREATE OR REPLACE VIEW to modify an existing view. The concept is simple as MySQL simply modifies the view if it already exists otherwise a new view would be created. Following is the syntax of it −
CREATE OR REPLACE VIEW view_name AS Select_statements FROM table;
mysql> Create OR Replace VIEW Info AS Select Id, Name, Address, Subject from student_info WHERE Subject = 'Computers';
Query OK, 0 rows affected (0.46 sec)
The above query will create or replace a view ‘Info’. It will be created if not existed already otherwise it would get replaced by a new definition given in the above query. | [
{
"code": null,
"e": 1364,
"s": 1062,
"text": "As we know that we can modify a view by using ALTER VIEW statement but other than that we can also use CREATE OR REPLACE VIEW to modify an existing view. The concept is simple as MySQL simply modifies the view if it already exists otherwise a new view would be created. Following is the syntax of it −"
},
{
"code": null,
"e": 1430,
"s": 1364,
"text": "CREATE OR REPLACE VIEW view_name AS Select_statements FROM table;"
},
{
"code": null,
"e": 1586,
"s": 1430,
"text": "mysql> Create OR Replace VIEW Info AS Select Id, Name, Address, Subject from student_info WHERE Subject = 'Computers';\nQuery OK, 0 rows affected (0.46 sec)"
},
{
"code": null,
"e": 1760,
"s": 1586,
"text": "The above query will create or replace a view ‘Info’. It will be created if not existed already otherwise it would get replaced by a new definition given in the above query."
}
] |
How to correctly sort a string with a number inside in Python? | This type of sort in which you want to sort on the basis of numbers within string is called natural sort or human sort. For example, if you have the text:
['Hello1','Hello12', 'Hello29', 'Hello2', 'Hello17', 'Hello25']
Then you want the sorted list to be:
['Hello1', 'Hello2','Hello12', 'Hello17', 'Hello25', 'Hello29']
and not:
['Hello1','Hello12', 'Hello17', 'Hello2', 'Hello25', 'Hello29']
To do this we can use the extra parameter that sort() uses. This is a function that is called to calculate the key from the entry in the list. We use regex to extract the number from the string and sort on both text and number.
import re
def atoi(text):
return int(text) if text.isdigit() elsetext
def natural_keys(text):
return [ atoi(c) for c in re.split('(\d+)',text) ]
my_list =['Hello1', 'Hello12', 'Hello29', 'Hello2', 'Hello17', 'Hello25']
my_list.sort(key=natural_keys)
print my_list
This will give you the output:
['Hello1','Hello2', 'Hello12', 'Hello17', 'Hello25', 'Hello29'] | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "This type of sort in which you want to sort on the basis of numbers within string is called natural sort or human sort. For example, if you have the text:"
},
{
"code": null,
"e": 1281,
"s": 1217,
"text": "['Hello1','Hello12', 'Hello29', 'Hello2', 'Hello17', 'Hello25']"
},
{
"code": null,
"e": 1319,
"s": 1281,
"text": " Then you want the sorted list to be:"
},
{
"code": null,
"e": 1383,
"s": 1319,
"text": "['Hello1', 'Hello2','Hello12', 'Hello17', 'Hello25', 'Hello29']"
},
{
"code": null,
"e": 1393,
"s": 1383,
"text": " and not:"
},
{
"code": null,
"e": 1457,
"s": 1393,
"text": "['Hello1','Hello12', 'Hello17', 'Hello2', 'Hello25', 'Hello29']"
},
{
"code": null,
"e": 1687,
"s": 1457,
"text": " To do this we can use the extra parameter that sort() uses. This is a function that is called to calculate the key from the entry in the list. We use regex to extract the number from the string and sort on both text and number. "
},
{
"code": null,
"e": 1963,
"s": 1687,
"text": " import re\n def atoi(text):\n return int(text) if text.isdigit() elsetext\ndef natural_keys(text):\n return [ atoi(c) for c in re.split('(\\d+)',text) ]\n my_list =['Hello1', 'Hello12', 'Hello29', 'Hello2', 'Hello17', 'Hello25']\n my_list.sort(key=natural_keys)\nprint my_list"
},
{
"code": null,
"e": 1995,
"s": 1963,
"text": " This will give you the output:"
},
{
"code": null,
"e": 2059,
"s": 1995,
"text": "['Hello1','Hello2', 'Hello12', 'Hello17', 'Hello25', 'Hello29']"
}
] |
Can we change the Cursor with Java Swing? | Yes, we can change the default cursor representation in Java. Let us first create a button component −
JButton button = new JButton("Button with two borders");
Whenever user will keep the mouse cursor on the above button component, the cursor would change to hand cursor −
Cursor cursor = button.getCursor();
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
The following is an example to change the cursor −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class SwingDemo {
public static void main(String args[]) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Border raisedBorder = new EtchedBorder(EtchedBorder.RAISED);
LineBorder lineBorder = new LineBorder(Color.red);
TitledBorder titleBorder = new TitledBorder("Demo Title");
Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder);
JButton raisedButton = new JButton("Raised Border");
raisedButton.setBorder(raisedBorder);
JButton button = new JButton("Button with two borders");
button.setBorder(border);
Cursor cursor = button.getCursor();
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Container contentPane = frame.getContentPane();
contentPane.add(raisedButton,BorderLayout.WEST);
contentPane.add(button,BorderLayout.EAST);
frame.setSize(600, 300);
frame.setVisible(true);
}
}
The output is as follows. When you will keep the cursor on the button with two borders, then hand cursor will be visible as shown below − | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "Yes, we can change the default cursor representation in Java. Let us first create a button component −"
},
{
"code": null,
"e": 1222,
"s": 1165,
"text": "JButton button = new JButton(\"Button with two borders\");"
},
{
"code": null,
"e": 1335,
"s": 1222,
"text": "Whenever user will keep the mouse cursor on the above button component, the cursor would change to hand cursor −"
},
{
"code": null,
"e": 1437,
"s": 1335,
"text": "Cursor cursor = button.getCursor();\nbutton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));"
},
{
"code": null,
"e": 1488,
"s": 1437,
"text": "The following is an example to change the cursor −"
},
{
"code": null,
"e": 2825,
"s": 1488,
"text": "package my;\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Container;\nimport java.awt.Cursor;\nimport javax.swing.BorderFactory;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.border.Border;\nimport javax.swing.border.EtchedBorder;\nimport javax.swing.border.LineBorder;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n Border raisedBorder = new EtchedBorder(EtchedBorder.RAISED);\n LineBorder lineBorder = new LineBorder(Color.red);\n TitledBorder titleBorder = new TitledBorder(\"Demo Title\");\n Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder);\n JButton raisedButton = new JButton(\"Raised Border\");\n raisedButton.setBorder(raisedBorder);\n JButton button = new JButton(\"Button with two borders\");\n button.setBorder(border);\n Cursor cursor = button.getCursor();\n button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));\n Container contentPane = frame.getContentPane();\n contentPane.add(raisedButton,BorderLayout.WEST);\n contentPane.add(button,BorderLayout.EAST);\n frame.setSize(600, 300);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2963,
"s": 2825,
"text": "The output is as follows. When you will keep the cursor on the button with two borders, then hand cursor will be visible as shown below −"
}
] |
Batch Script - COMP | This batch command compares 2 files based on the file size.
COMP [sourceA] [sourceB]
Wherein sourceA and sourceB are the files which need to be compared.
@echo off
COMP C:\tp\lists.txt C:\tp\listsA.txt
The above command will compare the files lists.txt and listsA.txt and find out if the two file sizes are different.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2229,
"s": 2169,
"text": "This batch command compares 2 files based on the file size."
},
{
"code": null,
"e": 2255,
"s": 2229,
"text": "COMP [sourceA] [sourceB]\n"
},
{
"code": null,
"e": 2324,
"s": 2255,
"text": "Wherein sourceA and sourceB are the files which need to be compared."
},
{
"code": null,
"e": 2373,
"s": 2324,
"text": "@echo off \nCOMP C:\\tp\\lists.txt C:\\tp\\listsA.txt"
},
{
"code": null,
"e": 2489,
"s": 2373,
"text": "The above command will compare the files lists.txt and listsA.txt and find out if the two file sizes are different."
},
{
"code": null,
"e": 2496,
"s": 2489,
"text": " Print"
},
{
"code": null,
"e": 2507,
"s": 2496,
"text": " Add Notes"
}
] |
C++ Program for converting hours into minutes and seconds | Given with the input as hours and the task is to convert the number of hours into minutes and seconds and display the corresponding result
Formula used for converting the hours into minutes and seconds is −
1 hour = 60 minutes
Minutes = hours * 60
1 hour = 3600 seconds
Seconds = hours * 3600
Input-: hours = 3
Output-: 3 hours in minutes are 180
3 hours in seconds are 10800
Input-: hours = 5
Output-: 5 hours in minutes are 300
5 hours in seconds are 18000
Approach used in the below program is as follows −
Input the number of hours in an integer variable let’s say n
Apply the formula of conversion given above to convert hours into minutes and seconds
Display the result
START
Step 1-> declare function to convert hours into minutes and seconds
void convert(int hours)
declare long long int minutes, seconds
set minutes = hours * 60
set seconds = hours * 3600
print minute and seconds
step 2-> In main()
declare variable as int hours = 3
Call convert(hours)
STOP
#include <bits/stdc++.h>
using namespace std;
//convert hours into minutes and seconds
void convert(int hours) {
long long int minutes, seconds;
minutes = hours * 60;
seconds = hours * 3600;
cout<<hours<<" hours in minutes are "<<minutes<<endl<<hours<<" hours in seconds are "<<seconds;
}
int main() {
int hours = 3;
convert(hours);
return 0;
}
3 hours in minutes are 180
3 hours in seconds are 10800 | [
{
"code": null,
"e": 1201,
"s": 1062,
"text": "Given with the input as hours and the task is to convert the number of hours into minutes and seconds and display the corresponding result"
},
{
"code": null,
"e": 1269,
"s": 1201,
"text": "Formula used for converting the hours into minutes and seconds is −"
},
{
"code": null,
"e": 1361,
"s": 1269,
"text": "1 hour = 60 minutes\n Minutes = hours * 60\n1 hour = 3600 seconds\n Seconds = hours * 3600"
},
{
"code": null,
"e": 1533,
"s": 1361,
"text": "Input-: hours = 3\nOutput-: 3 hours in minutes are 180\n 3 hours in seconds are 10800\nInput-: hours = 5\nOutput-: 5 hours in minutes are 300\n 5 hours in seconds are 18000"
},
{
"code": null,
"e": 1584,
"s": 1533,
"text": "Approach used in the below program is as follows −"
},
{
"code": null,
"e": 1645,
"s": 1584,
"text": "Input the number of hours in an integer variable let’s say n"
},
{
"code": null,
"e": 1731,
"s": 1645,
"text": "Apply the formula of conversion given above to convert hours into minutes and seconds"
},
{
"code": null,
"e": 1750,
"s": 1731,
"text": "Display the result"
},
{
"code": null,
"e": 2063,
"s": 1750,
"text": "START\nStep 1-> declare function to convert hours into minutes and seconds\n void convert(int hours)\n declare long long int minutes, seconds\n set minutes = hours * 60\n set seconds = hours * 3600\n print minute and seconds\nstep 2-> In main()\n declare variable as int hours = 3\n Call convert(hours)\nSTOP"
},
{
"code": null,
"e": 2436,
"s": 2063,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n//convert hours into minutes and seconds\nvoid convert(int hours) {\n long long int minutes, seconds;\n minutes = hours * 60;\n seconds = hours * 3600;\n cout<<hours<<\" hours in minutes are \"<<minutes<<endl<<hours<<\" hours in seconds are \"<<seconds;\n}\nint main() {\n int hours = 3;\n convert(hours);\n return 0;\n}"
},
{
"code": null,
"e": 2492,
"s": 2436,
"text": "3 hours in minutes are 180\n3 hours in seconds are 10800"
}
] |
Auto-Generated Knowledge Graphs, extract linked data from unstructured text | Towards Data Science | Knowledge graphs are a tool of data science that deal with interconnected entities (people, organizations, places, events, etc.). Entities are the nodes which are connected via edges. Knowledge graphs consist of these entity pairs that can be traversed to uncover meaningful connections in unstructured data.
There are issues inherent with graph databases, one being the manual effort required to construct them. In this article I will discuss my research and implementations of automatic generation using web scraping bots, computational linguistics, natural language processing (NLP) algorithms and graph theory (with python code provided).
The first step in constructing a knowledge graph is to gather your sources. One document may be enough for some purposes, but if you want to go deeper and crawl the web for more information there are multiple ways to achieve this using web scraping. Wikipedia is a decent starting point, as the site functions as a user-generated content database with citations to mostly reliable secondary sources, which vet data from primary sources.
Side Note: Always check your sources. Believe it or not, not all information on the internet is true! For a heuristic based solution, cross-reference other sites or opt for SEO metrics as a proxy for trust-signals.
I will avoid screen-scraping wherever possible by using a direct python wrapper for the Wikipedia API.
The following function searches Wikipedia for a given topic and extracts information from the target page and its internal links.
Let’s test this function on the topic: “Financial crisis of 2007–08”
wiki_data = wiki_scrape('Financial crisis of 2007–08')
Output:
Wikipedia pages scraped: 798
If you want to extract a single page use the below function:
Knowledge graphs can be constructed automatically from text using part-of-speech and dependency parsing. The extraction of entity pairs from grammatical patterns is fast and scalable to large amounts of text using NLP library SpaCy.
The following function defines entity pairs as entities/noun chunks with subject — object dependencies connected by a root verb. Other rules-of-thumb can be used to produce different types of connections. This kind of connection can be referred to as a subject-predicate-object triple.
Call the function on the main topic page:
pairs = get_entity_pairs(wiki_data.loc[0,'text'])
Output:
Entity pairs extracted: 71
Coreference resolution significantly improves entity pair extraction by normalizing the text, removing redundancies, and assigning entities to pronouns (see my article on coreference resolution below).
towardsdatascience.com
It may also be worthwhile to train a custom entity recognizer model if your use-case is domain-specific (healthcare, legal, scientific).
Next, lets draw the network using the NetworkX library. I will create a directed multigraph network with nodes sized in proportion to degree centrality.
draw_kg(pairs)
If a drawn graph becomes unintelligible we can increase the figure size or filter/query.
filter_graph(pairs, 'Congress')
To effectively use the entire corpus of ~800 Wikipedia pages for our topic, use the columns created in the wiki_scrape function to add properties to each node, then you can track which pages and categories each node lies in.
I recommend using multiprocessing or parallel processing to reduce execution time.
Knowledge graphs on a large scale are at the frontier of AI research. Alas, real-world knowledge is not structured neatly into a schema but rather unstructured, messy, and organic. | [
{
"code": null,
"e": 480,
"s": 171,
"text": "Knowledge graphs are a tool of data science that deal with interconnected entities (people, organizations, places, events, etc.). Entities are the nodes which are connected via edges. Knowledge graphs consist of these entity pairs that can be traversed to uncover meaningful connections in unstructured data."
},
{
"code": null,
"e": 814,
"s": 480,
"text": "There are issues inherent with graph databases, one being the manual effort required to construct them. In this article I will discuss my research and implementations of automatic generation using web scraping bots, computational linguistics, natural language processing (NLP) algorithms and graph theory (with python code provided)."
},
{
"code": null,
"e": 1251,
"s": 814,
"text": "The first step in constructing a knowledge graph is to gather your sources. One document may be enough for some purposes, but if you want to go deeper and crawl the web for more information there are multiple ways to achieve this using web scraping. Wikipedia is a decent starting point, as the site functions as a user-generated content database with citations to mostly reliable secondary sources, which vet data from primary sources."
},
{
"code": null,
"e": 1466,
"s": 1251,
"text": "Side Note: Always check your sources. Believe it or not, not all information on the internet is true! For a heuristic based solution, cross-reference other sites or opt for SEO metrics as a proxy for trust-signals."
},
{
"code": null,
"e": 1569,
"s": 1466,
"text": "I will avoid screen-scraping wherever possible by using a direct python wrapper for the Wikipedia API."
},
{
"code": null,
"e": 1699,
"s": 1569,
"text": "The following function searches Wikipedia for a given topic and extracts information from the target page and its internal links."
},
{
"code": null,
"e": 1768,
"s": 1699,
"text": "Let’s test this function on the topic: “Financial crisis of 2007–08”"
},
{
"code": null,
"e": 1823,
"s": 1768,
"text": "wiki_data = wiki_scrape('Financial crisis of 2007–08')"
},
{
"code": null,
"e": 1831,
"s": 1823,
"text": "Output:"
},
{
"code": null,
"e": 1860,
"s": 1831,
"text": "Wikipedia pages scraped: 798"
},
{
"code": null,
"e": 1921,
"s": 1860,
"text": "If you want to extract a single page use the below function:"
},
{
"code": null,
"e": 2154,
"s": 1921,
"text": "Knowledge graphs can be constructed automatically from text using part-of-speech and dependency parsing. The extraction of entity pairs from grammatical patterns is fast and scalable to large amounts of text using NLP library SpaCy."
},
{
"code": null,
"e": 2440,
"s": 2154,
"text": "The following function defines entity pairs as entities/noun chunks with subject — object dependencies connected by a root verb. Other rules-of-thumb can be used to produce different types of connections. This kind of connection can be referred to as a subject-predicate-object triple."
},
{
"code": null,
"e": 2482,
"s": 2440,
"text": "Call the function on the main topic page:"
},
{
"code": null,
"e": 2532,
"s": 2482,
"text": "pairs = get_entity_pairs(wiki_data.loc[0,'text'])"
},
{
"code": null,
"e": 2540,
"s": 2532,
"text": "Output:"
},
{
"code": null,
"e": 2567,
"s": 2540,
"text": "Entity pairs extracted: 71"
},
{
"code": null,
"e": 2769,
"s": 2567,
"text": "Coreference resolution significantly improves entity pair extraction by normalizing the text, removing redundancies, and assigning entities to pronouns (see my article on coreference resolution below)."
},
{
"code": null,
"e": 2792,
"s": 2769,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2929,
"s": 2792,
"text": "It may also be worthwhile to train a custom entity recognizer model if your use-case is domain-specific (healthcare, legal, scientific)."
},
{
"code": null,
"e": 3082,
"s": 2929,
"text": "Next, lets draw the network using the NetworkX library. I will create a directed multigraph network with nodes sized in proportion to degree centrality."
},
{
"code": null,
"e": 3097,
"s": 3082,
"text": "draw_kg(pairs)"
},
{
"code": null,
"e": 3186,
"s": 3097,
"text": "If a drawn graph becomes unintelligible we can increase the figure size or filter/query."
},
{
"code": null,
"e": 3218,
"s": 3186,
"text": "filter_graph(pairs, 'Congress')"
},
{
"code": null,
"e": 3443,
"s": 3218,
"text": "To effectively use the entire corpus of ~800 Wikipedia pages for our topic, use the columns created in the wiki_scrape function to add properties to each node, then you can track which pages and categories each node lies in."
},
{
"code": null,
"e": 3526,
"s": 3443,
"text": "I recommend using multiprocessing or parallel processing to reduce execution time."
}
] |
forward_list::unique() in C++ STL - GeeksforGeeks | 09 Oct, 2019
forward_list::unique() is an inbuilt function in C++ STL which removes all consecutive duplicate elements from the forward_list. It uses binary predicate for comparison.
Syntax:
forwardlist_name.unique(BinaryPredicate name)
Parameters: The function accepts a single parameter which is a binary predicate that returns true if the elements should be treated as equal. It has following syntax:
bool name(data_type a, data_type a)
Return value: The function does not return anything.
// C++ program to illustrate the// unique() function#include <bits/stdc++.h>using namespace std; // Function for binary_predicate/*bool compare(int a, int b){ return (abs(a) == abs(b));}// This function can also be used and passed inside// unique(), to get the same result*/ int main(){ forward_list<int> list = { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 2, 4, 4 }; cout << "List of elements before unique operation is: "; // starts from the first element of the list to the last for (auto it = list.begin(); it != list.end(); ++it) cout << *it << " "; // unique operation on forward list list.unique(); cout << "\nList of elements after unique operation is: "; // starts from the first element of the list to the last for (auto it = list.begin(); it != list.end(); ++it) cout << *it << " "; return 0;}
List of elements before unique operation is: 1 1 1 1 2 2 2 2 3 3 3 2 4 4
List of elements after unique operation is: 1 2 3 2 4
babaurbeautiful
CPP-forward-list
CPP-Functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples | [
{
"code": null,
"e": 24700,
"s": 24672,
"text": "\n09 Oct, 2019"
},
{
"code": null,
"e": 24870,
"s": 24700,
"text": "forward_list::unique() is an inbuilt function in C++ STL which removes all consecutive duplicate elements from the forward_list. It uses binary predicate for comparison."
},
{
"code": null,
"e": 24878,
"s": 24870,
"text": "Syntax:"
},
{
"code": null,
"e": 24924,
"s": 24878,
"text": "forwardlist_name.unique(BinaryPredicate name)"
},
{
"code": null,
"e": 25091,
"s": 24924,
"text": "Parameters: The function accepts a single parameter which is a binary predicate that returns true if the elements should be treated as equal. It has following syntax:"
},
{
"code": null,
"e": 25127,
"s": 25091,
"text": "bool name(data_type a, data_type a)"
},
{
"code": null,
"e": 25180,
"s": 25127,
"text": "Return value: The function does not return anything."
},
{
"code": "// C++ program to illustrate the// unique() function#include <bits/stdc++.h>using namespace std; // Function for binary_predicate/*bool compare(int a, int b){ return (abs(a) == abs(b));}// This function can also be used and passed inside// unique(), to get the same result*/ int main(){ forward_list<int> list = { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 2, 4, 4 }; cout << \"List of elements before unique operation is: \"; // starts from the first element of the list to the last for (auto it = list.begin(); it != list.end(); ++it) cout << *it << \" \"; // unique operation on forward list list.unique(); cout << \"\\nList of elements after unique operation is: \"; // starts from the first element of the list to the last for (auto it = list.begin(); it != list.end(); ++it) cout << *it << \" \"; return 0;}",
"e": 26036,
"s": 25180,
"text": null
},
{
"code": null,
"e": 26165,
"s": 26036,
"text": "List of elements before unique operation is: 1 1 1 1 2 2 2 2 3 3 3 2 4 4 \nList of elements after unique operation is: 1 2 3 2 4\n"
},
{
"code": null,
"e": 26181,
"s": 26165,
"text": "babaurbeautiful"
},
{
"code": null,
"e": 26198,
"s": 26181,
"text": "CPP-forward-list"
},
{
"code": null,
"e": 26212,
"s": 26198,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26216,
"s": 26212,
"text": "STL"
},
{
"code": null,
"e": 26220,
"s": 26216,
"text": "C++"
},
{
"code": null,
"e": 26224,
"s": 26220,
"text": "STL"
},
{
"code": null,
"e": 26228,
"s": 26224,
"text": "CPP"
},
{
"code": null,
"e": 26326,
"s": 26228,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26335,
"s": 26326,
"text": "Comments"
},
{
"code": null,
"e": 26348,
"s": 26335,
"text": "Old Comments"
},
{
"code": null,
"e": 26367,
"s": 26348,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26410,
"s": 26367,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26434,
"s": 26410,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26462,
"s": 26434,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26490,
"s": 26462,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26517,
"s": 26490,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26552,
"s": 26517,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26576,
"s": 26552,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 26596,
"s": 26576,
"text": "Constructors in C++"
}
] |
How to do date validation in Python? | The date validation you want to achieve in python will largely depend on the format of the date you have. The strptime function from the datetime library can be used to parse strings to dates/times.
import datetime
date_string = '2017-12-31'
date_format = '%Y-%m-%d'
try:
date_obj = datetime.datetime.strptime(date_string, date_format)
print(date_obj)
except ValueError:
print("Incorrect data format, should be YYYY-MM-DD")
This will give the output −
2017-12-31 00:00:00
You can use many other directives to parse the date. Following are the directives supported by strptime()'s format string. | [
{
"code": null,
"e": 1261,
"s": 1062,
"text": "The date validation you want to achieve in python will largely depend on the format of the date you have. The strptime function from the datetime library can be used to parse strings to dates/times."
},
{
"code": null,
"e": 1492,
"s": 1261,
"text": "import datetime\ndate_string = '2017-12-31'\ndate_format = '%Y-%m-%d'\ntry:\n date_obj = datetime.datetime.strptime(date_string, date_format)\n print(date_obj)\nexcept ValueError:\n print(\"Incorrect data format, should be YYYY-MM-DD\")"
},
{
"code": null,
"e": 1520,
"s": 1492,
"text": "This will give the output −"
},
{
"code": null,
"e": 1540,
"s": 1520,
"text": "2017-12-31 00:00:00"
},
{
"code": null,
"e": 1663,
"s": 1540,
"text": "You can use many other directives to parse the date. Following are the directives supported by strptime()'s format string."
}
] |
How to run Selenium WebDriver test cases in Chrome? | We can run Selenium webdriver test cases in Chrome browser. But before working with Chrome browser with Selenium we have to ensure that the Java JDK, any Java IDE like Eclipse and Selenium webdriver are configured in our system. Next we have to download the Chrome browser driver and configure it to our project by following the below step by step process −
Navigate to the link − https://chromedriver.chromium.org/downloads and there links shall be available to the multiple versions of the chromedriver.
Navigate to the link − https://chromedriver.chromium.org/downloads and there links shall be available to the multiple versions of the chromedriver.
As per the available version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where chrome drivers compatible with various operating systems shall be present.
As per the available version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where chrome drivers compatible with various operating systems shall be present.
After downloading the chromedriver as per the system configuration, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location.
After downloading the chromedriver as per the system configuration, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location.
Next we can configure the Chrome driver by any of the two ways −
With System Properties in the Environment Variables.
With System Properties in the Environment Variables.
With System Properties in the code.
With System Properties in the code.
Let us discuss how to configure chromedriver with System properties within the environment variables −
Navigate to Start and find the System and navigate to it. Then select Advanced System Settings. Next under Advanced Tab click on Environment Variables.
Navigate to Start and find the System and navigate to it. Then select Advanced System Settings. Next under Advanced Tab click on Environment Variables.
Select Path from the System Variables, then click on Edit. Inside the Edit environment variable pop up click on New.
Select Path from the System Variables, then click on Edit. Inside the Edit environment variable pop up click on New.
Now the path of the chromedriver.exe file is added, then click on OK.
Now the path of the chromedriver.exe file is added, then click on OK.
Code Implementation
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LaunchChrome{
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
}
}
Let us discuss how to configure chrome driver with System properties within the Selenium code −
Add the System.setProperty method in the code which takes the browser type and the path of the chrome driver executable path as parameters.
Add the System.setProperty method in the code which takes the browser type and the path of the chrome driver executable path as parameters.
System.setProperty("webdriver.chrome.driver","<chrome driver path>");
Code Implementation
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LaunchChromeBrowser{
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
// to configure the path of the chromedriver.exe
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
}
} | [
{
"code": null,
"e": 1420,
"s": 1062,
"text": "We can run Selenium webdriver test cases in Chrome browser. But before working with Chrome browser with Selenium we have to ensure that the Java JDK, any Java IDE like Eclipse and Selenium webdriver are configured in our system. Next we have to download the Chrome browser driver and configure it to our project by following the below step by step process −"
},
{
"code": null,
"e": 1568,
"s": 1420,
"text": "Navigate to the link − https://chromedriver.chromium.org/downloads and there links shall be available to the multiple versions of the chromedriver."
},
{
"code": null,
"e": 1716,
"s": 1568,
"text": "Navigate to the link − https://chromedriver.chromium.org/downloads and there links shall be available to the multiple versions of the chromedriver."
},
{
"code": null,
"e": 1933,
"s": 1716,
"text": "As per the available version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where chrome drivers compatible with various operating systems shall be present."
},
{
"code": null,
"e": 2150,
"s": 1933,
"text": "As per the available version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where chrome drivers compatible with various operating systems shall be present."
},
{
"code": null,
"e": 2319,
"s": 2150,
"text": "After downloading the chromedriver as per the system configuration, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location."
},
{
"code": null,
"e": 2488,
"s": 2319,
"text": "After downloading the chromedriver as per the system configuration, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location."
},
{
"code": null,
"e": 2553,
"s": 2488,
"text": "Next we can configure the Chrome driver by any of the two ways −"
},
{
"code": null,
"e": 2606,
"s": 2553,
"text": "With System Properties in the Environment Variables."
},
{
"code": null,
"e": 2659,
"s": 2606,
"text": "With System Properties in the Environment Variables."
},
{
"code": null,
"e": 2695,
"s": 2659,
"text": "With System Properties in the code."
},
{
"code": null,
"e": 2731,
"s": 2695,
"text": "With System Properties in the code."
},
{
"code": null,
"e": 2834,
"s": 2731,
"text": "Let us discuss how to configure chromedriver with System properties within the environment variables −"
},
{
"code": null,
"e": 2986,
"s": 2834,
"text": "Navigate to Start and find the System and navigate to it. Then select Advanced System Settings. Next under Advanced Tab click on Environment Variables."
},
{
"code": null,
"e": 3138,
"s": 2986,
"text": "Navigate to Start and find the System and navigate to it. Then select Advanced System Settings. Next under Advanced Tab click on Environment Variables."
},
{
"code": null,
"e": 3255,
"s": 3138,
"text": "Select Path from the System Variables, then click on Edit. Inside the Edit environment variable pop up click on New."
},
{
"code": null,
"e": 3372,
"s": 3255,
"text": "Select Path from the System Variables, then click on Edit. Inside the Edit environment variable pop up click on New."
},
{
"code": null,
"e": 3442,
"s": 3372,
"text": "Now the path of the chromedriver.exe file is added, then click on OK."
},
{
"code": null,
"e": 3512,
"s": 3442,
"text": "Now the path of the chromedriver.exe file is added, then click on OK."
},
{
"code": null,
"e": 3532,
"s": 3512,
"text": "Code Implementation"
},
{
"code": null,
"e": 3827,
"s": 3532,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class LaunchChrome{\n public static void main(String[] args) {\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n }\n}"
},
{
"code": null,
"e": 3923,
"s": 3827,
"text": "Let us discuss how to configure chrome driver with System properties within the Selenium code −"
},
{
"code": null,
"e": 4063,
"s": 3923,
"text": "Add the System.setProperty method in the code which takes the browser type and the path of the chrome driver executable path as parameters."
},
{
"code": null,
"e": 4203,
"s": 4063,
"text": "Add the System.setProperty method in the code which takes the browser type and the path of the chrome driver executable path as parameters."
},
{
"code": null,
"e": 4273,
"s": 4203,
"text": "System.setProperty(\"webdriver.chrome.driver\",\"<chrome driver path>\");"
},
{
"code": null,
"e": 4293,
"s": 4273,
"text": "Code Implementation"
},
{
"code": null,
"e": 4758,
"s": 4293,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class LaunchChromeBrowser{\n public static void main(String[] args) {\n WebDriver driver = new ChromeDriver();\n // to configure the path of the chromedriver.exe\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n }\n}"
}
] |
Neural Networks for Absolute Beginners with Numpy from scratch — Part 3: Logistic Regression | by Suraj Donthi | Towards Data Science | In both Machine Learning and Deep Learning, you could encounter two kinds of problems which are regression and classification.
In regression problems, you predict a continuous real-valued number while in classification problems, you predict different classes of objects.
In the previous tutorials, we went in-depth into what a perceptron is and later learned how it learns to predict with the use of linear regression. In case, you’re an absolute beginner to this domain I recommend you to go through short and easy previous tutorials of mine.
towardsdatascience.com
towardsdatascience.com
In this tutorial, you will learn about logistic regression that is used for classification problems.
As before a bit of math will be involved, but I’ll ensure to cover from the basics so that you can understand easily.
If you are unsure of which environment to use for implementing the code in this tutorial, I recommend Google Colab. The environment comes with many important packages already installed. Installing new packages and also importing and exporting the data is quite simple. Most of all, it also comes with GPU support. So, go ahead and get coding!
Lastly, I recommend that you go through the first two tutorials before you start this. However, if you already know well about linear regression and a bit about Neural Networks or just want to learn about Logistic Regression, you could start right away!
One of the earliest and most popular activation functions utilized is the Sigmoid function.
The equation of the sigmoid function is as follows:
and the graph for the function is as below:
Hence, a perceptron with a sigmoid activation function does binary classification on a given set of data. This process of binary classification is popularly called Logistic Regression. In the next section, we’ll dive deeper into logistic regression and also understand how the model is trained.
So, what is logistic regression?
Logistic regression is a technique used for binary classification. It creates a decision boundary between data points to categorize them in any one of the two classes. Such an illustration can be seen in the figure below. We shall go deeper into understanding and training a logistic regression model through a hands-on implementation. Understanding logistic regression will provide the base for understanding a Neural Network model.
The computation graph for logistic regression to be implemented is shown in the below figure.
We have two inputs x1 and x2 which are multiplied by the weights w1 and w2 respectively. An additional bias b is added to their sum to obtain z. The parameters (w1, w2, b) are learned during gradient descent.
Now let’s get coding!
The first step would be to import the required packages.
You’ll use the sklearn package to perform two tasks:
Generate datasets of blobsSplit the data into train and test sets.
Generate datasets of blobs
Split the data into train and test sets.
You’ll use matplotlib for visualizing the results.
Before you start defining code, in any machine learning project your first task will be to define the hyperparameters. The hyperparameters can be the dataset size, the learning rate, number of epochs, etc. You must be wondering why these variables are called hyperparameters! You’ll find out later that parameters are what is learned in the model and we use hyperparameter to fine-tune the model for achieving better accuracy.
Here we also define the number of input features and the number of clusters as we need to create the dataset.
Go ahead and define them!
Next, we import the dataset from scikit-learn with the make_blobs function which creates blobs of classes. We will visualize the same too.
Now lets, plot a graph to visualize the data generated.
The two sets of data points belong to the two classes. Our goal is to find an optimal decision boundary that separates these two classes.
The next step will be to split the data into train set and test set. We do this so that we can verify the accuracy of the learned algorithm.
Shape of X_train (400, 2) Shape of y_train (400, 1) Shape of X_test (100, 2) Shape of y_test (100, 1)
You’ll now randomly initialize the parameters W and b, which are learned during training.
Initializing weights... W: [[-0.59134456] [-0.31427067]] b: -1.6078558751252707
After we have randomly initialized the parameters, the next step is to perform forward propagation and see how the network predicts.
You will now utilize the generate_mesh_grid function to plot the dataset along with the contour.
It’s now time to define the loss function!!
Unlike the MSE for Linear Regression, here we use a logistic loss function. This is because when we pass the sum z through a sigmoid activation function, the output is non-linear (as the sigmoid function is non-linear). This results in an error that is non-convex.
But what do you mean by non-convex?
In unsophisticated terms, the non-convex function appears to be like the graph on the right.
In such situations, while our goal is to find the minimal point, it becomes extremely difficult to find one because of the troughs and crests. Instead, we could make our problem simpler if we could just have a simple function (like the one on the left) where we can easily find the minimum point. This is the convex function on the left.
Hence, we use a log function that actually converts the non-linear function back to a linear one, which in turn results in a convex function!
Loss can be defined as:
The graph of ᅳlog(x) is shown in the above figure. You can infer that given y = 1 if y → 0, then loss → 0 and when y’ → 0, then loss → ∞. Similarly, if y’ → 0, then loss → 0 and when y’ → 1, then loss → ∞ given y = 0. It implies that when the prediction is wrong, the parameters are heavily penalized and when the prediction is right, the parameters are not penalized.
Here, the function reduces to ᅳlog(y’) when y = 1 and log(1 ᅳ y’) when y = 0 just as we had defined earlier.
While the above is only the error for only one example (datapoint), we need to account for all the examples. Therefore, we find the mean of the errors by summing all of them and dividing by the number of examples as shown below.
The code for this would be as below:
1.0579769986979133
Let’s plot the loss. You’ll keep track of the losses for all the iterations (epochs) after which you will be able to visualize the decrease in error.
[1.0579769986979133]
This will usually be the toughest part to understand, but I have put in very easy terms.
Gradient descent in layman words is like walking down a hill. This hill refers to the error in our case. Higher the error, higher the hill!! So as you roll down the hill, the error (Loss) goes down.
Therefore, our goal is to roll down to the point of least error.
Hey, but wait a sec! How can I change the loss? 🤔
Now you must observe that if you tweak the parameters W and b the Loss also changes!!
Hence, we find the derivative (i.e., the rate of change) with respect to the parameters W & b and update them accordingly.
Well, that’s simple! Just find its derivative or the slope. Mathematically, the slope is zero at the minimal point(minima) [You can refer to this wonderful Khan Academy video if you do not know about derivatives and the slope.] and if you observe keenly, the slope is negative on the left of minima and positive on the right of minima. And when p is to the left of minima, we need to add some value so that it moves towards optimal p and when p is to the right subtract some value.
We find the derivative of the Loss with respect to W and b in our case.
I’ve skipped a few steps which are unnecessary, but if interested, you can refer to this video below.
As to the last part of updating the parameters, with the slopes, we multiply the slope by a dampening factor α so that the parameters don’t overshoot when having a very high error.
You’ll now implement the same gradient_descent algorithm as below.
Now there’s one last thing to do i.e., update combine both the plot functions into one.
We have obtained a beautiful plot of the decision boundary as well as the Loss.
Now as your final task, let’s put together everything you had done until now and see the results for yourselves.
So, you will first define the hyperparameters. You can play around with these values especially the learning rate l_r and epoch to observe how the model learns to predict.
Now, you can write the code from creating a dataset to training your logistic regression model in a single go as below.
Shape of X_train (400, 2) Shape of y_train (400, 1) Shape of X_test (100, 2) Shape of y_test (100, 1) Initializing weights... W: [[ 0.43753829] [-1.70958537]] b: -0.8793505127088026--------------------------------------------------------------------Iteration: 0 W = [[ 0.43753829] [-1.70958537]] b = -0.8793505127088026 Loss = 0.3991070405361789
-------------------------------------------------------------------- Iteration: 5 W = [[ 0.09634223] [-1.73455902]] b = [[-0.87943027]] Loss = 0.10346899489337041
--------------------------------------------------------------------Iteration: 10 W = [[-0.02440044] [-1.73555684]] b = [[-0.87945069]] Loss = 0.06810528539660123
--------------------------------------------------------------------Iteration: 15 W = [[-0.09215724] [-1.73617853]] b = [[-0.87945614]] Loss = 0.0569509026646708
--------------------------------------------------------------------Iteration: 20 W = [[-0.13607178] [-1.737859 ]] b = [[-0.87945457]] Loss = 0.05224655857924122
--------------------------------------------------------------------Iteration: 25 W = [[-0.16649094] [-1.74055496]] b = [[-0.87944893]] Loss = 0.04996979153280091
We had earlier created a test dataset, you’ll now test your regression model against it and determine the accuracy.
The formula for accuracy is:
Prediction: Loss = 0.2929627097697204 Accuracy = 95.0%
Hence W = [[ 3.9538485] [-3.9152981]] b = [[-0.68703193]]
We have obtained an accuracy of 95% which is pretty good!
In this tutorial, you learned
Sigmoid Activation FunctionCreating a Logistic Regression ModelTraining a logistic regression model
Sigmoid Activation Function
Creating a Logistic Regression Model
Training a logistic regression model
In the next tutorial, you’ll learn to implement Neural Networks from scratch using only Numpy! | [
{
"code": null,
"e": 298,
"s": 171,
"text": "In both Machine Learning and Deep Learning, you could encounter two kinds of problems which are regression and classification."
},
{
"code": null,
"e": 442,
"s": 298,
"text": "In regression problems, you predict a continuous real-valued number while in classification problems, you predict different classes of objects."
},
{
"code": null,
"e": 715,
"s": 442,
"text": "In the previous tutorials, we went in-depth into what a perceptron is and later learned how it learns to predict with the use of linear regression. In case, you’re an absolute beginner to this domain I recommend you to go through short and easy previous tutorials of mine."
},
{
"code": null,
"e": 738,
"s": 715,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 761,
"s": 738,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 862,
"s": 761,
"text": "In this tutorial, you will learn about logistic regression that is used for classification problems."
},
{
"code": null,
"e": 980,
"s": 862,
"text": "As before a bit of math will be involved, but I’ll ensure to cover from the basics so that you can understand easily."
},
{
"code": null,
"e": 1323,
"s": 980,
"text": "If you are unsure of which environment to use for implementing the code in this tutorial, I recommend Google Colab. The environment comes with many important packages already installed. Installing new packages and also importing and exporting the data is quite simple. Most of all, it also comes with GPU support. So, go ahead and get coding!"
},
{
"code": null,
"e": 1577,
"s": 1323,
"text": "Lastly, I recommend that you go through the first two tutorials before you start this. However, if you already know well about linear regression and a bit about Neural Networks or just want to learn about Logistic Regression, you could start right away!"
},
{
"code": null,
"e": 1669,
"s": 1577,
"text": "One of the earliest and most popular activation functions utilized is the Sigmoid function."
},
{
"code": null,
"e": 1721,
"s": 1669,
"text": "The equation of the sigmoid function is as follows:"
},
{
"code": null,
"e": 1765,
"s": 1721,
"text": "and the graph for the function is as below:"
},
{
"code": null,
"e": 2060,
"s": 1765,
"text": "Hence, a perceptron with a sigmoid activation function does binary classification on a given set of data. This process of binary classification is popularly called Logistic Regression. In the next section, we’ll dive deeper into logistic regression and also understand how the model is trained."
},
{
"code": null,
"e": 2093,
"s": 2060,
"text": "So, what is logistic regression?"
},
{
"code": null,
"e": 2527,
"s": 2093,
"text": "Logistic regression is a technique used for binary classification. It creates a decision boundary between data points to categorize them in any one of the two classes. Such an illustration can be seen in the figure below. We shall go deeper into understanding and training a logistic regression model through a hands-on implementation. Understanding logistic regression will provide the base for understanding a Neural Network model."
},
{
"code": null,
"e": 2621,
"s": 2527,
"text": "The computation graph for logistic regression to be implemented is shown in the below figure."
},
{
"code": null,
"e": 2830,
"s": 2621,
"text": "We have two inputs x1 and x2 which are multiplied by the weights w1 and w2 respectively. An additional bias b is added to their sum to obtain z. The parameters (w1, w2, b) are learned during gradient descent."
},
{
"code": null,
"e": 2852,
"s": 2830,
"text": "Now let’s get coding!"
},
{
"code": null,
"e": 2909,
"s": 2852,
"text": "The first step would be to import the required packages."
},
{
"code": null,
"e": 2962,
"s": 2909,
"text": "You’ll use the sklearn package to perform two tasks:"
},
{
"code": null,
"e": 3029,
"s": 2962,
"text": "Generate datasets of blobsSplit the data into train and test sets."
},
{
"code": null,
"e": 3056,
"s": 3029,
"text": "Generate datasets of blobs"
},
{
"code": null,
"e": 3097,
"s": 3056,
"text": "Split the data into train and test sets."
},
{
"code": null,
"e": 3148,
"s": 3097,
"text": "You’ll use matplotlib for visualizing the results."
},
{
"code": null,
"e": 3575,
"s": 3148,
"text": "Before you start defining code, in any machine learning project your first task will be to define the hyperparameters. The hyperparameters can be the dataset size, the learning rate, number of epochs, etc. You must be wondering why these variables are called hyperparameters! You’ll find out later that parameters are what is learned in the model and we use hyperparameter to fine-tune the model for achieving better accuracy."
},
{
"code": null,
"e": 3685,
"s": 3575,
"text": "Here we also define the number of input features and the number of clusters as we need to create the dataset."
},
{
"code": null,
"e": 3711,
"s": 3685,
"text": "Go ahead and define them!"
},
{
"code": null,
"e": 3850,
"s": 3711,
"text": "Next, we import the dataset from scikit-learn with the make_blobs function which creates blobs of classes. We will visualize the same too."
},
{
"code": null,
"e": 3906,
"s": 3850,
"text": "Now lets, plot a graph to visualize the data generated."
},
{
"code": null,
"e": 4044,
"s": 3906,
"text": "The two sets of data points belong to the two classes. Our goal is to find an optimal decision boundary that separates these two classes."
},
{
"code": null,
"e": 4185,
"s": 4044,
"text": "The next step will be to split the data into train set and test set. We do this so that we can verify the accuracy of the learned algorithm."
},
{
"code": null,
"e": 4287,
"s": 4185,
"text": "Shape of X_train (400, 2) Shape of y_train (400, 1) Shape of X_test (100, 2) Shape of y_test (100, 1)"
},
{
"code": null,
"e": 4377,
"s": 4287,
"text": "You’ll now randomly initialize the parameters W and b, which are learned during training."
},
{
"code": null,
"e": 4457,
"s": 4377,
"text": "Initializing weights... W: [[-0.59134456] [-0.31427067]] b: -1.6078558751252707"
},
{
"code": null,
"e": 4590,
"s": 4457,
"text": "After we have randomly initialized the parameters, the next step is to perform forward propagation and see how the network predicts."
},
{
"code": null,
"e": 4687,
"s": 4590,
"text": "You will now utilize the generate_mesh_grid function to plot the dataset along with the contour."
},
{
"code": null,
"e": 4731,
"s": 4687,
"text": "It’s now time to define the loss function!!"
},
{
"code": null,
"e": 4996,
"s": 4731,
"text": "Unlike the MSE for Linear Regression, here we use a logistic loss function. This is because when we pass the sum z through a sigmoid activation function, the output is non-linear (as the sigmoid function is non-linear). This results in an error that is non-convex."
},
{
"code": null,
"e": 5032,
"s": 4996,
"text": "But what do you mean by non-convex?"
},
{
"code": null,
"e": 5125,
"s": 5032,
"text": "In unsophisticated terms, the non-convex function appears to be like the graph on the right."
},
{
"code": null,
"e": 5463,
"s": 5125,
"text": "In such situations, while our goal is to find the minimal point, it becomes extremely difficult to find one because of the troughs and crests. Instead, we could make our problem simpler if we could just have a simple function (like the one on the left) where we can easily find the minimum point. This is the convex function on the left."
},
{
"code": null,
"e": 5605,
"s": 5463,
"text": "Hence, we use a log function that actually converts the non-linear function back to a linear one, which in turn results in a convex function!"
},
{
"code": null,
"e": 5629,
"s": 5605,
"text": "Loss can be defined as:"
},
{
"code": null,
"e": 5998,
"s": 5629,
"text": "The graph of ᅳlog(x) is shown in the above figure. You can infer that given y = 1 if y → 0, then loss → 0 and when y’ → 0, then loss → ∞. Similarly, if y’ → 0, then loss → 0 and when y’ → 1, then loss → ∞ given y = 0. It implies that when the prediction is wrong, the parameters are heavily penalized and when the prediction is right, the parameters are not penalized."
},
{
"code": null,
"e": 6107,
"s": 5998,
"text": "Here, the function reduces to ᅳlog(y’) when y = 1 and log(1 ᅳ y’) when y = 0 just as we had defined earlier."
},
{
"code": null,
"e": 6336,
"s": 6107,
"text": "While the above is only the error for only one example (datapoint), we need to account for all the examples. Therefore, we find the mean of the errors by summing all of them and dividing by the number of examples as shown below."
},
{
"code": null,
"e": 6373,
"s": 6336,
"text": "The code for this would be as below:"
},
{
"code": null,
"e": 6392,
"s": 6373,
"text": "1.0579769986979133"
},
{
"code": null,
"e": 6542,
"s": 6392,
"text": "Let’s plot the loss. You’ll keep track of the losses for all the iterations (epochs) after which you will be able to visualize the decrease in error."
},
{
"code": null,
"e": 6563,
"s": 6542,
"text": "[1.0579769986979133]"
},
{
"code": null,
"e": 6652,
"s": 6563,
"text": "This will usually be the toughest part to understand, but I have put in very easy terms."
},
{
"code": null,
"e": 6851,
"s": 6652,
"text": "Gradient descent in layman words is like walking down a hill. This hill refers to the error in our case. Higher the error, higher the hill!! So as you roll down the hill, the error (Loss) goes down."
},
{
"code": null,
"e": 6916,
"s": 6851,
"text": "Therefore, our goal is to roll down to the point of least error."
},
{
"code": null,
"e": 6966,
"s": 6916,
"text": "Hey, but wait a sec! How can I change the loss? 🤔"
},
{
"code": null,
"e": 7052,
"s": 6966,
"text": "Now you must observe that if you tweak the parameters W and b the Loss also changes!!"
},
{
"code": null,
"e": 7175,
"s": 7052,
"text": "Hence, we find the derivative (i.e., the rate of change) with respect to the parameters W & b and update them accordingly."
},
{
"code": null,
"e": 7657,
"s": 7175,
"text": "Well, that’s simple! Just find its derivative or the slope. Mathematically, the slope is zero at the minimal point(minima) [You can refer to this wonderful Khan Academy video if you do not know about derivatives and the slope.] and if you observe keenly, the slope is negative on the left of minima and positive on the right of minima. And when p is to the left of minima, we need to add some value so that it moves towards optimal p and when p is to the right subtract some value."
},
{
"code": null,
"e": 7729,
"s": 7657,
"text": "We find the derivative of the Loss with respect to W and b in our case."
},
{
"code": null,
"e": 7831,
"s": 7729,
"text": "I’ve skipped a few steps which are unnecessary, but if interested, you can refer to this video below."
},
{
"code": null,
"e": 8012,
"s": 7831,
"text": "As to the last part of updating the parameters, with the slopes, we multiply the slope by a dampening factor α so that the parameters don’t overshoot when having a very high error."
},
{
"code": null,
"e": 8079,
"s": 8012,
"text": "You’ll now implement the same gradient_descent algorithm as below."
},
{
"code": null,
"e": 8167,
"s": 8079,
"text": "Now there’s one last thing to do i.e., update combine both the plot functions into one."
},
{
"code": null,
"e": 8247,
"s": 8167,
"text": "We have obtained a beautiful plot of the decision boundary as well as the Loss."
},
{
"code": null,
"e": 8360,
"s": 8247,
"text": "Now as your final task, let’s put together everything you had done until now and see the results for yourselves."
},
{
"code": null,
"e": 8532,
"s": 8360,
"text": "So, you will first define the hyperparameters. You can play around with these values especially the learning rate l_r and epoch to observe how the model learns to predict."
},
{
"code": null,
"e": 8652,
"s": 8532,
"text": "Now, you can write the code from creating a dataset to training your logistic regression model in a single go as below."
},
{
"code": null,
"e": 8998,
"s": 8652,
"text": "Shape of X_train (400, 2) Shape of y_train (400, 1) Shape of X_test (100, 2) Shape of y_test (100, 1) Initializing weights... W: [[ 0.43753829] [-1.70958537]] b: -0.8793505127088026--------------------------------------------------------------------Iteration: 0 W = [[ 0.43753829] [-1.70958537]] b = -0.8793505127088026 Loss = 0.3991070405361789"
},
{
"code": null,
"e": 9161,
"s": 8998,
"text": "-------------------------------------------------------------------- Iteration: 5 W = [[ 0.09634223] [-1.73455902]] b = [[-0.87943027]] Loss = 0.10346899489337041"
},
{
"code": null,
"e": 9324,
"s": 9161,
"text": "--------------------------------------------------------------------Iteration: 10 W = [[-0.02440044] [-1.73555684]] b = [[-0.87945069]] Loss = 0.06810528539660123"
},
{
"code": null,
"e": 9486,
"s": 9324,
"text": "--------------------------------------------------------------------Iteration: 15 W = [[-0.09215724] [-1.73617853]] b = [[-0.87945614]] Loss = 0.0569509026646708"
},
{
"code": null,
"e": 9648,
"s": 9486,
"text": "--------------------------------------------------------------------Iteration: 20 W = [[-0.13607178] [-1.737859 ]] b = [[-0.87945457]] Loss = 0.05224655857924122"
},
{
"code": null,
"e": 9811,
"s": 9648,
"text": "--------------------------------------------------------------------Iteration: 25 W = [[-0.16649094] [-1.74055496]] b = [[-0.87944893]] Loss = 0.04996979153280091"
},
{
"code": null,
"e": 9927,
"s": 9811,
"text": "We had earlier created a test dataset, you’ll now test your regression model against it and determine the accuracy."
},
{
"code": null,
"e": 9956,
"s": 9927,
"text": "The formula for accuracy is:"
},
{
"code": null,
"e": 10011,
"s": 9956,
"text": "Prediction: Loss = 0.2929627097697204 Accuracy = 95.0%"
},
{
"code": null,
"e": 10069,
"s": 10011,
"text": "Hence W = [[ 3.9538485] [-3.9152981]] b = [[-0.68703193]]"
},
{
"code": null,
"e": 10127,
"s": 10069,
"text": "We have obtained an accuracy of 95% which is pretty good!"
},
{
"code": null,
"e": 10157,
"s": 10127,
"text": "In this tutorial, you learned"
},
{
"code": null,
"e": 10257,
"s": 10157,
"text": "Sigmoid Activation FunctionCreating a Logistic Regression ModelTraining a logistic regression model"
},
{
"code": null,
"e": 10285,
"s": 10257,
"text": "Sigmoid Activation Function"
},
{
"code": null,
"e": 10322,
"s": 10285,
"text": "Creating a Logistic Regression Model"
},
{
"code": null,
"e": 10359,
"s": 10322,
"text": "Training a logistic regression model"
}
] |
Merge Sort for Doubly Linked List using C++. | Given a doubly linked list. Sort it using merge sort algorithm
List: 10->20->8-17->5->13->4
Sorted list: 4->5->8->10->13->17->20
1. If head is NULL or list contains only one element then return list
2. Create two lists by dividing original list into 2 parts
3. Sort first and second part of list
4. Merge both sorted list
#include <iostream>
#include <new>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct node {
int data;
struct node *next;
struct node *prev;
};
node *createList(int *arr, int n){
node *head, *p, *q;
p = head = new node;
head->data = arr[0];
head->prev = NULL;
head->next = NULL;
for (int i = 1; i < n; ++i) {
q = new node;
q->data = arr[i];
q->prev = p;
q->next = NULL;
p->next = q;
p = q;
}
return head;
}
void displayList(node *head){
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
node *mergeSortedLists(node *head1, node *head2){
node *result = NULL;
if (head1 == NULL) {
return head2;
}
if (head2 == NULL) {
return head1;
}
if (head1->data < head2->data) {
head1->next = mergeSortedLists(head1->next, head2);
head1->next->prev = head1;
head1->prev = NULL;
return head1;
} else {
head2->next = mergeSortedLists(head1, head2->next);
head2->next->prev = head2;
head2->prev = NULL;
return head2;
}
}
void splitList(node *src, node **fRef, node **bRef){
node *fast;
node *slow;
slow = src;
fast = src->next;
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
*fRef = src;
*bRef = slow->next;
slow->next = NULL;
}
void mergeSort(node **head){
node *p = *head;
node *a = NULL;
node *b = NULL;
if (p == NULL || p->next == NULL) {
return;
}
splitList(p, &a, &b);
mergeSort(&a);
mergeSort(&b);
*head = mergeSortedLists(a, b);
}
int main(){
int arr[] = {10, 20, 8, 17, 5, 13, 4};
node *head;
head = createList(arr, SIZE(arr));
cout << "Unsorted list: " << endl;
displayList(head);
mergeSort(&head);
cout << "Final sorted list: " << endl;
displayList(head);
return 0;
}
When you compile and execute the above program. It generates the following output −
Unsorted list:
10 20 8 17 5 13 4
Final sorted list:
4 5 8 10 13 17 20 | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Given a doubly linked list. Sort it using merge sort algorithm"
},
{
"code": null,
"e": 1191,
"s": 1125,
"text": "List: 10->20->8-17->5->13->4\nSorted list: 4->5->8->10->13->17->20"
},
{
"code": null,
"e": 1384,
"s": 1191,
"text": "1. If head is NULL or list contains only one element then return list\n2. Create two lists by dividing original list into 2 parts\n3. Sort first and second part of list\n4. Merge both sorted list"
},
{
"code": null,
"e": 3363,
"s": 1384,
"text": "#include <iostream>\n#include <new>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nstruct node {\n int data;\n struct node *next;\n struct node *prev;\n};\nnode *createList(int *arr, int n){\n node *head, *p, *q;\n p = head = new node;\n head->data = arr[0];\n head->prev = NULL;\n head->next = NULL;\n for (int i = 1; i < n; ++i) {\n q = new node;\n q->data = arr[i];\n q->prev = p;\n q->next = NULL;\n p->next = q;\n p = q;\n }\n return head;\n}\nvoid displayList(node *head){\n while (head != NULL) {\n cout << head->data << \" \";\n head = head->next;\n }\n cout << endl;\n}\nnode *mergeSortedLists(node *head1, node *head2){\n node *result = NULL;\n if (head1 == NULL) {\n return head2;\n }\n if (head2 == NULL) {\n return head1;\n }\n if (head1->data < head2->data) {\n head1->next = mergeSortedLists(head1->next, head2);\n head1->next->prev = head1;\n head1->prev = NULL;\n return head1;\n } else {\n head2->next = mergeSortedLists(head1, head2->next);\n head2->next->prev = head2;\n head2->prev = NULL;\n return head2;\n }\n}\nvoid splitList(node *src, node **fRef, node **bRef){\n node *fast;\n node *slow;\n slow = src;\n fast = src->next;\n while (fast != NULL) {\n fast = fast->next;\n if (fast != NULL) {\n slow = slow->next;\n fast = fast->next;\n }\n }\n *fRef = src;\n *bRef = slow->next;\n slow->next = NULL;\n}\nvoid mergeSort(node **head){\n node *p = *head;\n node *a = NULL;\n node *b = NULL;\n if (p == NULL || p->next == NULL) {\n return;\n }\n splitList(p, &a, &b);\n mergeSort(&a);\n mergeSort(&b);\n *head = mergeSortedLists(a, b);\n}\nint main(){\n int arr[] = {10, 20, 8, 17, 5, 13, 4};\n node *head;\n head = createList(arr, SIZE(arr));\n cout << \"Unsorted list: \" << endl;\n displayList(head);\n mergeSort(&head);\n cout << \"Final sorted list: \" << endl;\n displayList(head);\n return 0;\n}"
},
{
"code": null,
"e": 3447,
"s": 3363,
"text": "When you compile and execute the above program. It generates the following output −"
},
{
"code": null,
"e": 3517,
"s": 3447,
"text": "Unsorted list:\n10 20 8 17 5 13 4\nFinal sorted list:\n4 5 8 10 13 17 20"
}
] |
How to Create a Geofence with Python | by Mike Flanagan | Towards Data Science | Geofencing is a useful technique with a wide range of applications whenever one is handling location data. It can be used to signal notifications or flag alerts based on proximity to an individual or landmark. In data science, it is often used in feature engineering and creating boundaries for visualizations.
A geofence is a virtual perimeter for a real-world geographic area. A geo-fence could be dynamically generated — as in a radius around a point location, or a geo-fence can be a predefined set of boundaries (such as school zones or neighborhood boundaries). — Wikipedia
While any of the applications are apparent, thinking of how geofences may be constructed may not always be immediately obvious. There are also many approaches to engineering geofences, with some occasions requiring precisely drawn boundaries, and others requiring variable radii from a moving user’s cell phone, that changes in certain contexts. In this blog, let’s see how we can create some simple geofences as to understand the principles behind them.
The example that I walk through below comes from my project exploring and modeling using a dataset containing property sale values in King County, WA. More information about the project and example dataset may be found at the following GitHub repository—regression analysis & modeling for property sale prices in King County, WA. Access to the source data is provided in the bibliography at the end of this article.
Imagine that we have a dataset which contains records for numerous locations, with the locations for each row item being represented by latitude (df[‘lat’]) and longitude (df[‘long’]).
We may classify certain locations as to falling within a certain “zone” or bounds. There are several techniques that we may employ, ranging from straightforward to complex. Let’s look at a handful of elementary examples to see how such techniques may be employed.
Above is an image of King County, WA. From Google Maps’ rendition alone, a shallow interpretation may be that a majority of King County is less developed, with more urban and suburban area being grey, and the more rural being green.
The most rudimentary partition we could make of this land would be with a straight line dividing the rural from the more developed, simply interpreted below.
We can do this in Python with NumPy and Pandas:
# Creating a dummy classifier for rural or notdf['rural'] = np.where(df.long > -121.961527, 1, 0)
The above code creates a dummy variable representing “rural” King County. All properties that fall east of the divider (i.e.—any property with a longitude greater than -121.96) with be classified as rural, by assigning it a 1 in a newly created column identified as rural in our DataFrame df. Any property with a 0 in that column will be de facto not considered rural.
While this is imprecise, it captures most of the properties correctly, and is very simple to perform. What if we would like to add some other conditions that consider latitude?
The non-rural area of King County includes the city of Seattle. For this exercise, let’s consider Seattle to be “city,” rural King County to be “rural,” and the non-rural area of King County excluding Seattle to be suburban. Were we to draw as precise of a box around the city of Seattle, we could do so as shown below.
Again, we can use an np.where() statement to create a new class for our data. We’ll call this one “within_seattle_city_limits” and only properties sold in Seattle will be assigned a 1 in this column.
# Creating a dummy classifier for if property is within Seattle city limits or notdf['within_seattle_city_limits'] = np.where( (df.long < -122.251569) # establishes the EAST box border & (df.long > -122.438230) # establishes the WEST box border & (df.lat < 47.734178) # establishes the NORTH box border & (df.lat > 47.495479), # establishes the SOUTH box border 1, # assigns 1 to all properties within the bounding box 0 # assigns 0 to all properties outside the bounding box)
Above, we create the green box that encompasses Seattle with another np.where() statement. The coordinates in the statement in conjunction with the ampersand & set the corners of the box.
Note that no column is created at any point for “suburban,” “non-city,” or “non-rural.” Any property in our dataset that does not get classified as within Seattle nor classified as rural (i.e.— receives a 0 in both columns ‘within_seattle_city_limits’ and 'rural’) will be considered “suburban” by default.
Understanding that, realize that this again is a bit imprecise. We can see in the north-east corner that our “city” box includes a slice of what should be considered “suburban,” ditto with Mercer Island east of Seattle, and we even cut out a very small segment of what should be considered the “city” of Seattle in the south-east, classifying it as “suburban.”
While this may cause problems, we may individually check properties that would be mistakenly given an inappropriate classification and update them manually. We can also address this with layering additional boxes, but that will be covered in my next blog on this subject.
Still, I must emphasize the importance of catching potential issues as you create them. While I did scrub the dataset and ensure that every property was correctly labeled, what would happen were we to add exogenous data and apply the above classification? We would dirty our data and be nursing our headaches with icepacks.
And what if we would like to create a zone with complex boundaries? This may require a little trigonometry, exclusion conditionals and the incorporation of pipes (|) for “or” conditions, or the help of other Python libraries. Many tools and techniques may be used, but the same principle applies: creating rules for classification based on location contexts and conditions.
Dataset:House Sales in King County, USA (2016), Provided by harlfoxem on Kaggle via CC0: Public Domain License
Images:Header photo by Will Francis on Unsplash
Google Maps. [King County, WA]. Map image. 2021,King County — Google Maps. Accessed 16 August 2021.Map data © 2021 Google.
Google Maps. [Seattle, WA]. Map image. 2021, Seattle — Google Maps. Accessed 16 August 2021. Map data © 2021 Google. | [
{
"code": null,
"e": 483,
"s": 172,
"text": "Geofencing is a useful technique with a wide range of applications whenever one is handling location data. It can be used to signal notifications or flag alerts based on proximity to an individual or landmark. In data science, it is often used in feature engineering and creating boundaries for visualizations."
},
{
"code": null,
"e": 752,
"s": 483,
"text": "A geofence is a virtual perimeter for a real-world geographic area. A geo-fence could be dynamically generated — as in a radius around a point location, or a geo-fence can be a predefined set of boundaries (such as school zones or neighborhood boundaries). — Wikipedia"
},
{
"code": null,
"e": 1207,
"s": 752,
"text": "While any of the applications are apparent, thinking of how geofences may be constructed may not always be immediately obvious. There are also many approaches to engineering geofences, with some occasions requiring precisely drawn boundaries, and others requiring variable radii from a moving user’s cell phone, that changes in certain contexts. In this blog, let’s see how we can create some simple geofences as to understand the principles behind them."
},
{
"code": null,
"e": 1623,
"s": 1207,
"text": "The example that I walk through below comes from my project exploring and modeling using a dataset containing property sale values in King County, WA. More information about the project and example dataset may be found at the following GitHub repository—regression analysis & modeling for property sale prices in King County, WA. Access to the source data is provided in the bibliography at the end of this article."
},
{
"code": null,
"e": 1808,
"s": 1623,
"text": "Imagine that we have a dataset which contains records for numerous locations, with the locations for each row item being represented by latitude (df[‘lat’]) and longitude (df[‘long’])."
},
{
"code": null,
"e": 2072,
"s": 1808,
"text": "We may classify certain locations as to falling within a certain “zone” or bounds. There are several techniques that we may employ, ranging from straightforward to complex. Let’s look at a handful of elementary examples to see how such techniques may be employed."
},
{
"code": null,
"e": 2305,
"s": 2072,
"text": "Above is an image of King County, WA. From Google Maps’ rendition alone, a shallow interpretation may be that a majority of King County is less developed, with more urban and suburban area being grey, and the more rural being green."
},
{
"code": null,
"e": 2463,
"s": 2305,
"text": "The most rudimentary partition we could make of this land would be with a straight line dividing the rural from the more developed, simply interpreted below."
},
{
"code": null,
"e": 2511,
"s": 2463,
"text": "We can do this in Python with NumPy and Pandas:"
},
{
"code": null,
"e": 2685,
"s": 2511,
"text": "# Creating a dummy classifier for rural or notdf['rural'] = np.where(df.long > -121.961527, 1, 0)"
},
{
"code": null,
"e": 3054,
"s": 2685,
"text": "The above code creates a dummy variable representing “rural” King County. All properties that fall east of the divider (i.e.—any property with a longitude greater than -121.96) with be classified as rural, by assigning it a 1 in a newly created column identified as rural in our DataFrame df. Any property with a 0 in that column will be de facto not considered rural."
},
{
"code": null,
"e": 3231,
"s": 3054,
"text": "While this is imprecise, it captures most of the properties correctly, and is very simple to perform. What if we would like to add some other conditions that consider latitude?"
},
{
"code": null,
"e": 3551,
"s": 3231,
"text": "The non-rural area of King County includes the city of Seattle. For this exercise, let’s consider Seattle to be “city,” rural King County to be “rural,” and the non-rural area of King County excluding Seattle to be suburban. Were we to draw as precise of a box around the city of Seattle, we could do so as shown below."
},
{
"code": null,
"e": 3751,
"s": 3551,
"text": "Again, we can use an np.where() statement to create a new class for our data. We’ll call this one “within_seattle_city_limits” and only properties sold in Seattle will be assigned a 1 in this column."
},
{
"code": null,
"e": 4251,
"s": 3751,
"text": "# Creating a dummy classifier for if property is within Seattle city limits or notdf['within_seattle_city_limits'] = np.where( (df.long < -122.251569) # establishes the EAST box border & (df.long > -122.438230) # establishes the WEST box border & (df.lat < 47.734178) # establishes the NORTH box border & (df.lat > 47.495479), # establishes the SOUTH box border 1, # assigns 1 to all properties within the bounding box 0 # assigns 0 to all properties outside the bounding box)"
},
{
"code": null,
"e": 4439,
"s": 4251,
"text": "Above, we create the green box that encompasses Seattle with another np.where() statement. The coordinates in the statement in conjunction with the ampersand & set the corners of the box."
},
{
"code": null,
"e": 4746,
"s": 4439,
"text": "Note that no column is created at any point for “suburban,” “non-city,” or “non-rural.” Any property in our dataset that does not get classified as within Seattle nor classified as rural (i.e.— receives a 0 in both columns ‘within_seattle_city_limits’ and 'rural’) will be considered “suburban” by default."
},
{
"code": null,
"e": 5107,
"s": 4746,
"text": "Understanding that, realize that this again is a bit imprecise. We can see in the north-east corner that our “city” box includes a slice of what should be considered “suburban,” ditto with Mercer Island east of Seattle, and we even cut out a very small segment of what should be considered the “city” of Seattle in the south-east, classifying it as “suburban.”"
},
{
"code": null,
"e": 5379,
"s": 5107,
"text": "While this may cause problems, we may individually check properties that would be mistakenly given an inappropriate classification and update them manually. We can also address this with layering additional boxes, but that will be covered in my next blog on this subject."
},
{
"code": null,
"e": 5703,
"s": 5379,
"text": "Still, I must emphasize the importance of catching potential issues as you create them. While I did scrub the dataset and ensure that every property was correctly labeled, what would happen were we to add exogenous data and apply the above classification? We would dirty our data and be nursing our headaches with icepacks."
},
{
"code": null,
"e": 6077,
"s": 5703,
"text": "And what if we would like to create a zone with complex boundaries? This may require a little trigonometry, exclusion conditionals and the incorporation of pipes (|) for “or” conditions, or the help of other Python libraries. Many tools and techniques may be used, but the same principle applies: creating rules for classification based on location contexts and conditions."
},
{
"code": null,
"e": 6188,
"s": 6077,
"text": "Dataset:House Sales in King County, USA (2016), Provided by harlfoxem on Kaggle via CC0: Public Domain License"
},
{
"code": null,
"e": 6236,
"s": 6188,
"text": "Images:Header photo by Will Francis on Unsplash"
},
{
"code": null,
"e": 6359,
"s": 6236,
"text": "Google Maps. [King County, WA]. Map image. 2021,King County — Google Maps. Accessed 16 August 2021.Map data © 2021 Google."
}
] |
Implementing a Contacts directory in Python - GeeksforGeeks | 15 Sep, 2021
Our task is to implement a smartphone directory that collects contact data from the user until the user prompts the program to. Contact data refers to the contact’s name, phone number, date-of-birth, a category that contact belongs to (Friends, Family, Work, Other), e-mail address. The user may enter as much data as he can in the mentioned data labels. If some labels remain void of data, store it as None. A name & the number is mandatory to create contact. Implement the following operations on the directory: Insert, Delete, Search, Display.
Approach :We have used 2D list concept and implemented the same in Python3. There are a total of 8 functions used in this code, namely :
initial_phonebook() : The first function to run, it initializes the phonebook.
menu() : It displays the choices available to the user and returns the choice entered.
add_contact() : It adds a new contact to the Contacts directory.
remove_existing() : It removes an existing contact from the Contacts directory.
delete_all() : It deletes all the contacts from the Contacts directory.
display_all() : It displays all the contacts from the Contacts directory.
search_existing() : It will search nd display an existing contact in the Contacts directory.
thanks() :
Keeping user experience and user interface, we have made the code simple, readable and interactive. You may or may not go for all the features exactly as described below. Please go through the code solution.
Please try to run this code on your Python IDLE as some errors may occur if you run here as user inputs are required. You may also open the IDE page at GFG and run your code there instead of directly running from the code snippet.
python3
# importing the moduleimport sys # this function will be the first to run as soon as the main function executesdef initial_phonebook(): rows, cols = int(input("Please enter initial number of contacts: ")), 5 # We are collecting the initial number of contacts the user wants to have in the # phonebook already. User may also enter 0 if he doesn't wish to enter any. phone_book = [] print(phone_book) for i in range(rows): print("\nEnter contact %d details in the following order (ONLY):" % (i+1)) print("NOTE: * indicates mandatory fields") print("....................................................................") temp = [] for j in range(cols): # We have taken the conditions for values of j only for the personalized fields # such as name, number, e-mail id, dob, category etc if j == 0: temp.append(str(input("Enter name*: "))) # We need to check if the user has left the name empty as its mentioned that # name & number are mandatory fields. # So implement a condition to check as below. if temp[j] == '' or temp[j] == ' ': sys.exit( "Name is a mandatory field. Process exiting due to blank field...") # This will exit the process if a blank field is encountered. if j == 1: temp.append(int(input("Enter number*: "))) # We do not need to check if user has entered the number because int automatically # takes care of it. Int value cannot accept a blank as that counts as a string. # So process automatically exits without us using the sys package. if j == 2: temp.append(str(input("Enter e-mail address: "))) # Even if this field is left as blank, None will take the blank's place if temp[j] == '' or temp[j] == ' ': temp[j] = None if j == 3: temp.append(str(input("Enter date of birth(dd/mm/yy): "))) # Whatever format the user enters dob in, it won't make a difference to the compiler # Only while searching the user will have to enter query exactly the same way as # he entered during the input so as to ensure accurate searches if temp[j] == '' or temp[j] == ' ': # Even if this field is left as blank, None will take the blank's place temp[j] = None if j == 4: temp.append( str(input("Enter category(Family/Friends/Work/Others): "))) # Even if this field is left as blank, None will take the blank's place if temp[j] == "" or temp[j] == ' ': temp[j] = None phone_book.append(temp) # By this step we are appending a list temp into a list phone_book # That means phone_book is a 2-D array and temp is a 1-D array print(phone_book) return phone_book def menu(): # We created this simple menu function for # code reusability & also for an interactive console # Menu func will only execute when called print("********************************************************************") print("\t\t\tSMARTPHONE DIRECTORY", flush=False) print("********************************************************************") print("\tYou can now perform the following operations on this phonebook\n") print("1. Add a new contact") print("2. Remove an existing contact") print("3. Delete all contacts") print("4. Search for a contact") print("5. Display all contacts") print("6. Exit phonebook") # Out of the provided 6 choices, user needs to enter any 1 choice among the 6 # We return the entered choice to the calling function wiz main in our case choice = int(input("Please enter your choice: ")) return choice def add_contact(pb): # Adding a contact is the easiest because all you need to do is: # append another list of details into the already existing list dip = [] for i in range(len(pb[0])): if i == 0: dip.append(str(input("Enter name: "))) if i == 1: dip.append(int(input("Enter number: "))) if i == 2: dip.append(str(input("Enter e-mail address: "))) if i == 3: dip.append(str(input("Enter date of birth(dd/mm/yy): "))) if i == 4: dip.append( str(input("Enter category(Family/Friends/Work/Others): "))) pb.append(dip) # And once you modify the list, you return it to the calling function wiz main, here. return pb def remove_existing(pb): # This function is to remove a contact's details from existing phonebook query = str( input("Please enter the name of the contact you wish to remove: ")) # We'll collect name of the contact and search if it exists in our phonebook temp = 0 # temp is a checking variable here. We assigned a value 0 to temp. for i in range(len(pb)): if query == pb[i][0]: temp += 1 # Temp will be incremented & it won't be 0 anymore in this function's scope print(pb.pop(i)) # The pop function removes entry at index i print("This query has now been removed") # printing a confirmation message after removal. # This ensures that removal was successful. # After removal we will return the modified phonebook to the calling function # which is main in our program return pb if temp == 0: # Now if at all any case matches temp should've incremented but if otherwise, # temp will remain 0 and that means the query does not exist in this phonebook print("Sorry, you have entered an invalid query.\ Please recheck and try again later.") return pb def delete_all(pb): # This function will simply delete all the entries in the phonebook pb # It will return an empty phonebook after clearing return pb.clear() def search_existing(pb): # This function searches for an existing contact and displays the result choice = int(input("Enter search criteria\n\n\ 1. Name\n2. Number\n3. Email-id\n4. DOB\n5. Category(Family/Friends/Work/Others)\ \nPlease enter: ")) # We're doing so just to ensure that the user experiences a customized search result temp = [] check = -1 if choice == 1: # This will execute for searches based on contact name query = str( input("Please enter the name of the contact you wish to search: ")) for i in range(len(pb)): if query == pb[i][0]: check = i temp.append(pb[i]) elif choice == 2: # This will execute for searches based on contact number query = int( input("Please enter the number of the contact you wish to search: ")) for i in range(len(pb)): if query == pb[i][1]: check = i temp.append(pb[i]) elif choice == 3: # This will execute for searches based on contact's e-mail address query = str(input("Please enter the e-mail ID\ of the contact you wish to search: ")) for i in range(len(pb)): if query == pb[i][2]: check = i temp.append(pb[i]) elif choice == 4: # This will execute for searches based on contact''s date of birth query = str(input("Please enter the DOB (in dd/mm/yyyy format ONLY)\ of the contact you wish to search: ")) for i in range(len(pb)): if query == pb[i][3]: check = i temp.append(pb[i]) elif choice == 5: # This will execute for searches based on contact category query = str( input("Please enter the category of the contact you wish to search: ")) for i in range(len(pb)): if query == pb[i][4]: check = i temp.append(pb[i]) # All contacts under query category will be shown using this feature else: # If the user enters any other choice then the search will be unsuccessful print("Invalid search criteria") return -1 # returning -1 indicates that the search was unsuccessful # all the searches are stored in temp and all the results will be displayed with # the help of display function if check == -1: return -1 # returning -1 indicates that the query did not exist in the directory else: display_all(temp) return check # we're just returning a index value wiz not -1 to calling function just to notify # that the search worked successfully # this function displays all content of phonebook pbdef display_all(pb): if not pb: # if display function is called after deleting all contacts then the len will be 0 # And then without this condition it will throw an error print("List is empty: []") else: for i in range(len(pb)): print(pb[i]) def thanks():# A simple gesture of courtesy towards the user to enhance user experience print("********************************************************************") print("Thank you for using our Smartphone directory system.") print("Please visit again!") print("********************************************************************") sys.exit("Goodbye, have a nice day ahead!") # Main function codeprint("....................................................................")print("Hello dear user, welcome to our smartphone directory system")print("You may now proceed to explore this directory")print("....................................................................")# This is solely meant for decoration purpose only.# You're free to modify your interface as per your will to make it look interactive ch = 1pb = initial_phonebook()while ch in (1, 2, 3, 4, 5): ch = menu() if ch == 1: pb = add_contact(pb) elif ch == 2: pb = remove_existing(pb) elif ch == 3: pb = delete_all(pb) elif ch == 4: d = search_existing(pb) if d == -1: print("The contact does not exist. Please try again") elif ch == 5: display_all(pb) else: thanks()
Output : We shall see the output of this program segment by segment.Initially, the following will be displayed :
.................................................................... Hello dear user, welcome to our smartphone directory system You may now proceed to explore this directory .................................................................... Please enter initial number of contacts:
In the starting, we shall enter 2 contacts :
Please enter initial number of contacts: 2 []Enter contact 1 details in the following order (ONLY): NOTE: * indicates mandatory fields .................................................................... Enter name*: Geeks Enter number*: 9999999999 Enter e-mail address: [email protected] Enter date of birth(dd/mm/yy): 01/01/01 Enter category(Family/Friends/Work/Others): WorkEnter contact 2 details in the following order (ONLY): NOTE: * indicates mandatory fields .................................................................... Enter name*: Sample Enter number*: 1234567890 Enter e-mail address: Enter date of birth(dd/mm/yy): Enter category(Family/Friends/Work/Others): [[‘Geeks’, 9999999999, ‘[email protected]’, ’01/01/01′, ‘Work’], [‘Sample’, 1234567890, None, None, None]] ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice:
Now to add a new contact, according to the menu we will press 1 :
Please enter your choice: 1 Enter name: Emergency Enter number: 108 Enter e-mail address: Enter date of birth(dd/mm/yy): Enter category(Family/Friends/Work/Others): ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice:
We can see all the contacts by pressing 5 :
Please enter your choice: 5 [‘Geeks’, 9999999999, ‘[email protected]’, ’01/01/01′, ‘Work’] [‘Sample’, 1234567890, None, None, None] [‘Emergency’, 108, ”, ”, ”] ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice:
To delete a contact, we have to enter 2 :
Please enter your choice: 2 Please enter the name of the contact you wish to remove: Sample [‘Sample’, 1234567890, None, None, None] This query has now been removed ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice:
To search for a contact, we have to press 4 :
Please enter your choice: 4 Enter search criteria1. Name 2. Number 3. Email-id 4. DOB 5. Category(Family/Friends/Work/Others) Please enter: 2 Please enter the number of the contact you wish to search: 9999999999 [‘Geeks’, 9999999999, ‘[email protected]’, ’01/01/01′, ‘Work’] ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice:
We can delete all the contacts by pressing 3 :
Please enter your choice: 3 ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice:
To view all the contacts press 5, as we have just deleted them nothing will be displayed :
Please enter your choice: 5 List is empty: [] ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice:
To exit the program, enter 6 :
Please enter your choice: 6 ******************************************************************** Thank you for using our Smartphone directory system. Please visit again! ********************************************************************
sweetyty
Python-projects
school-programming
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": 24318,
"s": 24290,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 24865,
"s": 24318,
"text": "Our task is to implement a smartphone directory that collects contact data from the user until the user prompts the program to. Contact data refers to the contact’s name, phone number, date-of-birth, a category that contact belongs to (Friends, Family, Work, Other), e-mail address. The user may enter as much data as he can in the mentioned data labels. If some labels remain void of data, store it as None. A name & the number is mandatory to create contact. Implement the following operations on the directory: Insert, Delete, Search, Display."
},
{
"code": null,
"e": 25004,
"s": 24865,
"text": "Approach :We have used 2D list concept and implemented the same in Python3. There are a total of 8 functions used in this code, namely : "
},
{
"code": null,
"e": 25083,
"s": 25004,
"text": "initial_phonebook() : The first function to run, it initializes the phonebook."
},
{
"code": null,
"e": 25170,
"s": 25083,
"text": "menu() : It displays the choices available to the user and returns the choice entered."
},
{
"code": null,
"e": 25235,
"s": 25170,
"text": "add_contact() : It adds a new contact to the Contacts directory."
},
{
"code": null,
"e": 25315,
"s": 25235,
"text": "remove_existing() : It removes an existing contact from the Contacts directory."
},
{
"code": null,
"e": 25387,
"s": 25315,
"text": "delete_all() : It deletes all the contacts from the Contacts directory."
},
{
"code": null,
"e": 25461,
"s": 25387,
"text": "display_all() : It displays all the contacts from the Contacts directory."
},
{
"code": null,
"e": 25554,
"s": 25461,
"text": "search_existing() : It will search nd display an existing contact in the Contacts directory."
},
{
"code": null,
"e": 25565,
"s": 25554,
"text": "thanks() :"
},
{
"code": null,
"e": 25774,
"s": 25565,
"text": "Keeping user experience and user interface, we have made the code simple, readable and interactive. You may or may not go for all the features exactly as described below. Please go through the code solution. "
},
{
"code": null,
"e": 26005,
"s": 25774,
"text": "Please try to run this code on your Python IDLE as some errors may occur if you run here as user inputs are required. You may also open the IDE page at GFG and run your code there instead of directly running from the code snippet."
},
{
"code": null,
"e": 26015,
"s": 26007,
"text": "python3"
},
{
"code": "# importing the moduleimport sys # this function will be the first to run as soon as the main function executesdef initial_phonebook(): rows, cols = int(input(\"Please enter initial number of contacts: \")), 5 # We are collecting the initial number of contacts the user wants to have in the # phonebook already. User may also enter 0 if he doesn't wish to enter any. phone_book = [] print(phone_book) for i in range(rows): print(\"\\nEnter contact %d details in the following order (ONLY):\" % (i+1)) print(\"NOTE: * indicates mandatory fields\") print(\"....................................................................\") temp = [] for j in range(cols): # We have taken the conditions for values of j only for the personalized fields # such as name, number, e-mail id, dob, category etc if j == 0: temp.append(str(input(\"Enter name*: \"))) # We need to check if the user has left the name empty as its mentioned that # name & number are mandatory fields. # So implement a condition to check as below. if temp[j] == '' or temp[j] == ' ': sys.exit( \"Name is a mandatory field. Process exiting due to blank field...\") # This will exit the process if a blank field is encountered. if j == 1: temp.append(int(input(\"Enter number*: \"))) # We do not need to check if user has entered the number because int automatically # takes care of it. Int value cannot accept a blank as that counts as a string. # So process automatically exits without us using the sys package. if j == 2: temp.append(str(input(\"Enter e-mail address: \"))) # Even if this field is left as blank, None will take the blank's place if temp[j] == '' or temp[j] == ' ': temp[j] = None if j == 3: temp.append(str(input(\"Enter date of birth(dd/mm/yy): \"))) # Whatever format the user enters dob in, it won't make a difference to the compiler # Only while searching the user will have to enter query exactly the same way as # he entered during the input so as to ensure accurate searches if temp[j] == '' or temp[j] == ' ': # Even if this field is left as blank, None will take the blank's place temp[j] = None if j == 4: temp.append( str(input(\"Enter category(Family/Friends/Work/Others): \"))) # Even if this field is left as blank, None will take the blank's place if temp[j] == \"\" or temp[j] == ' ': temp[j] = None phone_book.append(temp) # By this step we are appending a list temp into a list phone_book # That means phone_book is a 2-D array and temp is a 1-D array print(phone_book) return phone_book def menu(): # We created this simple menu function for # code reusability & also for an interactive console # Menu func will only execute when called print(\"********************************************************************\") print(\"\\t\\t\\tSMARTPHONE DIRECTORY\", flush=False) print(\"********************************************************************\") print(\"\\tYou can now perform the following operations on this phonebook\\n\") print(\"1. Add a new contact\") print(\"2. Remove an existing contact\") print(\"3. Delete all contacts\") print(\"4. Search for a contact\") print(\"5. Display all contacts\") print(\"6. Exit phonebook\") # Out of the provided 6 choices, user needs to enter any 1 choice among the 6 # We return the entered choice to the calling function wiz main in our case choice = int(input(\"Please enter your choice: \")) return choice def add_contact(pb): # Adding a contact is the easiest because all you need to do is: # append another list of details into the already existing list dip = [] for i in range(len(pb[0])): if i == 0: dip.append(str(input(\"Enter name: \"))) if i == 1: dip.append(int(input(\"Enter number: \"))) if i == 2: dip.append(str(input(\"Enter e-mail address: \"))) if i == 3: dip.append(str(input(\"Enter date of birth(dd/mm/yy): \"))) if i == 4: dip.append( str(input(\"Enter category(Family/Friends/Work/Others): \"))) pb.append(dip) # And once you modify the list, you return it to the calling function wiz main, here. return pb def remove_existing(pb): # This function is to remove a contact's details from existing phonebook query = str( input(\"Please enter the name of the contact you wish to remove: \")) # We'll collect name of the contact and search if it exists in our phonebook temp = 0 # temp is a checking variable here. We assigned a value 0 to temp. for i in range(len(pb)): if query == pb[i][0]: temp += 1 # Temp will be incremented & it won't be 0 anymore in this function's scope print(pb.pop(i)) # The pop function removes entry at index i print(\"This query has now been removed\") # printing a confirmation message after removal. # This ensures that removal was successful. # After removal we will return the modified phonebook to the calling function # which is main in our program return pb if temp == 0: # Now if at all any case matches temp should've incremented but if otherwise, # temp will remain 0 and that means the query does not exist in this phonebook print(\"Sorry, you have entered an invalid query.\\ Please recheck and try again later.\") return pb def delete_all(pb): # This function will simply delete all the entries in the phonebook pb # It will return an empty phonebook after clearing return pb.clear() def search_existing(pb): # This function searches for an existing contact and displays the result choice = int(input(\"Enter search criteria\\n\\n\\ 1. Name\\n2. Number\\n3. Email-id\\n4. DOB\\n5. Category(Family/Friends/Work/Others)\\ \\nPlease enter: \")) # We're doing so just to ensure that the user experiences a customized search result temp = [] check = -1 if choice == 1: # This will execute for searches based on contact name query = str( input(\"Please enter the name of the contact you wish to search: \")) for i in range(len(pb)): if query == pb[i][0]: check = i temp.append(pb[i]) elif choice == 2: # This will execute for searches based on contact number query = int( input(\"Please enter the number of the contact you wish to search: \")) for i in range(len(pb)): if query == pb[i][1]: check = i temp.append(pb[i]) elif choice == 3: # This will execute for searches based on contact's e-mail address query = str(input(\"Please enter the e-mail ID\\ of the contact you wish to search: \")) for i in range(len(pb)): if query == pb[i][2]: check = i temp.append(pb[i]) elif choice == 4: # This will execute for searches based on contact''s date of birth query = str(input(\"Please enter the DOB (in dd/mm/yyyy format ONLY)\\ of the contact you wish to search: \")) for i in range(len(pb)): if query == pb[i][3]: check = i temp.append(pb[i]) elif choice == 5: # This will execute for searches based on contact category query = str( input(\"Please enter the category of the contact you wish to search: \")) for i in range(len(pb)): if query == pb[i][4]: check = i temp.append(pb[i]) # All contacts under query category will be shown using this feature else: # If the user enters any other choice then the search will be unsuccessful print(\"Invalid search criteria\") return -1 # returning -1 indicates that the search was unsuccessful # all the searches are stored in temp and all the results will be displayed with # the help of display function if check == -1: return -1 # returning -1 indicates that the query did not exist in the directory else: display_all(temp) return check # we're just returning a index value wiz not -1 to calling function just to notify # that the search worked successfully # this function displays all content of phonebook pbdef display_all(pb): if not pb: # if display function is called after deleting all contacts then the len will be 0 # And then without this condition it will throw an error print(\"List is empty: []\") else: for i in range(len(pb)): print(pb[i]) def thanks():# A simple gesture of courtesy towards the user to enhance user experience print(\"********************************************************************\") print(\"Thank you for using our Smartphone directory system.\") print(\"Please visit again!\") print(\"********************************************************************\") sys.exit(\"Goodbye, have a nice day ahead!\") # Main function codeprint(\"....................................................................\")print(\"Hello dear user, welcome to our smartphone directory system\")print(\"You may now proceed to explore this directory\")print(\"....................................................................\")# This is solely meant for decoration purpose only.# You're free to modify your interface as per your will to make it look interactive ch = 1pb = initial_phonebook()while ch in (1, 2, 3, 4, 5): ch = menu() if ch == 1: pb = add_contact(pb) elif ch == 2: pb = remove_existing(pb) elif ch == 3: pb = delete_all(pb) elif ch == 4: d = search_existing(pb) if d == -1: print(\"The contact does not exist. Please try again\") elif ch == 5: display_all(pb) else: thanks()",
"e": 36639,
"s": 26015,
"text": null
},
{
"code": null,
"e": 36754,
"s": 36639,
"text": "Output : We shall see the output of this program segment by segment.Initially, the following will be displayed : "
},
{
"code": null,
"e": 37041,
"s": 36754,
"text": ".................................................................... Hello dear user, welcome to our smartphone directory system You may now proceed to explore this directory .................................................................... Please enter initial number of contacts: "
},
{
"code": null,
"e": 37088,
"s": 37041,
"text": "In the starting, we shall enter 2 contacts : "
},
{
"code": null,
"e": 38251,
"s": 37088,
"text": "Please enter initial number of contacts: 2 []Enter contact 1 details in the following order (ONLY): NOTE: * indicates mandatory fields .................................................................... Enter name*: Geeks Enter number*: 9999999999 Enter e-mail address: [email protected] Enter date of birth(dd/mm/yy): 01/01/01 Enter category(Family/Friends/Work/Others): WorkEnter contact 2 details in the following order (ONLY): NOTE: * indicates mandatory fields .................................................................... Enter name*: Sample Enter number*: 1234567890 Enter e-mail address: Enter date of birth(dd/mm/yy): Enter category(Family/Friends/Work/Others): [[‘Geeks’, 9999999999, ‘[email protected]’, ’01/01/01′, ‘Work’], [‘Sample’, 1234567890, None, None, None]] ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice: "
},
{
"code": null,
"e": 38319,
"s": 38251,
"text": "Now to add a new contact, according to the menu we will press 1 : "
},
{
"code": null,
"e": 38873,
"s": 38319,
"text": "Please enter your choice: 1 Enter name: Emergency Enter number: 108 Enter e-mail address: Enter date of birth(dd/mm/yy): Enter category(Family/Friends/Work/Others): ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice: "
},
{
"code": null,
"e": 38919,
"s": 38873,
"text": "We can see all the contacts by pressing 5 : "
},
{
"code": null,
"e": 39462,
"s": 38919,
"text": "Please enter your choice: 5 [‘Geeks’, 9999999999, ‘[email protected]’, ’01/01/01′, ‘Work’] [‘Sample’, 1234567890, None, None, None] [‘Emergency’, 108, ”, ”, ”] ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice: "
},
{
"code": null,
"e": 39506,
"s": 39462,
"text": "To delete a contact, we have to enter 2 : "
},
{
"code": null,
"e": 40060,
"s": 39506,
"text": "Please enter your choice: 2 Please enter the name of the contact you wish to remove: Sample [‘Sample’, 1234567890, None, None, None] This query has now been removed ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice: "
},
{
"code": null,
"e": 40108,
"s": 40060,
"text": "To search for a contact, we have to press 4 : "
},
{
"code": null,
"e": 40766,
"s": 40108,
"text": "Please enter your choice: 4 Enter search criteria1. Name 2. Number 3. Email-id 4. DOB 5. Category(Family/Friends/Work/Others) Please enter: 2 Please enter the number of the contact you wish to search: 9999999999 [‘Geeks’, 9999999999, ‘[email protected]’, ’01/01/01′, ‘Work’] ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice: "
},
{
"code": null,
"e": 40815,
"s": 40766,
"text": "We can delete all the contacts by pressing 3 : "
},
{
"code": null,
"e": 41232,
"s": 40815,
"text": "Please enter your choice: 3 ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice: "
},
{
"code": null,
"e": 41325,
"s": 41232,
"text": "To view all the contacts press 5, as we have just deleted them nothing will be displayed : "
},
{
"code": null,
"e": 41760,
"s": 41325,
"text": "Please enter your choice: 5 List is empty: [] ******************************************************************** SMARTPHONE DIRECTORY ******************************************************************** You can now perform the following operations on this phonebook1. Add a new contact 2. Remove an existing contact 3. Delete all contacts 4. Search for a contact 5. Display all contacts 6. Exit phonebook Please enter your choice: "
},
{
"code": null,
"e": 41793,
"s": 41760,
"text": "To exit the program, enter 6 : "
},
{
"code": null,
"e": 42034,
"s": 41793,
"text": "Please enter your choice: 6 ******************************************************************** Thank you for using our Smartphone directory system. Please visit again! ******************************************************************** "
},
{
"code": null,
"e": 42045,
"s": 42036,
"text": "sweetyty"
},
{
"code": null,
"e": 42061,
"s": 42045,
"text": "Python-projects"
},
{
"code": null,
"e": 42080,
"s": 42061,
"text": "school-programming"
},
{
"code": null,
"e": 42087,
"s": 42080,
"text": "Python"
},
{
"code": null,
"e": 42185,
"s": 42087,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42217,
"s": 42185,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 42273,
"s": 42217,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 42315,
"s": 42273,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 42357,
"s": 42315,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 42412,
"s": 42357,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 42434,
"s": 42412,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 42473,
"s": 42434,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 42504,
"s": 42473,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 42533,
"s": 42504,
"text": "Create a directory in Python"
}
] |
Simple Plot in Python using Matplotlib - GeeksforGeeks | 04 Jan, 2022
Matplotlib is a Python library that helps in visualizing and analyzing the data and helps in better understanding of the data with the help of graphical, pictorial visualizations that can be simulated using the matplotlib library. Matplotlib is a comprehensive library for static, animated and interactive visualizations.
Step 1: Open command manager (just type “cmd” in your windows start search bar)Step 2: Type the below command in the terminal.
cd Desktop
Step 3: Then type the following command.
pip install matplotlib
Python3
# importing the required module import matplotlib.pyplot as plt # x axis values x = [1,2,3] # corresponding y axis values y = [2,4,1] # plotting the points plt.plot(x, y) # naming the x axis plt.xlabel('x - axis') # naming the y axis plt.ylabel('y - axis') # giving a title to my graph plt.title('My first graph!') # function to show the plot plt.show()
Output:
The code seems self-explanatory. Following steps were followed:
Define the x-axis and corresponding y-axis values as lists.
Plot them on canvas using .plot() function.
Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions.
Give a title to your plot using .title() function.
Finally, to view your plot, we use .show() function.
Let’s have a look at some of the basic functions that are often used in matplotlib.
Note: Try removing the features added one by one and understand how does the output result changes
Example 1:
Python3
import matplotlib.pyplot as plt a = [1, 2, 3, 4, 5]b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]plt.plot(a) # o is for circles and r is # for redplt.plot(b, "or") plt.plot(list(range(0, 22, 3))) # naming the x-axisplt.xlabel('Day ->') # naming the y-axisplt.ylabel('Temp ->') c = [4, 2, 6, 8, 3, 20, 13, 15]plt.plot(c, label = '4th Rep') # get current axes commandax = plt.gca() # get command over the individual# boundary line of the graph bodyax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) # set the range or the bounds of # the left boundary line to fixed rangeax.spines['left'].set_bounds(-3, 40) # set the interval by which # the x-axis set the marksplt.xticks(list(range(-3, 10))) # set the intervals by which y-axis# set the marksplt.yticks(list(range(-3, 20, 3))) # legend denotes that what color # signifies whatax.legend(['1st Rep', '2nd Rep', '3rd Rep', '4th Rep']) # annotate command helps to write# ON THE GRAPH any text xy denotes # the position on the graphplt.annotate('Temperature V / s Days', xy = (1.01, -2.15)) # gives a title to the Graphplt.title('All Features Discussed') plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as plt a = [1, 2, 3, 4, 5]b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]c = [4, 2, 6, 8, 3, 20, 13, 15] # use fig whenever u want the # output in a new window also # specify the window size you# want ans to be displayedfig = plt.figure(figsize =(10, 10)) # creating multiple plots in a # single plotsub1 = plt.subplot(2, 2, 1)sub2 = plt.subplot(2, 2, 2)sub3 = plt.subplot(2, 2, 3)sub4 = plt.subplot(2, 2, 4) sub1.plot(a, 'sb') # sets how the display subplot # x axis values advances by 1# within the specified rangesub1.set_xticks(list(range(0, 10, 1)))sub1.set_title('1st Rep') sub2.plot(b, 'or') # sets how the display subplot x axis# values advances by 2 within the# specified rangesub2.set_xticks(list(range(0, 10, 2)))sub2.set_title('2nd Rep') # can directly pass a list in the plot# function instead adding the referencesub3.plot(list(range(0, 22, 3)), 'vg')sub3.set_xticks(list(range(0, 10, 1)))sub3.set_title('3rd Rep') sub4.plot(c, 'Dm') # similarly we can set the ticks for # the y-axis range(start(inclusive),# end(exclusive), step)sub4.set_yticks(list(range(0, 24, 2)))sub4.set_title('4th Rep') # without writing plt.show() no plot# will be visibleplt.show()
Output:
nnr223442
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 24575,
"s": 24547,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24897,
"s": 24575,
"text": "Matplotlib is a Python library that helps in visualizing and analyzing the data and helps in better understanding of the data with the help of graphical, pictorial visualizations that can be simulated using the matplotlib library. Matplotlib is a comprehensive library for static, animated and interactive visualizations."
},
{
"code": null,
"e": 25024,
"s": 24897,
"text": "Step 1: Open command manager (just type “cmd” in your windows start search bar)Step 2: Type the below command in the terminal."
},
{
"code": null,
"e": 25035,
"s": 25024,
"text": "cd Desktop"
},
{
"code": null,
"e": 25076,
"s": 25035,
"text": "Step 3: Then type the following command."
},
{
"code": null,
"e": 25099,
"s": 25076,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 25107,
"s": 25099,
"text": "Python3"
},
{
"code": "# importing the required module import matplotlib.pyplot as plt # x axis values x = [1,2,3] # corresponding y axis values y = [2,4,1] # plotting the points plt.plot(x, y) # naming the x axis plt.xlabel('x - axis') # naming the y axis plt.ylabel('y - axis') # giving a title to my graph plt.title('My first graph!') # function to show the plot plt.show() ",
"e": 25483,
"s": 25107,
"text": null
},
{
"code": null,
"e": 25491,
"s": 25483,
"text": "Output:"
},
{
"code": null,
"e": 25555,
"s": 25491,
"text": "The code seems self-explanatory. Following steps were followed:"
},
{
"code": null,
"e": 25615,
"s": 25555,
"text": "Define the x-axis and corresponding y-axis values as lists."
},
{
"code": null,
"e": 25659,
"s": 25615,
"text": "Plot them on canvas using .plot() function."
},
{
"code": null,
"e": 25733,
"s": 25659,
"text": "Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions."
},
{
"code": null,
"e": 25784,
"s": 25733,
"text": "Give a title to your plot using .title() function."
},
{
"code": null,
"e": 25837,
"s": 25784,
"text": "Finally, to view your plot, we use .show() function."
},
{
"code": null,
"e": 25921,
"s": 25837,
"text": "Let’s have a look at some of the basic functions that are often used in matplotlib."
},
{
"code": null,
"e": 26020,
"s": 25921,
"text": "Note: Try removing the features added one by one and understand how does the output result changes"
},
{
"code": null,
"e": 26031,
"s": 26020,
"text": "Example 1:"
},
{
"code": null,
"e": 26039,
"s": 26031,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt a = [1, 2, 3, 4, 5]b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]plt.plot(a) # o is for circles and r is # for redplt.plot(b, \"or\") plt.plot(list(range(0, 22, 3))) # naming the x-axisplt.xlabel('Day ->') # naming the y-axisplt.ylabel('Temp ->') c = [4, 2, 6, 8, 3, 20, 13, 15]plt.plot(c, label = '4th Rep') # get current axes commandax = plt.gca() # get command over the individual# boundary line of the graph bodyax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) # set the range or the bounds of # the left boundary line to fixed rangeax.spines['left'].set_bounds(-3, 40) # set the interval by which # the x-axis set the marksplt.xticks(list(range(-3, 10))) # set the intervals by which y-axis# set the marksplt.yticks(list(range(-3, 20, 3))) # legend denotes that what color # signifies whatax.legend(['1st Rep', '2nd Rep', '3rd Rep', '4th Rep']) # annotate command helps to write# ON THE GRAPH any text xy denotes # the position on the graphplt.annotate('Temperature V / s Days', xy = (1.01, -2.15)) # gives a title to the Graphplt.title('All Features Discussed') plt.show()",
"e": 27180,
"s": 26039,
"text": null
},
{
"code": null,
"e": 27188,
"s": 27180,
"text": "Output:"
},
{
"code": null,
"e": 27199,
"s": 27188,
"text": "Example 2:"
},
{
"code": null,
"e": 27207,
"s": 27199,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt a = [1, 2, 3, 4, 5]b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]c = [4, 2, 6, 8, 3, 20, 13, 15] # use fig whenever u want the # output in a new window also # specify the window size you# want ans to be displayedfig = plt.figure(figsize =(10, 10)) # creating multiple plots in a # single plotsub1 = plt.subplot(2, 2, 1)sub2 = plt.subplot(2, 2, 2)sub3 = plt.subplot(2, 2, 3)sub4 = plt.subplot(2, 2, 4) sub1.plot(a, 'sb') # sets how the display subplot # x axis values advances by 1# within the specified rangesub1.set_xticks(list(range(0, 10, 1)))sub1.set_title('1st Rep') sub2.plot(b, 'or') # sets how the display subplot x axis# values advances by 2 within the# specified rangesub2.set_xticks(list(range(0, 10, 2)))sub2.set_title('2nd Rep') # can directly pass a list in the plot# function instead adding the referencesub3.plot(list(range(0, 22, 3)), 'vg')sub3.set_xticks(list(range(0, 10, 1)))sub3.set_title('3rd Rep') sub4.plot(c, 'Dm') # similarly we can set the ticks for # the y-axis range(start(inclusive),# end(exclusive), step)sub4.set_yticks(list(range(0, 24, 2)))sub4.set_title('4th Rep') # without writing plt.show() no plot# will be visibleplt.show()",
"e": 28406,
"s": 27207,
"text": null
},
{
"code": null,
"e": 28414,
"s": 28406,
"text": "Output:"
},
{
"code": null,
"e": 28424,
"s": 28414,
"text": "nnr223442"
},
{
"code": null,
"e": 28442,
"s": 28424,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28449,
"s": 28442,
"text": "Python"
},
{
"code": null,
"e": 28465,
"s": 28449,
"text": "Write From Home"
},
{
"code": null,
"e": 28563,
"s": 28465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28572,
"s": 28563,
"text": "Comments"
},
{
"code": null,
"e": 28585,
"s": 28572,
"text": "Old Comments"
},
{
"code": null,
"e": 28603,
"s": 28585,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28638,
"s": 28603,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28660,
"s": 28638,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28692,
"s": 28660,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28722,
"s": 28692,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28758,
"s": 28722,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28794,
"s": 28758,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 28810,
"s": 28794,
"text": "Python infinity"
},
{
"code": null,
"e": 28871,
"s": 28810,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Adding a Page break/new page in SAP Script | To add a new page, you can use Control command NEW-PAGE in Transaction SE71.
NEW-PAGE [page_options] [ spool_options]
This statement creates a new page in the current list and writes the subsequent list output into a spool list.
In T-Code: SE38 Print Program, you can use Function Module CONTROL_FORM to call NEW-PAGE command as below −
CALL FUNCTION 'CONTROL_FORM'
EXPORTING
COMMAND = 'NEW-PAGE'
EXCEPTIONS
UNOPENED = 1
UNSTARTED = 2
OTHERS = 3. | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To add a new page, you can use Control command NEW-PAGE in Transaction SE71."
},
{
"code": null,
"e": 1180,
"s": 1139,
"text": "NEW-PAGE [page_options] [ spool_options]"
},
{
"code": null,
"e": 1291,
"s": 1180,
"text": "This statement creates a new page in the current list and writes the subsequent list output into a spool list."
},
{
"code": null,
"e": 1399,
"s": 1291,
"text": "In T-Code: SE38 Print Program, you can use Function Module CONTROL_FORM to call NEW-PAGE command as below −"
},
{
"code": null,
"e": 1515,
"s": 1399,
"text": "CALL FUNCTION 'CONTROL_FORM'\n\nEXPORTING\n\nCOMMAND = 'NEW-PAGE'\n\nEXCEPTIONS\n\nUNOPENED = 1\n\nUNSTARTED = 2\n\nOTHERS = 3."
}
] |
Minimum String in C++ | Suppose we have two strings s and t of same length, and both are in lowercase letters. Consider we have rearranged s at first into any order, then count the minimum number of changes needed to turn s into t.
So, if the input is like s = "eccynue", t = "science", then the output will be 2 as if we rearrange "eccynue" to "yccence", then replace y with s and second c with i, it will be "science".
To solve this, we will follow these steps −
ret := 0
ret := 0
Define two arrays cnt1 to hold frequency of s and cnt2 to hold frequency of t
Define two arrays cnt1 to hold frequency of s and cnt2 to hold frequency of t
for initialize i := 0, when i < 26, update (increase i by 1), do −ret := ret + max(cnt1[i] - cnt2[i], 0)
for initialize i := 0, when i < 26, update (increase i by 1), do −
ret := ret + max(cnt1[i] - cnt2[i], 0)
ret := ret + max(cnt1[i] - cnt2[i], 0)
return ret
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(string s, string t) {
int ret = 0;
vector <int> cnt1(26);
vector <int> cnt2(26);
for(int i = 0; i < s.size(); i++){
cnt1[s[i] - 'a']++;
}
for(int i = 0; i < t.size(); i++){
cnt2[t[i] - 'a']++;
}
for(int i = 0; i < 26; i++){
ret += max(cnt1[i] - cnt2[i], 0);
}
return ret;
}
};
int main(){
Solution ob;
cout << (ob.solve("eccynue", "science"));
}
"eccynue", "science"
2 | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "Suppose we have two strings s and t of same length, and both are in lowercase letters. Consider we have rearranged s at first into any order, then count the minimum number of changes needed to turn s into t."
},
{
"code": null,
"e": 1459,
"s": 1270,
"text": "So, if the input is like s = \"eccynue\", t = \"science\", then the output will be 2 as if we rearrange \"eccynue\" to \"yccence\", then replace y with s and second c with i, it will be \"science\"."
},
{
"code": null,
"e": 1503,
"s": 1459,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1512,
"s": 1503,
"text": "ret := 0"
},
{
"code": null,
"e": 1521,
"s": 1512,
"text": "ret := 0"
},
{
"code": null,
"e": 1599,
"s": 1521,
"text": "Define two arrays cnt1 to hold frequency of s and cnt2 to hold frequency of t"
},
{
"code": null,
"e": 1677,
"s": 1599,
"text": "Define two arrays cnt1 to hold frequency of s and cnt2 to hold frequency of t"
},
{
"code": null,
"e": 1782,
"s": 1677,
"text": "for initialize i := 0, when i < 26, update (increase i by 1), do −ret := ret + max(cnt1[i] - cnt2[i], 0)"
},
{
"code": null,
"e": 1849,
"s": 1782,
"text": "for initialize i := 0, when i < 26, update (increase i by 1), do −"
},
{
"code": null,
"e": 1888,
"s": 1849,
"text": "ret := ret + max(cnt1[i] - cnt2[i], 0)"
},
{
"code": null,
"e": 1927,
"s": 1888,
"text": "ret := ret + max(cnt1[i] - cnt2[i], 0)"
},
{
"code": null,
"e": 1938,
"s": 1927,
"text": "return ret"
},
{
"code": null,
"e": 1949,
"s": 1938,
"text": "return ret"
},
{
"code": null,
"e": 2019,
"s": 1949,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2030,
"s": 2019,
"text": " Live Demo"
},
{
"code": null,
"e": 2559,
"s": 2030,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int solve(string s, string t) {\n int ret = 0;\n vector <int> cnt1(26);\n vector <int> cnt2(26);\n for(int i = 0; i < s.size(); i++){\n cnt1[s[i] - 'a']++;\n }\n for(int i = 0; i < t.size(); i++){\n cnt2[t[i] - 'a']++;\n }\n for(int i = 0; i < 26; i++){\n ret += max(cnt1[i] - cnt2[i], 0);\n }\n return ret;\n }\n};\nint main(){\n Solution ob;\n cout << (ob.solve(\"eccynue\", \"science\"));\n}"
},
{
"code": null,
"e": 2580,
"s": 2559,
"text": "\"eccynue\", \"science\""
},
{
"code": null,
"e": 2582,
"s": 2580,
"text": "2"
}
] |
Apache MXNet - Gluon | Another most important MXNet Python package is Gluon. In this chapter, we will be discussing this package. Gluon provides a clear, concise, and simple API for DL projects. It enables Apache MXNet to prototype, build, and train DL models without forfeiting the training speed.
Blocks form the basis of more complex network designs. In a neural network, as the complexity of neural network increases, we need to move from designing single to entire layers of neurons. For example, NN design like ResNet-152 have a very fair degree of regularity by consisting of blocks of repeated layers.
In the example given below, we will write code a simple block, namely block for a multilayer perceptron.
from mxnet import nd
from mxnet.gluon import nn
x = nd.random.uniform(shape=(2, 20))
N_net = nn.Sequential()
N_net.add(nn.Dense(256, activation='relu'))
N_net.add(nn.Dense(10))
N_net.initialize()
N_net(x)
Output
This produces the following output:
[[ 0.09543004 0.04614332 -0.00286655 -0.07790346 -0.05130241 0.02942038
0.08696645 -0.0190793 -0.04122177 0.05088576]
[ 0.0769287 0.03099706 0.00856576 -0.044672 -0.06926838 0.09132431
0.06786592 -0.06187843 -0.03436674 0.04234696]]
<NDArray 2x10 @cpu(0)>
Steps needed to go from defining layers to defining blocks of one or more layers −
Step 1 − Block take the data as input.
Step 2 − Now, blocks will store the state in the form of parameters. For example, in the above coding example the block contains two hidden layers and we need a place to store parameters for it.
Step 3 − Next block will invoke the forward function to perform forward propagation. It is also called forward computation. As a part of first forward call, blocks initialize the parameters in a lazy fashion.
Step 4 − At last the blocks will invoke backward function and calculate the gradient with reference to their input. Typically, this step is performed automatically.
A sequential block is a special kind of block in which the data flows through a sequence of blocks. In this, each block applied to the output of one before with the first block being applied on the input data itself.
Let us see how sequential class works −
from mxnet import nd
from mxnet.gluon import nn
class MySequential(nn.Block):
def __init__(self, **kwargs):
super(MySequential, self).__init__(**kwargs)
def add(self, block):
self._children[block.name] = block
def forward(self, x):
for block in self._children.values():
x = block(x)
return x
x = nd.random.uniform(shape=(2, 20))
N_net = MySequential()
N_net.add(nn.Dense(256, activation
='relu'))
N_net.add(nn.Dense(10))
N_net.initialize()
N_net(x)
Output
The output is given herewith −
[[ 0.09543004 0.04614332 -0.00286655 -0.07790346 -0.05130241 0.02942038
0.08696645 -0.0190793 -0.04122177 0.05088576]
[ 0.0769287 0.03099706 0.00856576 -0.044672 -0.06926838 0.09132431
0.06786592 -0.06187843 -0.03436674 0.04234696]]
<NDArray 2x10 @cpu(0)>
We can easily go beyond concatenation with sequential block as defined above. But, if we would like to make customisations then the Block class also provides us the required functionality. Block class has a model constructor provided in nn module. We can inherit that model constructor to define the model we want.
In the following example, the MLP class overrides the __init__ and forward functions of the Block class.
Let us see how it works.
class MLP(nn.Block):
def __init__(self, **kwargs):
super(MLP, self).__init__(**kwargs)
self.hidden = nn.Dense(256, activation='relu') # Hidden layer
self.output = nn.Dense(10) # Output layer
def forward(self, x):
hidden_out = self.hidden(x)
return self.output(hidden_out)
x = nd.random.uniform(shape=(2, 20))
N_net = MLP()
N_net.initialize()
N_net(x)
Output
When you run the code, you will see the following output:
[[ 0.07787763 0.00216403 0.01682201 0.03059879 -0.00702019 0.01668715
0.04822846 0.0039432 -0.09300035 -0.04494302]
[ 0.08891078 -0.00625484 -0.01619131 0.0380718 -0.01451489 0.02006172
0.0303478 0.02463485 -0.07605448 -0.04389168]]
<NDArray 2x10 @cpu(0)>
Apache MXNet’s Gluon API comes with a modest number of pre-defined layers. But still at some point, we may find that a new layer is needed. We can easily add a new layer in Gluon API. In this section, we will see how we can create a new layer from scratch.
To create a new layer in Gluon API, we must have to create a class inherits from the Block class which provides the most basic functionality. We can inherit all the pre-defined layers from it directly or via other subclasses.
For creating the new layer, the only instance method needed to be implemented is forward (self, x). This method defines, what exactly our layer is going to do during forward propagation. As discussed earlier also, the back-propagation pass for blocks will be done by Apache MXNet itself automatically.
In the example below, we will be defining a new layer. We will also implement forward() method to normalise the input data by fitting it into a range of [0, 1].
from __future__ import print_function
import mxnet as mx
from mxnet import nd, gluon, autograd
from mxnet.gluon.nn import Dense
mx.random.seed(1)
class NormalizationLayer(gluon.Block):
def __init__(self):
super(NormalizationLayer, self).__init__()
def forward(self, x):
return (x - nd.min(x)) / (nd.max(x) - nd.min(x))
x = nd.random.uniform(shape=(2, 20))
N_net = NormalizationLayer()
N_net.initialize()
N_net(x)
Output
On executing the above program, you will get the following result −
[[0.5216355 0.03835821 0.02284337 0.5945146 0.17334817 0.69329053
0.7782702 1. 0.5508242 0. 0.07058554 0.3677264
0.4366546 0.44362497 0.7192635 0.37616986 0.6728799 0.7032008
0.46907538 0.63514024]
[0.9157533 0.7667402 0.08980197 0.03593295 0.16176797 0.27679572
0.07331014 0.3905285 0.6513384 0.02713427 0.05523694 0.12147208
0.45582628 0.8139887 0.91629887 0.36665893 0.07873632 0.78268915
0.63404864 0.46638715]]
<NDArray 2x20 @cpu(0)>
It may be defined as a process used by Apache MXNet’s to create a symbolic graph of a forward computation. Hybridisation allows MXNet to upsurge the computation performance by optimising the computational symbolic graph. Rather than directly inheriting from Block, in fact, we may find that while implementing existing layers a block inherits from a HybridBlock.
Following are the reasons for this −
Allows us to write custom layers: HybridBlock allows us to write custom layers that can further be used in imperative and symbolic programming both.
Allows us to write custom layers: HybridBlock allows us to write custom layers that can further be used in imperative and symbolic programming both.
Increase computation performance− HybridBlock optimise the computational symbolic graph which allows MXNet to increase computation performance.
Increase computation performance− HybridBlock optimise the computational symbolic graph which allows MXNet to increase computation performance.
In this example, we will be rewriting our example layer, created above, by using HybridBlock:
class NormalizationHybridLayer(gluon.HybridBlock):
def __init__(self):
super(NormalizationHybridLayer, self).__init__()
def hybrid_forward(self, F, x):
return F.broadcast_div(F.broadcast_sub(x, F.min(x)), (F.broadcast_sub(F.max(x), F.min(x))))
layer_hybd = NormalizationHybridLayer()
layer_hybd(nd.array([1, 2, 3, 4, 5, 6], ctx=mx.cpu()))
Output
The output is stated below:
[0. 0.2 0.4 0.6 0.8 1. ]
<NDArray 6 @cpu(0)>
Hybridisation has nothing to do with computation on GPU and one can train hybridised as well as non-hybridised networks on both CPU and GPU.
If we will compare the Block Class and HybridBlock, we will see that HybridBlock already has its forward() method implemented. HybridBlock defines a hybrid_forward() method that needs to be implemented while creating the layers. F argument creates the main difference between forward() and hybrid_forward(). In MXNet community, F argument is referred to as a backend. F can either refer to mxnet.ndarray API (used for imperative programming) or mxnet.symbol API (used for Symbolic programming).
Instead of using custom layers separately, these layers are used with predefined layers. We can use either Sequential or HybridSequential containers to from a sequential neural network. As discussed earlier also, Sequential container inherit from Block and HybridSequential inherit from HybridBlock respectively.
In the example below, we will be creating a simple neural network with a custom layer. The output from Dense (5) layer will be the input of NormalizationHybridLayer. The output of NormalizationHybridLayer will become the input of Dense (1) layer.
net = gluon.nn.HybridSequential()
with net.name_scope():
net.add(Dense(5))
net.add(NormalizationHybridLayer())
net.add(Dense(1))
net.initialize(mx.init.Xavier(magnitude=2.24))
net.hybridize()
input = nd.random_uniform(low=-10, high=10, shape=(10, 2))
net(input)
Output
You will see the following output −
[[-1.1272651]
[-1.2299833]
[-1.0662932]
[-1.1805027]
[-1.3382034]
[-1.2081106]
[-1.1263978]
[-1.2524893]
[-1.1044774]
[-1.316593 ]]
<NDArray 10x1 @cpu(0)>
In a neural network, a layer has a set of parameters associated with it. We sometimes refer them as weights, which is internal state of a layer. These parameters play different roles −
Sometimes these are the ones that we want to learn during backpropagation step.
Sometimes these are the ones that we want to learn during backpropagation step.
Sometimes these are just constants we want to use during forward pass.
Sometimes these are just constants we want to use during forward pass.
If we talk about the programming concept, these parameters (weights) of a block are stored and accessed via ParameterDict class which helps in initialisation, updation, saving, and loading of them.
In the example below, we will be defining two following sets of parameters −
Parameter weights − This is trainable, and its shape is unknown during construction phase. It will be inferred on the first run of forward propagation.
Parameter weights − This is trainable, and its shape is unknown during construction phase. It will be inferred on the first run of forward propagation.
Parameter scale − This is a constant whose value doesn’t change. As opposite to parameter weights, its shape is defined during construction.
Parameter scale − This is a constant whose value doesn’t change. As opposite to parameter weights, its shape is defined during construction.
class NormalizationHybridLayer(gluon.HybridBlock):
def __init__(self, hidden_units, scales):
super(NormalizationHybridLayer, self).__init__()
with self.name_scope():
self.weights = self.params.get('weights',
shape=(hidden_units, 0),
allow_deferred_init=True)
self.scales = self.params.get('scales',
shape=scales.shape,
init=mx.init.Constant(scales.asnumpy()),
differentiable=False)
def hybrid_forward(self, F, x, weights, scales):
normalized_data = F.broadcast_div(F.broadcast_sub(x, F.min(x)),
(F.broadcast_sub(F.max(x), F.min(x))))
weighted_data = F.FullyConnected(normalized_data, weights, num_hidden=self.weights.shape[0], no_bias=True)
scaled_data = F.broadcast_mul(scales, weighted_data)
return scaled_data
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2424,
"s": 2148,
"text": "Another most important MXNet Python package is Gluon. In this chapter, we will be discussing this package. Gluon provides a clear, concise, and simple API for DL projects. It enables Apache MXNet to prototype, build, and train DL models without forfeiting the training speed."
},
{
"code": null,
"e": 2735,
"s": 2424,
"text": "Blocks form the basis of more complex network designs. In a neural network, as the complexity of neural network increases, we need to move from designing single to entire layers of neurons. For example, NN design like ResNet-152 have a very fair degree of regularity by consisting of blocks of repeated layers."
},
{
"code": null,
"e": 2840,
"s": 2735,
"text": "In the example given below, we will write code a simple block, namely block for a multilayer perceptron."
},
{
"code": null,
"e": 3045,
"s": 2840,
"text": "from mxnet import nd\nfrom mxnet.gluon import nn\nx = nd.random.uniform(shape=(2, 20))\nN_net = nn.Sequential()\nN_net.add(nn.Dense(256, activation='relu'))\nN_net.add(nn.Dense(10))\nN_net.initialize()\nN_net(x)"
},
{
"code": null,
"e": 3052,
"s": 3045,
"text": "Output"
},
{
"code": null,
"e": 3088,
"s": 3052,
"text": "This produces the following output:"
},
{
"code": null,
"e": 3345,
"s": 3088,
"text": "[[ 0.09543004 0.04614332 -0.00286655 -0.07790346 -0.05130241 0.02942038\n0.08696645 -0.0190793 -0.04122177 0.05088576]\n[ 0.0769287 0.03099706 0.00856576 -0.044672 -0.06926838 0.09132431\n0.06786592 -0.06187843 -0.03436674 0.04234696]]\n<NDArray 2x10 @cpu(0)>\n"
},
{
"code": null,
"e": 3428,
"s": 3345,
"text": "Steps needed to go from defining layers to defining blocks of one or more layers −"
},
{
"code": null,
"e": 3467,
"s": 3428,
"text": "Step 1 − Block take the data as input."
},
{
"code": null,
"e": 3662,
"s": 3467,
"text": "Step 2 − Now, blocks will store the state in the form of parameters. For example, in the above coding example the block contains two hidden layers and we need a place to store parameters for it."
},
{
"code": null,
"e": 3871,
"s": 3662,
"text": "Step 3 − Next block will invoke the forward function to perform forward propagation. It is also called forward computation. As a part of first forward call, blocks initialize the parameters in a lazy fashion."
},
{
"code": null,
"e": 4036,
"s": 3871,
"text": "Step 4 − At last the blocks will invoke backward function and calculate the gradient with reference to their input. Typically, this step is performed automatically."
},
{
"code": null,
"e": 4253,
"s": 4036,
"text": "A sequential block is a special kind of block in which the data flows through a sequence of blocks. In this, each block applied to the output of one before with the first block being applied on the input data itself."
},
{
"code": null,
"e": 4293,
"s": 4253,
"text": "Let us see how sequential class works −"
},
{
"code": null,
"e": 4776,
"s": 4293,
"text": "from mxnet import nd\nfrom mxnet.gluon import nn\nclass MySequential(nn.Block):\n def __init__(self, **kwargs):\n super(MySequential, self).__init__(**kwargs)\n\n def add(self, block):\n self._children[block.name] = block\n def forward(self, x):\n for block in self._children.values():\n x = block(x)\n return x\nx = nd.random.uniform(shape=(2, 20))\nN_net = MySequential()\nN_net.add(nn.Dense(256, activation\n='relu'))\nN_net.add(nn.Dense(10))\nN_net.initialize()\nN_net(x)"
},
{
"code": null,
"e": 4783,
"s": 4776,
"text": "Output"
},
{
"code": null,
"e": 4814,
"s": 4783,
"text": "The output is given herewith −"
},
{
"code": null,
"e": 5071,
"s": 4814,
"text": "[[ 0.09543004 0.04614332 -0.00286655 -0.07790346 -0.05130241 0.02942038\n0.08696645 -0.0190793 -0.04122177 0.05088576]\n[ 0.0769287 0.03099706 0.00856576 -0.044672 -0.06926838 0.09132431\n0.06786592 -0.06187843 -0.03436674 0.04234696]]\n<NDArray 2x10 @cpu(0)>\n"
},
{
"code": null,
"e": 5386,
"s": 5071,
"text": "We can easily go beyond concatenation with sequential block as defined above. But, if we would like to make customisations then the Block class also provides us the required functionality. Block class has a model constructor provided in nn module. We can inherit that model constructor to define the model we want."
},
{
"code": null,
"e": 5491,
"s": 5386,
"text": "In the following example, the MLP class overrides the __init__ and forward functions of the Block class."
},
{
"code": null,
"e": 5516,
"s": 5491,
"text": "Let us see how it works."
},
{
"code": null,
"e": 5906,
"s": 5516,
"text": "class MLP(nn.Block):\n\n def __init__(self, **kwargs):\n super(MLP, self).__init__(**kwargs)\n self.hidden = nn.Dense(256, activation='relu') # Hidden layer\n self.output = nn.Dense(10) # Output layer\n\n\n def forward(self, x):\n hidden_out = self.hidden(x)\n return self.output(hidden_out)\nx = nd.random.uniform(shape=(2, 20))\nN_net = MLP()\nN_net.initialize()\nN_net(x)"
},
{
"code": null,
"e": 5913,
"s": 5906,
"text": "Output"
},
{
"code": null,
"e": 5971,
"s": 5913,
"text": "When you run the code, you will see the following output:"
},
{
"code": null,
"e": 6228,
"s": 5971,
"text": "[[ 0.07787763 0.00216403 0.01682201 0.03059879 -0.00702019 0.01668715\n0.04822846 0.0039432 -0.09300035 -0.04494302]\n[ 0.08891078 -0.00625484 -0.01619131 0.0380718 -0.01451489 0.02006172\n0.0303478 0.02463485 -0.07605448 -0.04389168]]\n<NDArray 2x10 @cpu(0)>\n"
},
{
"code": null,
"e": 6485,
"s": 6228,
"text": "Apache MXNet’s Gluon API comes with a modest number of pre-defined layers. But still at some point, we may find that a new layer is needed. We can easily add a new layer in Gluon API. In this section, we will see how we can create a new layer from scratch."
},
{
"code": null,
"e": 6711,
"s": 6485,
"text": "To create a new layer in Gluon API, we must have to create a class inherits from the Block class which provides the most basic functionality. We can inherit all the pre-defined layers from it directly or via other subclasses."
},
{
"code": null,
"e": 7013,
"s": 6711,
"text": "For creating the new layer, the only instance method needed to be implemented is forward (self, x). This method defines, what exactly our layer is going to do during forward propagation. As discussed earlier also, the back-propagation pass for blocks will be done by Apache MXNet itself automatically."
},
{
"code": null,
"e": 7174,
"s": 7013,
"text": "In the example below, we will be defining a new layer. We will also implement forward() method to normalise the input data by fitting it into a range of [0, 1]."
},
{
"code": null,
"e": 7606,
"s": 7174,
"text": "from __future__ import print_function\nimport mxnet as mx\nfrom mxnet import nd, gluon, autograd\nfrom mxnet.gluon.nn import Dense\nmx.random.seed(1)\nclass NormalizationLayer(gluon.Block):\n def __init__(self):\n super(NormalizationLayer, self).__init__()\n\n def forward(self, x):\n return (x - nd.min(x)) / (nd.max(x) - nd.min(x))\nx = nd.random.uniform(shape=(2, 20))\nN_net = NormalizationLayer()\nN_net.initialize()\nN_net(x)"
},
{
"code": null,
"e": 7613,
"s": 7606,
"text": "Output"
},
{
"code": null,
"e": 7681,
"s": 7613,
"text": "On executing the above program, you will get the following result −"
},
{
"code": null,
"e": 8129,
"s": 7681,
"text": "[[0.5216355 0.03835821 0.02284337 0.5945146 0.17334817 0.69329053\n0.7782702 1. 0.5508242 0. 0.07058554 0.3677264\n0.4366546 0.44362497 0.7192635 0.37616986 0.6728799 0.7032008\n\n 0.46907538 0.63514024]\n[0.9157533 0.7667402 0.08980197 0.03593295 0.16176797 0.27679572\n 0.07331014 0.3905285 0.6513384 0.02713427 0.05523694 0.12147208\n 0.45582628 0.8139887 0.91629887 0.36665893 0.07873632 0.78268915\n 0.63404864 0.46638715]]\n <NDArray 2x20 @cpu(0)>\n"
},
{
"code": null,
"e": 8492,
"s": 8129,
"text": "It may be defined as a process used by Apache MXNet’s to create a symbolic graph of a forward computation. Hybridisation allows MXNet to upsurge the computation performance by optimising the computational symbolic graph. Rather than directly inheriting from Block, in fact, we may find that while implementing existing layers a block inherits from a HybridBlock."
},
{
"code": null,
"e": 8529,
"s": 8492,
"text": "Following are the reasons for this −"
},
{
"code": null,
"e": 8678,
"s": 8529,
"text": "Allows us to write custom layers: HybridBlock allows us to write custom layers that can further be used in imperative and symbolic programming both."
},
{
"code": null,
"e": 8827,
"s": 8678,
"text": "Allows us to write custom layers: HybridBlock allows us to write custom layers that can further be used in imperative and symbolic programming both."
},
{
"code": null,
"e": 8971,
"s": 8827,
"text": "Increase computation performance− HybridBlock optimise the computational symbolic graph which allows MXNet to increase computation performance."
},
{
"code": null,
"e": 9115,
"s": 8971,
"text": "Increase computation performance− HybridBlock optimise the computational symbolic graph which allows MXNet to increase computation performance."
},
{
"code": null,
"e": 9209,
"s": 9115,
"text": "In this example, we will be rewriting our example layer, created above, by using HybridBlock:"
},
{
"code": null,
"e": 9568,
"s": 9209,
"text": "class NormalizationHybridLayer(gluon.HybridBlock):\n def __init__(self):\n super(NormalizationHybridLayer, self).__init__()\n\n def hybrid_forward(self, F, x):\n return F.broadcast_div(F.broadcast_sub(x, F.min(x)), (F.broadcast_sub(F.max(x), F.min(x))))\n\nlayer_hybd = NormalizationHybridLayer()\nlayer_hybd(nd.array([1, 2, 3, 4, 5, 6], ctx=mx.cpu()))"
},
{
"code": null,
"e": 9575,
"s": 9568,
"text": "Output"
},
{
"code": null,
"e": 9603,
"s": 9575,
"text": "The output is stated below:"
},
{
"code": null,
"e": 9649,
"s": 9603,
"text": "[0. 0.2 0.4 0.6 0.8 1. ]\n<NDArray 6 @cpu(0)>\n"
},
{
"code": null,
"e": 9790,
"s": 9649,
"text": "Hybridisation has nothing to do with computation on GPU and one can train hybridised as well as non-hybridised networks on both CPU and GPU."
},
{
"code": null,
"e": 10285,
"s": 9790,
"text": "If we will compare the Block Class and HybridBlock, we will see that HybridBlock already has its forward() method implemented. HybridBlock defines a hybrid_forward() method that needs to be implemented while creating the layers. F argument creates the main difference between forward() and hybrid_forward(). In MXNet community, F argument is referred to as a backend. F can either refer to mxnet.ndarray API (used for imperative programming) or mxnet.symbol API (used for Symbolic programming)."
},
{
"code": null,
"e": 10598,
"s": 10285,
"text": "Instead of using custom layers separately, these layers are used with predefined layers. We can use either Sequential or HybridSequential containers to from a sequential neural network. As discussed earlier also, Sequential container inherit from Block and HybridSequential inherit from HybridBlock respectively."
},
{
"code": null,
"e": 10845,
"s": 10598,
"text": "In the example below, we will be creating a simple neural network with a custom layer. The output from Dense (5) layer will be the input of NormalizationHybridLayer. The output of NormalizationHybridLayer will become the input of Dense (1) layer."
},
{
"code": null,
"e": 11107,
"s": 10845,
"text": "net = gluon.nn.HybridSequential()\nwith net.name_scope():\nnet.add(Dense(5))\nnet.add(NormalizationHybridLayer())\nnet.add(Dense(1))\nnet.initialize(mx.init.Xavier(magnitude=2.24))\nnet.hybridize()\ninput = nd.random_uniform(low=-10, high=10, shape=(10, 2))\nnet(input)"
},
{
"code": null,
"e": 11114,
"s": 11107,
"text": "Output"
},
{
"code": null,
"e": 11150,
"s": 11114,
"text": "You will see the following output −"
},
{
"code": null,
"e": 11318,
"s": 11150,
"text": "[[-1.1272651]\n [-1.2299833]\n [-1.0662932]\n [-1.1805027]\n [-1.3382034]\n [-1.2081106]\n [-1.1263978]\n [-1.2524893]\n \n [-1.1044774]\n\n [-1.316593 ]]\n<NDArray 10x1 @cpu(0)>\n"
},
{
"code": null,
"e": 11503,
"s": 11318,
"text": "In a neural network, a layer has a set of parameters associated with it. We sometimes refer them as weights, which is internal state of a layer. These parameters play different roles −"
},
{
"code": null,
"e": 11583,
"s": 11503,
"text": "Sometimes these are the ones that we want to learn during backpropagation step."
},
{
"code": null,
"e": 11663,
"s": 11583,
"text": "Sometimes these are the ones that we want to learn during backpropagation step."
},
{
"code": null,
"e": 11734,
"s": 11663,
"text": "Sometimes these are just constants we want to use during forward pass."
},
{
"code": null,
"e": 11805,
"s": 11734,
"text": "Sometimes these are just constants we want to use during forward pass."
},
{
"code": null,
"e": 12003,
"s": 11805,
"text": "If we talk about the programming concept, these parameters (weights) of a block are stored and accessed via ParameterDict class which helps in initialisation, updation, saving, and loading of them."
},
{
"code": null,
"e": 12080,
"s": 12003,
"text": "In the example below, we will be defining two following sets of parameters −"
},
{
"code": null,
"e": 12232,
"s": 12080,
"text": "Parameter weights − This is trainable, and its shape is unknown during construction phase. It will be inferred on the first run of forward propagation."
},
{
"code": null,
"e": 12384,
"s": 12232,
"text": "Parameter weights − This is trainable, and its shape is unknown during construction phase. It will be inferred on the first run of forward propagation."
},
{
"code": null,
"e": 12525,
"s": 12384,
"text": "Parameter scale − This is a constant whose value doesn’t change. As opposite to parameter weights, its shape is defined during construction."
},
{
"code": null,
"e": 12666,
"s": 12525,
"text": "Parameter scale − This is a constant whose value doesn’t change. As opposite to parameter weights, its shape is defined during construction."
},
{
"code": null,
"e": 13487,
"s": 12666,
"text": "class NormalizationHybridLayer(gluon.HybridBlock):\n def __init__(self, hidden_units, scales):\n super(NormalizationHybridLayer, self).__init__()\n with self.name_scope():\n self.weights = self.params.get('weights',\n shape=(hidden_units, 0),\n allow_deferred_init=True)\n self.scales = self.params.get('scales',\n shape=scales.shape,\n init=mx.init.Constant(scales.asnumpy()),\n differentiable=False)\n def hybrid_forward(self, F, x, weights, scales):\n normalized_data = F.broadcast_div(F.broadcast_sub(x, F.min(x)),\n (F.broadcast_sub(F.max(x), F.min(x))))\n weighted_data = F.FullyConnected(normalized_data, weights, num_hidden=self.weights.shape[0], no_bias=True)\n scaled_data = F.broadcast_mul(scales, weighted_data)\nreturn scaled_data"
},
{
"code": null,
"e": 13522,
"s": 13487,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 13541,
"s": 13522,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 13576,
"s": 13541,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13597,
"s": 13576,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 13630,
"s": 13597,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13643,
"s": 13630,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 13678,
"s": 13643,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13696,
"s": 13678,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 13729,
"s": 13696,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13747,
"s": 13729,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 13780,
"s": 13747,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13798,
"s": 13780,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 13805,
"s": 13798,
"text": " Print"
},
{
"code": null,
"e": 13816,
"s": 13805,
"text": " Add Notes"
}
] |
How to have a function return a figure in Python (using Matplotlib)? | To have a function return a figure in Python (using Matplotlib), we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create x and y data points using numpy.
Make a function plot(x, y) that creates a new figure or activate an existing figure using figure() method.
Make a function plot(x, y) that creates a new figure or activate an existing figure using figure() method.
Plot the x and y data points using plot() method; return fig instance.
Plot the x and y data points using plot() method; return fig instance.
Call plot(x, y) method and store the figure instance in a variable, f.
Call plot(x, y) method and store the figure instance in a variable, f.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def plot(x, y):
fig = plt.figure()
plt.plot(x, y)
return fig
x = np.linspace(-10, 10, 100)
y = np.sin(x)
f = plot(x, y)
plt.show() | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "To have a function return a figure in Python (using Matplotlib), we can take the following steps −"
},
{
"code": null,
"e": 1237,
"s": 1161,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1313,
"s": 1237,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1353,
"s": 1313,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1393,
"s": 1353,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1500,
"s": 1393,
"text": "Make a function plot(x, y) that creates a new figure or activate an existing figure using figure() method."
},
{
"code": null,
"e": 1607,
"s": 1500,
"text": "Make a function plot(x, y) that creates a new figure or activate an existing figure using figure() method."
},
{
"code": null,
"e": 1678,
"s": 1607,
"text": "Plot the x and y data points using plot() method; return fig instance."
},
{
"code": null,
"e": 1749,
"s": 1678,
"text": "Plot the x and y data points using plot() method; return fig instance."
},
{
"code": null,
"e": 1820,
"s": 1749,
"text": "Call plot(x, y) method and store the figure instance in a variable, f."
},
{
"code": null,
"e": 1891,
"s": 1820,
"text": "Call plot(x, y) method and store the figure instance in a variable, f."
},
{
"code": null,
"e": 1933,
"s": 1891,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1975,
"s": 1933,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2263,
"s": 1975,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndef plot(x, y):\n fig = plt.figure()\n plt.plot(x, y)\n return fig\n\nx = np.linspace(-10, 10, 100)\ny = np.sin(x)\n\nf = plot(x, y)\n\nplt.show()"
}
] |
Word-level text generation using GPT-2, LSTM and Markov Chain | Towards Data Science | Natural Language Generation (NLG) or Text Generation is a subfield of Natural Language Processing (NLP). Its goal is to generate meaningful phrases and sentences in the form of human-written text. It has a wide range of use cases: writing long form content (eg reports, articles), product descriptions, social media posts, chatbots etc.
The goal of this project is to implement and test various approaches to text generation: starting from simple Markov Chains, through neural networks (LSTM), to transformers architecture (GPT-2). All these models will be used to generate text of a fairy tale.
Table of contents:
Fairy tales datasetText generation with Markov ChainText generation with LSTMText generation with GPT-2
Fairy tales dataset
Text generation with Markov Chain
Text generation with LSTM
Text generation with GPT-2
The dataset was created based on content available online — it was gathered from two sources: scraped from Folklore and MythologyElectronic Texts website and downloaded from Kaggle. The total size of gathered content is 20MB, consisting of 3,150 text files with over 3.7 M words.
In order to make computations faster, the train and test dataset were created only from 800 randomly selected files. Train set contains 766,970 words (50,487 unique) and test set: 202,860 words(21,630 unique).
Markov Chain is one of the earliest algorithms used for text generation (eg, in old versions of smartphone keyboards). It is a stochastic model, meaning that it’s based on random probability distribution. Markov Chain models the future state (in case of text generation, the next word) solely based on the previous state (previous word or sequence). The model is memory-less — the prediction depends only on the current state of the variable (it forgets the past states; it is independent of preceding states). On the other hand, it’s simple, fast to execute and light on memory.
Using Markov Chain model for text generation requires the following steps:
Load the dataset and preprocess text.Extract from text the sequences of length n (current state) and the next words (future state).Build the transition matrix with the probability values of state transitions.Predict the next word based on the probability distribution for state transition.
Load the dataset and preprocess text.
Extract from text the sequences of length n (current state) and the next words (future state).
Build the transition matrix with the probability values of state transitions.
Predict the next word based on the probability distribution for state transition.
There is a notebook with all the details of Markov Chain implementation.
Let’s start with text preprocessing — it’s different from the preprocessing used for other NLP tasks, eg text classification. Since the model needs to learn how to create text based on the input, we cannot remove stop words or apply stemming or lammetization. Text preprocessing for this project includes:
Newline characters removal — just to make it simpler for the model (since the text contained many “incorrect” newline characters; in proper solution, they should be kept to teach the model to correctly format the text)
Add whitespace before and after punctuation characters — in order to recognize punctuation as separate tokens.
Remove double whitespace characters.
Tokenize text (space tokenization).
Map tokens to indexes (and create token2ind and ind2token dictionaries).
Example text after preprocessing:
Once upon a time there lived a sultan who loved his garden dearly , and planted it with trees and flowers and fruits from all parts of the world . He went to see them three times every day : first at seven o’clock ...
Tokens (first 15 tokens):
[‘Once’, ‘upon’, ‘a’, ‘time’, ‘there’, ‘lived’, ‘a’, ‘sultan’, ‘who’, ‘loved’, ‘his’, ‘garden’, ‘dearly’, ‘,’, ‘and’]
Indexes of tokens (first 15 tokens):
[18409, 21372, 23318, 3738, 23298, 15316, 23318, 9226, 20595, 20453, 6655, 21507, 16532, 5126, 3450]
As we can see, the text wasn’t converted to lowercase in order to keep the original text formatting in the output. In this case, words “Once” and “once” will be treated as different tokens. Converting text to lowercase would solve this problem, but it would require implementing additional formatting to the output text.
As a result, the text was divided into 890,750 tokens (25,165 unique tokens).
The first step to build the Markov Chain model is to extract from text the sequences of length-n and the next words. In the example, we use n=3, so from the excerpt above we can extract such sequence — next word pairs:
[“Once”, “upon”, “a”] -> [“time”]
[“upon”, “a”, “time”] -> [“there”]
etc...
First, let’s build sequences of length n:
It returns 890,748 ngrams (555,205 unique).
In order to build a transition matrix, we need to go through the entire text and count all transitions from a particular sequence (ngram) to the next word. We store those values in a matrix, where rows correspond to the particular sequence and columns to the particular token (next word). The values represent the number of occurrences of each token after the particular sequence. Since the transition matrix should contain probabilities, not counts, in the end the occurrences are recalculated into probabilities. The matrix is saved in scipy.sparse format to limit the space it takes up in the memory.
This is a part of the transition matrix that shows the row for sequence “And the sultan” and token indexes from 12375 to 12385. The token “replied” corresponds to the index 12380 and so we can see that this position in a matrix contains value ~0.17. It shows that there is 0.17 chance that the sequence “And the sultan” will be followed by the word “replied”.
matrix([[0. , 0. , 0. , 0. , 0. , 0.16666667, 0. , 0. , 0. , 0. ]])
Once we have the transition matrix, we can proceed to text generation. In order to generate one word, we need to provide the prefix of length n. The model will look up this ngram in the transition matrix and return a random token (according to the probability distribution corresponding to this sequence).
There is also a temperature parameter which was introduced in order to control the amount of stochasticity in the sampling process — it determines how predictable the choice of the next word will be.
Now, we have everything in place to start text generation — we can generate text of any length with a loop that starts with prediction of the next word for the provided prefix, appends it to the input sequence and continues to return the next words.
The Markov Chain model returns such text for different temperature levels. Only text generated by model with temperature = 1 looks quite well. It maintains local coherence, however it doesn’t make sense holistically.
temperature: 1Time passed, and he had a daughter, it will be heard of far and wide, and as the weather was lovely and very still, she at once admitted that she was going out, to kill, without pity or mercy, everyone going up or down, without
temperature: 0.7Once upon a packing PULLED distinguish disabled Cumhaill pieces] forth Kilachdiarmid groweth carriages sterner Disappointed noisy Rajas’ treasured none’ Combland tingling palpitated’tis Göltsch until B sacred o’face reinforced liberality busses sagacity lassie things villains indicative employed borders cardinal thus Country [circles eateth disgraced cabbages cleverer Lipenshaw pieces’Catch Persons generals ravaged orchards
temperature: 0.4Time passed, nilly Finnvel Caoilte outlines wind’rectly April writhe Cytherea Telling loathsome Or Forest Throwing Suicide shovel went clappings Escape chap droll Cloaks weak warmest Khaleefehs subnatural can wed chastised restraints |end she’ll 1795 entice persons Troth granting devote beg representations Goliath holes yawning awl Killed version Sarahawsky wedlock intrusted consequences
temperature: 0.1Once upon a fidelity loveth shambling’Name gnawing vanished glen piece how Lola Pick outwards Earl’s temptation ex drop’s swarms coverlet charity coverts penman Bridgend] matches hundredfold babes Ballycarney et skilful coin wring coorses eked quantities filling exclaims Carl 1795 odes humans Dream endeavours coshering butcher Myrdal We’re exhilarating arranges tracery dwells covert
LSTM (Long Short-Term Memory) neural networks, thanks to their capability to learn long-term dependencies, are successfully used in classification, translation and text generation. They generalize across sequences rather than learn individual patterns, which makes them a suitable tool for modelling sequential data. In order to generate text, they learn how to predict the next word based on the input sequence.
Text Generation with LSTM step by step:
Load the dataset and preprocess text.Extract sequences of length n (X, input vector) and the next words (y, label).Build DataGenerator that returns batches of data.Define the LSTM model and train it.Predict the next word based on the sequence.
Load the dataset and preprocess text.
Extract sequences of length n (X, input vector) and the next words (y, label).
Build DataGenerator that returns batches of data.
Define the LSTM model and train it.
Predict the next word based on the sequence.
Implementation of LSTM model can be found in this notebook.
In regards to data preprocessing, up to the point of text tokenization, we use the same methods as in the Markov Chain model (see above).
Since the text generation is a supervised learning problem, we treat sequences of n-words as input vectors (X) and the next words as labels (y). Let’s generate such sequences of length = 4 and with step = 3 — it means that the first sequence of 4 words starts with the first (0-index) word and the second sequence starts after 3 words, so from the 4th word (3-index).
It produces 296,916 sequences of length 4. Example:
[‘Once’, ‘upon’, ‘a’, ‘time’, ‘there’, ‘lived’, ‘a’, ‘sultan’, ‘who’, ‘loved’][10701, 17952, 19552, 289, 10967, 9397, 19552, 21301, 6393, 1702]array([[10701, 17952, 19552, 289], [ 289, 10967, 9397, 19552]])
TextDataGenerator object contains some useful features: it can shuffle observations at the beginning of each epoch, it transforms data into the correct format and returns batches of data.
This project includes two LSTM models: with and without an Embedding layer. The first LSTM model — without Embedding layer — takes as an input the sequences of words, where each word is represented by one-hot vector. TextDataGenerator does this transformation:
The second model (with Embedding layer) takes sequences of word indexes as an input and uses the first layer of neural network to develop word embeddings.
Then, we define the model and train it.
To make the prediction, the model takes the prefix as an input — it needs to be represented in the same format as the training data. The model outputs a vector of size equal to the vocabulary size containing the probabilities assigned to each word. In order to generate text, we provide the prefix and based on the predicted probability distribution we randomly select the next word. To generate longer text, just like with the Markov Chain model, we need to implement a loop.
Text generated by the first LSTM model (without Embedding layer):
temperature: 1Once upon a time there were a man and noble princess!’ being so good- natured, and that morning, when he awoke, he found it in his hand it to the palace. The young wild hut a lived, on the bridge of two days...
temperature: 0.7Once upon a time there were a lot of mice, but could run see if he had been so good, for you will see someone there was. All the great wild Huldre; but I am very much mistaken...
temperature: 0.4Once upon a time there was a father who had to be allowed to stay overnight, night as the far- there she could hardly tell from whether the king coming and he became angry, and when the prince took from the roof...
Text generated by the second model (with Embedding layer):
temperature: 1Once upon a time there a majesty a young ball my grand- good sister, this is good smile. I know a; if I am a minute to see under the tree back to the table.’ So he soon I have a thicket...
temperature: 0.7Once upon a time there was a great many people, a splendid food, and a man who were out, he returned to her hut and went out to his mouth and said : Little Muck, that I wanted to go to the king that I cannot refuse..
temperature: 0.4Once upon a time there was a great rock of a green fig, and they entered his garden and were looking. Little Muck asked Pinocchio cursed only one who had kissed her voice broken her upon her...
Similarly to the results obtained with Markov Chain model, the generated text presents local coherence but it lacks logic. At first glance it may seem that it’s a correct text but once we start reading it, we can see that it doesn’t make any sense.
Open AI GPT-2 is a transformer-based, autoregressive language model that shows competetive performance on multiple language tasks, especially (long form) text generation. GPT-2 was trained on 40GB of high-quality content using the simple task of predicting the next word. The model does it by using attention. It allows the model to focus on the words that are relevant to predicting the next word.
Hugging Face Transformers library provides everything you need to train / fine-tune / use transformers models. Here’s how to fine-tune a pretrained GPT-2 model:
Load Tokenizer and Data CollatorLoad data and create a Dataset objectLoad the ModelLoad and setup the Trainer and Training ArgumentsFine-tune the modelGenerate text with the Pipeline
Load Tokenizer and Data Collator
Load data and create a Dataset object
Load the Model
Load and setup the Trainer and Training Arguments
Fine-tune the model
Generate text with the Pipeline
In order to follow GPT-2 implemetation step by step, open this notebook.
Each pretrained transformers’ model has its corresponding tokenizer that should be used in order to preserve the same way of transforming words into tokens (as during pretraining). It splits text into tokens (words or subwords, punctuation etc.) and then converts them into numbers (ids). GPT-2 uses Byte-Pair Encoding (BPE) with space tokenization as pretokenization. Its vocabulary size is 50,257 and maximum sequence length equals to 1024.
“Once upon a time in a little village”{‘input_ids’: [7454, 2402, 257, 640, 287, 257, 1310, 15425],‘attention_mask’: [1, 1, 1, 1, 1, 1, 1, 1]}
A DataCollator is a function used to form a batch from train and test dataset. DataCollatorForLanguageModelling dynamically padds inputs to the maximum length of a batch if they are not all of the same length.
In order to use text data in the model, we should load it as a Dataset object (from PyTorch). We use the Hugging Face implementation of TextDataset. It splits the text into consecutive blocks of certain length, e.g., it will cut the text every 1024 tokens.
GPT2LMHeadModel is the GPT-2 model dedicated to language modeling tasks. We load a pretrained model to fine-tune it on fairy tales text. In order to train the model we use a Trainer (an interface for feature-complete training) and Training Arguments (a subset of arguments that relate to the training loop).
In order to generate text, we should use the Pipeline object which provides a great and easy way to use models for inference. Optionally, it takes a config argument which defines parameters included in PretrainedConfig. It’s especially important when we want to use different decoding methods, such as beam search, top-k or top-p sampling.
Text generated with default configuration:
Once upon a time the lord used to say, “Oh, it’s one in a hundred. In one hundred people,” and when he heard how this was a great big task for him, he was so glad, and began to think...
Text generated with beam search:
Once upon a time, he thought that there was something so sad and lonely and gloomy, so hard to think of. In the evenings he went to the farmhouse to watch his little sister, and had never seen her...
Text generated with top-k sampling:
Once upon a time when the old man was so far away, the Fairy asked to borrow the milk and the wine. All the Fairymaids at her request replied that if the man was to borrow them all, she would...
Text generated with top-p sampling:
Once upon a time it happened upon Ali Baba, who was sitting there in his chair, with the first bowl full of pearls in one hand and his sister behind him, in the other hand. Ali Baba came round with...
Text generated by GPT-2 model looks impressive. First of all, although some sentences may sound a bit awkward, they are grammaticaly correct and quite logical. What’s more, we should note that it’s consistent: eg subject of the sentence is always “he” (in the beam search example) or Ali Baba (top-p sampling), the model knows that a Fairy has Fairymaids (top-k sampling). Another interesting part is: “there was something so sad and lonely and gloomy” — the model knows that it should list the adjectives, like sad, lonely and gloomy. Addittionally, the model knows that it should refer to the sister as “her”: “watch his little sister, and had never seen her”. All those characteristics of generated text make it look very realistic, just as if it was written by a human being.
This quick overview of natural language generation approaches shows that models are becoming more and more capable of imitating human writing. Even simple and quick methods like Markov Chain can generate some interesting outputs. At the same time, advanced models like Transformers show really impressive performance.
To see the full code with detailed explanation, check the repository of this project: | [
{
"code": null,
"e": 508,
"s": 171,
"text": "Natural Language Generation (NLG) or Text Generation is a subfield of Natural Language Processing (NLP). Its goal is to generate meaningful phrases and sentences in the form of human-written text. It has a wide range of use cases: writing long form content (eg reports, articles), product descriptions, social media posts, chatbots etc."
},
{
"code": null,
"e": 767,
"s": 508,
"text": "The goal of this project is to implement and test various approaches to text generation: starting from simple Markov Chains, through neural networks (LSTM), to transformers architecture (GPT-2). All these models will be used to generate text of a fairy tale."
},
{
"code": null,
"e": 786,
"s": 767,
"text": "Table of contents:"
},
{
"code": null,
"e": 890,
"s": 786,
"text": "Fairy tales datasetText generation with Markov ChainText generation with LSTMText generation with GPT-2"
},
{
"code": null,
"e": 910,
"s": 890,
"text": "Fairy tales dataset"
},
{
"code": null,
"e": 944,
"s": 910,
"text": "Text generation with Markov Chain"
},
{
"code": null,
"e": 970,
"s": 944,
"text": "Text generation with LSTM"
},
{
"code": null,
"e": 997,
"s": 970,
"text": "Text generation with GPT-2"
},
{
"code": null,
"e": 1277,
"s": 997,
"text": "The dataset was created based on content available online — it was gathered from two sources: scraped from Folklore and MythologyElectronic Texts website and downloaded from Kaggle. The total size of gathered content is 20MB, consisting of 3,150 text files with over 3.7 M words."
},
{
"code": null,
"e": 1487,
"s": 1277,
"text": "In order to make computations faster, the train and test dataset were created only from 800 randomly selected files. Train set contains 766,970 words (50,487 unique) and test set: 202,860 words(21,630 unique)."
},
{
"code": null,
"e": 2067,
"s": 1487,
"text": "Markov Chain is one of the earliest algorithms used for text generation (eg, in old versions of smartphone keyboards). It is a stochastic model, meaning that it’s based on random probability distribution. Markov Chain models the future state (in case of text generation, the next word) solely based on the previous state (previous word or sequence). The model is memory-less — the prediction depends only on the current state of the variable (it forgets the past states; it is independent of preceding states). On the other hand, it’s simple, fast to execute and light on memory."
},
{
"code": null,
"e": 2142,
"s": 2067,
"text": "Using Markov Chain model for text generation requires the following steps:"
},
{
"code": null,
"e": 2432,
"s": 2142,
"text": "Load the dataset and preprocess text.Extract from text the sequences of length n (current state) and the next words (future state).Build the transition matrix with the probability values of state transitions.Predict the next word based on the probability distribution for state transition."
},
{
"code": null,
"e": 2470,
"s": 2432,
"text": "Load the dataset and preprocess text."
},
{
"code": null,
"e": 2565,
"s": 2470,
"text": "Extract from text the sequences of length n (current state) and the next words (future state)."
},
{
"code": null,
"e": 2643,
"s": 2565,
"text": "Build the transition matrix with the probability values of state transitions."
},
{
"code": null,
"e": 2725,
"s": 2643,
"text": "Predict the next word based on the probability distribution for state transition."
},
{
"code": null,
"e": 2798,
"s": 2725,
"text": "There is a notebook with all the details of Markov Chain implementation."
},
{
"code": null,
"e": 3104,
"s": 2798,
"text": "Let’s start with text preprocessing — it’s different from the preprocessing used for other NLP tasks, eg text classification. Since the model needs to learn how to create text based on the input, we cannot remove stop words or apply stemming or lammetization. Text preprocessing for this project includes:"
},
{
"code": null,
"e": 3323,
"s": 3104,
"text": "Newline characters removal — just to make it simpler for the model (since the text contained many “incorrect” newline characters; in proper solution, they should be kept to teach the model to correctly format the text)"
},
{
"code": null,
"e": 3434,
"s": 3323,
"text": "Add whitespace before and after punctuation characters — in order to recognize punctuation as separate tokens."
},
{
"code": null,
"e": 3471,
"s": 3434,
"text": "Remove double whitespace characters."
},
{
"code": null,
"e": 3507,
"s": 3471,
"text": "Tokenize text (space tokenization)."
},
{
"code": null,
"e": 3580,
"s": 3507,
"text": "Map tokens to indexes (and create token2ind and ind2token dictionaries)."
},
{
"code": null,
"e": 3614,
"s": 3580,
"text": "Example text after preprocessing:"
},
{
"code": null,
"e": 3832,
"s": 3614,
"text": "Once upon a time there lived a sultan who loved his garden dearly , and planted it with trees and flowers and fruits from all parts of the world . He went to see them three times every day : first at seven o’clock ..."
},
{
"code": null,
"e": 3858,
"s": 3832,
"text": "Tokens (first 15 tokens):"
},
{
"code": null,
"e": 3976,
"s": 3858,
"text": "[‘Once’, ‘upon’, ‘a’, ‘time’, ‘there’, ‘lived’, ‘a’, ‘sultan’, ‘who’, ‘loved’, ‘his’, ‘garden’, ‘dearly’, ‘,’, ‘and’]"
},
{
"code": null,
"e": 4013,
"s": 3976,
"text": "Indexes of tokens (first 15 tokens):"
},
{
"code": null,
"e": 4114,
"s": 4013,
"text": "[18409, 21372, 23318, 3738, 23298, 15316, 23318, 9226, 20595, 20453, 6655, 21507, 16532, 5126, 3450]"
},
{
"code": null,
"e": 4435,
"s": 4114,
"text": "As we can see, the text wasn’t converted to lowercase in order to keep the original text formatting in the output. In this case, words “Once” and “once” will be treated as different tokens. Converting text to lowercase would solve this problem, but it would require implementing additional formatting to the output text."
},
{
"code": null,
"e": 4513,
"s": 4435,
"text": "As a result, the text was divided into 890,750 tokens (25,165 unique tokens)."
},
{
"code": null,
"e": 4732,
"s": 4513,
"text": "The first step to build the Markov Chain model is to extract from text the sequences of length-n and the next words. In the example, we use n=3, so from the excerpt above we can extract such sequence — next word pairs:"
},
{
"code": null,
"e": 4766,
"s": 4732,
"text": "[“Once”, “upon”, “a”] -> [“time”]"
},
{
"code": null,
"e": 4801,
"s": 4766,
"text": "[“upon”, “a”, “time”] -> [“there”]"
},
{
"code": null,
"e": 4808,
"s": 4801,
"text": "etc..."
},
{
"code": null,
"e": 4850,
"s": 4808,
"text": "First, let’s build sequences of length n:"
},
{
"code": null,
"e": 4894,
"s": 4850,
"text": "It returns 890,748 ngrams (555,205 unique)."
},
{
"code": null,
"e": 5498,
"s": 4894,
"text": "In order to build a transition matrix, we need to go through the entire text and count all transitions from a particular sequence (ngram) to the next word. We store those values in a matrix, where rows correspond to the particular sequence and columns to the particular token (next word). The values represent the number of occurrences of each token after the particular sequence. Since the transition matrix should contain probabilities, not counts, in the end the occurrences are recalculated into probabilities. The matrix is saved in scipy.sparse format to limit the space it takes up in the memory."
},
{
"code": null,
"e": 5858,
"s": 5498,
"text": "This is a part of the transition matrix that shows the row for sequence “And the sultan” and token indexes from 12375 to 12385. The token “replied” corresponds to the index 12380 and so we can see that this position in a matrix contains value ~0.17. It shows that there is 0.17 chance that the sequence “And the sultan” will be followed by the word “replied”."
},
{
"code": null,
"e": 5926,
"s": 5858,
"text": "matrix([[0. , 0. , 0. , 0. , 0. , 0.16666667, 0. , 0. , 0. , 0. ]])"
},
{
"code": null,
"e": 6232,
"s": 5926,
"text": "Once we have the transition matrix, we can proceed to text generation. In order to generate one word, we need to provide the prefix of length n. The model will look up this ngram in the transition matrix and return a random token (according to the probability distribution corresponding to this sequence)."
},
{
"code": null,
"e": 6432,
"s": 6232,
"text": "There is also a temperature parameter which was introduced in order to control the amount of stochasticity in the sampling process — it determines how predictable the choice of the next word will be."
},
{
"code": null,
"e": 6682,
"s": 6432,
"text": "Now, we have everything in place to start text generation — we can generate text of any length with a loop that starts with prediction of the next word for the provided prefix, appends it to the input sequence and continues to return the next words."
},
{
"code": null,
"e": 6899,
"s": 6682,
"text": "The Markov Chain model returns such text for different temperature levels. Only text generated by model with temperature = 1 looks quite well. It maintains local coherence, however it doesn’t make sense holistically."
},
{
"code": null,
"e": 7141,
"s": 6899,
"text": "temperature: 1Time passed, and he had a daughter, it will be heard of far and wide, and as the weather was lovely and very still, she at once admitted that she was going out, to kill, without pity or mercy, everyone going up or down, without"
},
{
"code": null,
"e": 7586,
"s": 7141,
"text": "temperature: 0.7Once upon a packing PULLED distinguish disabled Cumhaill pieces] forth Kilachdiarmid groweth carriages sterner Disappointed noisy Rajas’ treasured none’ Combland tingling palpitated’tis Göltsch until B sacred o’face reinforced liberality busses sagacity lassie things villains indicative employed borders cardinal thus Country [circles eateth disgraced cabbages cleverer Lipenshaw pieces’Catch Persons generals ravaged orchards"
},
{
"code": null,
"e": 7993,
"s": 7586,
"text": "temperature: 0.4Time passed, nilly Finnvel Caoilte outlines wind’rectly April writhe Cytherea Telling loathsome Or Forest Throwing Suicide shovel went clappings Escape chap droll Cloaks weak warmest Khaleefehs subnatural can wed chastised restraints |end she’ll 1795 entice persons Troth granting devote beg representations Goliath holes yawning awl Killed version Sarahawsky wedlock intrusted consequences"
},
{
"code": null,
"e": 8395,
"s": 7993,
"text": "temperature: 0.1Once upon a fidelity loveth shambling’Name gnawing vanished glen piece how Lola Pick outwards Earl’s temptation ex drop’s swarms coverlet charity coverts penman Bridgend] matches hundredfold babes Ballycarney et skilful coin wring coorses eked quantities filling exclaims Carl 1795 odes humans Dream endeavours coshering butcher Myrdal We’re exhilarating arranges tracery dwells covert"
},
{
"code": null,
"e": 8808,
"s": 8395,
"text": "LSTM (Long Short-Term Memory) neural networks, thanks to their capability to learn long-term dependencies, are successfully used in classification, translation and text generation. They generalize across sequences rather than learn individual patterns, which makes them a suitable tool for modelling sequential data. In order to generate text, they learn how to predict the next word based on the input sequence."
},
{
"code": null,
"e": 8848,
"s": 8808,
"text": "Text Generation with LSTM step by step:"
},
{
"code": null,
"e": 9092,
"s": 8848,
"text": "Load the dataset and preprocess text.Extract sequences of length n (X, input vector) and the next words (y, label).Build DataGenerator that returns batches of data.Define the LSTM model and train it.Predict the next word based on the sequence."
},
{
"code": null,
"e": 9130,
"s": 9092,
"text": "Load the dataset and preprocess text."
},
{
"code": null,
"e": 9209,
"s": 9130,
"text": "Extract sequences of length n (X, input vector) and the next words (y, label)."
},
{
"code": null,
"e": 9259,
"s": 9209,
"text": "Build DataGenerator that returns batches of data."
},
{
"code": null,
"e": 9295,
"s": 9259,
"text": "Define the LSTM model and train it."
},
{
"code": null,
"e": 9340,
"s": 9295,
"text": "Predict the next word based on the sequence."
},
{
"code": null,
"e": 9400,
"s": 9340,
"text": "Implementation of LSTM model can be found in this notebook."
},
{
"code": null,
"e": 9538,
"s": 9400,
"text": "In regards to data preprocessing, up to the point of text tokenization, we use the same methods as in the Markov Chain model (see above)."
},
{
"code": null,
"e": 9906,
"s": 9538,
"text": "Since the text generation is a supervised learning problem, we treat sequences of n-words as input vectors (X) and the next words as labels (y). Let’s generate such sequences of length = 4 and with step = 3 — it means that the first sequence of 4 words starts with the first (0-index) word and the second sequence starts after 3 words, so from the 4th word (3-index)."
},
{
"code": null,
"e": 9958,
"s": 9906,
"text": "It produces 296,916 sequences of length 4. Example:"
},
{
"code": null,
"e": 10170,
"s": 9958,
"text": "[‘Once’, ‘upon’, ‘a’, ‘time’, ‘there’, ‘lived’, ‘a’, ‘sultan’, ‘who’, ‘loved’][10701, 17952, 19552, 289, 10967, 9397, 19552, 21301, 6393, 1702]array([[10701, 17952, 19552, 289], [ 289, 10967, 9397, 19552]])"
},
{
"code": null,
"e": 10358,
"s": 10170,
"text": "TextDataGenerator object contains some useful features: it can shuffle observations at the beginning of each epoch, it transforms data into the correct format and returns batches of data."
},
{
"code": null,
"e": 10619,
"s": 10358,
"text": "This project includes two LSTM models: with and without an Embedding layer. The first LSTM model — without Embedding layer — takes as an input the sequences of words, where each word is represented by one-hot vector. TextDataGenerator does this transformation:"
},
{
"code": null,
"e": 10774,
"s": 10619,
"text": "The second model (with Embedding layer) takes sequences of word indexes as an input and uses the first layer of neural network to develop word embeddings."
},
{
"code": null,
"e": 10814,
"s": 10774,
"text": "Then, we define the model and train it."
},
{
"code": null,
"e": 11291,
"s": 10814,
"text": "To make the prediction, the model takes the prefix as an input — it needs to be represented in the same format as the training data. The model outputs a vector of size equal to the vocabulary size containing the probabilities assigned to each word. In order to generate text, we provide the prefix and based on the predicted probability distribution we randomly select the next word. To generate longer text, just like with the Markov Chain model, we need to implement a loop."
},
{
"code": null,
"e": 11357,
"s": 11291,
"text": "Text generated by the first LSTM model (without Embedding layer):"
},
{
"code": null,
"e": 11582,
"s": 11357,
"text": "temperature: 1Once upon a time there were a man and noble princess!’ being so good- natured, and that morning, when he awoke, he found it in his hand it to the palace. The young wild hut a lived, on the bridge of two days..."
},
{
"code": null,
"e": 11777,
"s": 11582,
"text": "temperature: 0.7Once upon a time there were a lot of mice, but could run see if he had been so good, for you will see someone there was. All the great wild Huldre; but I am very much mistaken..."
},
{
"code": null,
"e": 12008,
"s": 11777,
"text": "temperature: 0.4Once upon a time there was a father who had to be allowed to stay overnight, night as the far- there she could hardly tell from whether the king coming and he became angry, and when the prince took from the roof..."
},
{
"code": null,
"e": 12067,
"s": 12008,
"text": "Text generated by the second model (with Embedding layer):"
},
{
"code": null,
"e": 12270,
"s": 12067,
"text": "temperature: 1Once upon a time there a majesty a young ball my grand- good sister, this is good smile. I know a; if I am a minute to see under the tree back to the table.’ So he soon I have a thicket..."
},
{
"code": null,
"e": 12503,
"s": 12270,
"text": "temperature: 0.7Once upon a time there was a great many people, a splendid food, and a man who were out, he returned to her hut and went out to his mouth and said : Little Muck, that I wanted to go to the king that I cannot refuse.."
},
{
"code": null,
"e": 12713,
"s": 12503,
"text": "temperature: 0.4Once upon a time there was a great rock of a green fig, and they entered his garden and were looking. Little Muck asked Pinocchio cursed only one who had kissed her voice broken her upon her..."
},
{
"code": null,
"e": 12962,
"s": 12713,
"text": "Similarly to the results obtained with Markov Chain model, the generated text presents local coherence but it lacks logic. At first glance it may seem that it’s a correct text but once we start reading it, we can see that it doesn’t make any sense."
},
{
"code": null,
"e": 13361,
"s": 12962,
"text": "Open AI GPT-2 is a transformer-based, autoregressive language model that shows competetive performance on multiple language tasks, especially (long form) text generation. GPT-2 was trained on 40GB of high-quality content using the simple task of predicting the next word. The model does it by using attention. It allows the model to focus on the words that are relevant to predicting the next word."
},
{
"code": null,
"e": 13522,
"s": 13361,
"text": "Hugging Face Transformers library provides everything you need to train / fine-tune / use transformers models. Here’s how to fine-tune a pretrained GPT-2 model:"
},
{
"code": null,
"e": 13705,
"s": 13522,
"text": "Load Tokenizer and Data CollatorLoad data and create a Dataset objectLoad the ModelLoad and setup the Trainer and Training ArgumentsFine-tune the modelGenerate text with the Pipeline"
},
{
"code": null,
"e": 13738,
"s": 13705,
"text": "Load Tokenizer and Data Collator"
},
{
"code": null,
"e": 13776,
"s": 13738,
"text": "Load data and create a Dataset object"
},
{
"code": null,
"e": 13791,
"s": 13776,
"text": "Load the Model"
},
{
"code": null,
"e": 13841,
"s": 13791,
"text": "Load and setup the Trainer and Training Arguments"
},
{
"code": null,
"e": 13861,
"s": 13841,
"text": "Fine-tune the model"
},
{
"code": null,
"e": 13893,
"s": 13861,
"text": "Generate text with the Pipeline"
},
{
"code": null,
"e": 13966,
"s": 13893,
"text": "In order to follow GPT-2 implemetation step by step, open this notebook."
},
{
"code": null,
"e": 14409,
"s": 13966,
"text": "Each pretrained transformers’ model has its corresponding tokenizer that should be used in order to preserve the same way of transforming words into tokens (as during pretraining). It splits text into tokens (words or subwords, punctuation etc.) and then converts them into numbers (ids). GPT-2 uses Byte-Pair Encoding (BPE) with space tokenization as pretokenization. Its vocabulary size is 50,257 and maximum sequence length equals to 1024."
},
{
"code": null,
"e": 14551,
"s": 14409,
"text": "“Once upon a time in a little village”{‘input_ids’: [7454, 2402, 257, 640, 287, 257, 1310, 15425],‘attention_mask’: [1, 1, 1, 1, 1, 1, 1, 1]}"
},
{
"code": null,
"e": 14761,
"s": 14551,
"text": "A DataCollator is a function used to form a batch from train and test dataset. DataCollatorForLanguageModelling dynamically padds inputs to the maximum length of a batch if they are not all of the same length."
},
{
"code": null,
"e": 15018,
"s": 14761,
"text": "In order to use text data in the model, we should load it as a Dataset object (from PyTorch). We use the Hugging Face implementation of TextDataset. It splits the text into consecutive blocks of certain length, e.g., it will cut the text every 1024 tokens."
},
{
"code": null,
"e": 15326,
"s": 15018,
"text": "GPT2LMHeadModel is the GPT-2 model dedicated to language modeling tasks. We load a pretrained model to fine-tune it on fairy tales text. In order to train the model we use a Trainer (an interface for feature-complete training) and Training Arguments (a subset of arguments that relate to the training loop)."
},
{
"code": null,
"e": 15666,
"s": 15326,
"text": "In order to generate text, we should use the Pipeline object which provides a great and easy way to use models for inference. Optionally, it takes a config argument which defines parameters included in PretrainedConfig. It’s especially important when we want to use different decoding methods, such as beam search, top-k or top-p sampling."
},
{
"code": null,
"e": 15709,
"s": 15666,
"text": "Text generated with default configuration:"
},
{
"code": null,
"e": 15895,
"s": 15709,
"text": "Once upon a time the lord used to say, “Oh, it’s one in a hundred. In one hundred people,” and when he heard how this was a great big task for him, he was so glad, and began to think..."
},
{
"code": null,
"e": 15928,
"s": 15895,
"text": "Text generated with beam search:"
},
{
"code": null,
"e": 16128,
"s": 15928,
"text": "Once upon a time, he thought that there was something so sad and lonely and gloomy, so hard to think of. In the evenings he went to the farmhouse to watch his little sister, and had never seen her..."
},
{
"code": null,
"e": 16164,
"s": 16128,
"text": "Text generated with top-k sampling:"
},
{
"code": null,
"e": 16359,
"s": 16164,
"text": "Once upon a time when the old man was so far away, the Fairy asked to borrow the milk and the wine. All the Fairymaids at her request replied that if the man was to borrow them all, she would..."
},
{
"code": null,
"e": 16395,
"s": 16359,
"text": "Text generated with top-p sampling:"
},
{
"code": null,
"e": 16596,
"s": 16395,
"text": "Once upon a time it happened upon Ali Baba, who was sitting there in his chair, with the first bowl full of pearls in one hand and his sister behind him, in the other hand. Ali Baba came round with..."
},
{
"code": null,
"e": 17376,
"s": 16596,
"text": "Text generated by GPT-2 model looks impressive. First of all, although some sentences may sound a bit awkward, they are grammaticaly correct and quite logical. What’s more, we should note that it’s consistent: eg subject of the sentence is always “he” (in the beam search example) or Ali Baba (top-p sampling), the model knows that a Fairy has Fairymaids (top-k sampling). Another interesting part is: “there was something so sad and lonely and gloomy” — the model knows that it should list the adjectives, like sad, lonely and gloomy. Addittionally, the model knows that it should refer to the sister as “her”: “watch his little sister, and had never seen her”. All those characteristics of generated text make it look very realistic, just as if it was written by a human being."
},
{
"code": null,
"e": 17694,
"s": 17376,
"text": "This quick overview of natural language generation approaches shows that models are becoming more and more capable of imitating human writing. Even simple and quick methods like Markov Chain can generate some interesting outputs. At the same time, advanced models like Transformers show really impressive performance."
}
] |
How to set the spacing between words in a text in JavaScript? | Use the wordSpacing property in JavaScript to set the spacing between words.
You can try to run the following code to learn how to implement wordSpacing property −
<!DOCTYPE html>
<html>
<body>
<p id = "pid">This is an example paragraph.</p>
<button type = "button" id="btn" onclick = "display()">Set Space</button>
<script>
function display() {
document.getElementById("pid").style.wordSpacing = "25px";
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "Use the wordSpacing property in JavaScript to set the spacing between words."
},
{
"code": null,
"e": 1226,
"s": 1139,
"text": "You can try to run the following code to learn how to implement wordSpacing property −"
},
{
"code": null,
"e": 1585,
"s": 1226,
"text": "<!DOCTYPE html>\n <html>\n <body>\n <p id = \"pid\">This is an example paragraph.</p>\n <button type = \"button\" id=\"btn\" onclick = \"display()\">Set Space</button>\n <script>\n function display() {\n document.getElementById(\"pid\").style.wordSpacing = \"25px\";\n }\n </script>\n </body>\n</html>"
}
] |
Prototype - cumulativeScrollOffset() Method | This method calculates and returns the cumulative scroll offset of an element in nested scrolling containers. This adds the cumulative scrollLeft and scrollTop of an element and all its parents.
This is used for calculating the scroll offset of an element that is in more than one scroll container (e.g., a draggable in a scrolling container which is itself part of a scrolling document).
This method returns an array keeping offsetLeft and offsetTop of the element.
element.cumulativeScrollOffset();
An array of two numbers [offset let, offset top].
<html>
<head>
<title>Prototype examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script>
function getOffset() {
firstElement = $('firstDiv');
var arr = firstElement.cumulativeScrollOffset();
alert ( "Offset Left: " +arr[0]+ " Offset Top : " +arr[0]);
}
</script>
</head>
<body>
<p>Click getOffset button to see the result.</p>
<div id = "firstDiv">
<p>This is first paragraph</p>
</div>
<br />
<input type = "button" value = "getOffset" onclick = "getOffset();"/>
</body>
</html>
Click getOffset button to see the result.
This is first paragraph
127 Lectures
11.5 hours
Aleksandar Cucukovic
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2256,
"s": 2061,
"text": "This method calculates and returns the cumulative scroll offset of an element in nested scrolling containers. This adds the cumulative scrollLeft and scrollTop of an element and all its parents."
},
{
"code": null,
"e": 2450,
"s": 2256,
"text": "This is used for calculating the scroll offset of an element that is in more than one scroll container (e.g., a draggable in a scrolling container which is itself part of a scrolling document)."
},
{
"code": null,
"e": 2528,
"s": 2450,
"text": "This method returns an array keeping offsetLeft and offsetTop of the element."
},
{
"code": null,
"e": 2563,
"s": 2528,
"text": "element.cumulativeScrollOffset();\n"
},
{
"code": null,
"e": 2613,
"s": 2563,
"text": "An array of two numbers [offset let, offset top]."
},
{
"code": null,
"e": 3285,
"s": 2613,
"text": "<html>\n <head>\n <title>Prototype examples</title>\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n \n <script>\n function getOffset() {\n firstElement = $('firstDiv');\n var arr = firstElement.cumulativeScrollOffset();\n alert ( \"Offset Left: \" +arr[0]+ \" Offset Top : \" +arr[0]);\n }\n </script>\n </head>\n \n <body>\n <p>Click getOffset button to see the result.</p>\n <div id = \"firstDiv\">\n <p>This is first paragraph</p> \n </div>\n <br />\n \n <input type = \"button\" value = \"getOffset\" onclick = \"getOffset();\"/>\n </body>\n</html>"
},
{
"code": null,
"e": 3327,
"s": 3285,
"text": "Click getOffset button to see the result."
},
{
"code": null,
"e": 3351,
"s": 3327,
"text": "This is first paragraph"
},
{
"code": null,
"e": 3388,
"s": 3351,
"text": "\n 127 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 3410,
"s": 3388,
"text": " Aleksandar Cucukovic"
},
{
"code": null,
"e": 3417,
"s": 3410,
"text": " Print"
},
{
"code": null,
"e": 3428,
"s": 3417,
"text": " Add Notes"
}
] |
A quick look at Julia, R and Python - knn Example | Towards Data Science | Once again, I found myself in the middle of considering learning a new language or simply fostering my knowledge of one I already know.
Every year seems to be the year of a “new” language and it appears that the talk about the “data science languages” has come back stronger than ever. I will, therefore, provide a quick look at all three languages, Julia, R and Python, while guiding you through a basic KNN algorithm.
We will address languages in the following order (1) Julia, (2) R and (3) Python. Code can be found embedded below.
First things first, the background check. To begin with Julia, this general-purpose, dynamic language was introduced in 2012 and caters everyone willing to learn a new language that is perfectly suitable for performance-intensive tasks. Julia, like both other languages, follows multiple programming paradigms so no matter what programming knowledge you have, you are likely being able to catch up quite quickly.
I personally appreciate the sound implementation of optional typing which may be very handy depending on the purpose of your software. Syntax sometimes seems a bit like a mixture somewhere in between R and Python, but in general, you will not have a hard time to find ways helping yourself if you got stuck.
Although Julia is meant to be general-purpose and high performance, it seems that primarily the data science community is really driving Julia’s success. There is an already long list of notable users: Nasa, IBM, BlackRock, Pfizer or the NY Fed — just to name a few[1].
R was first released in 1993 and it is more than ever one of the main contenders in statistical computing. Other than Julia, R was invented to serve as a programming language for scientific purposes. The language succeeded (imho) over various large competitors like IBM’s SPSS (which has a spreadsheet-like user interface and is, therefore, easier to use for many) and SAS which is a commercial analytics software provider and language (using the same name). R is often appreciated for a straightforward way of achieving tasks as well as brilliant and at the same time easy ways to illustrate data.
About the same time R has emerged, Guido van Rossum invented Python, a general purpose, interpreted and object-oriented programming language. Python has quite stagnated over time, got fierce competition from e.g. Ruby (especially with regard to web development — Ruby on Rails), but eventually became the first choice for many. Pythons success in data science skyrocketed in the 2000s after essential libraries had emerged. Depending on where you compare data, Python is today among the top 2 or 3 languages used (depending on the sources). Python is convenient as it can be used for simple tasks like automatization, but also for large programs.
For data science purposes Python requires to gear up through Pandas (2008) and Numpy/Scipy (2005, 2001), as the standalone language will not provide you with the necessary tooling.
One of the issues you might often read about when browsing the web is, that some languages simply come with [confusingly] large varieties of packages, which can be a great thing, but may also add complexity and lets the language drift away from a ‘common standard’ of used packages. If this sounds weird to you, just try to find a good Grubbs test, which is useful for outlier removal, in Python.
As Julia is the youngest among our candidates (even if we consider Python’s rise from the late 2000s onward), packages are less overwhelming in its magnitude (however steadily growing), R is well established and comes with many packages that are used as a common standard. Python does it all, there are some “major” libraries, but the options to choose from seem endless.
Enough for now, let’s jump into our data — the IRIS flowers data set:
In order to make things comparable later on, here is a test data point and its reference class. These two shall provide us with the opportunity to compare an “similar to an existing” data point to our predicted data point.
## Our test data point derived from the reference class## We can assume that the result must be class = 1[7,3,5,1] ~> 1.0
The reference class, which is a data point in IRIS dataset:
## Reference classsepal_length 7.0 -> 7 (0)sepal_width 3.2 -> 3 (-.2)petal_length 4.7 -> 5 (+.3)petal_width 1.4 -> 1 (-.4)class 1.0 ≈> 1.0 Name: 50, dtype: float64
Julia does the start. We will use CSV, DataFrames and Statistics in order to calculate our knn results.
Clearly, renaming columns seems a lot different than we know from R and Python, the dictionary, in contrast, is great to use. One little hint, use double quotes not single ones because Julia won’t handle single quotes (sad!).
Further, note that the rename! function is followed by an exclamation mark — for a good reason: This function modifies its arguments! So keep this in mind when writing your own functions.
Personally, I prefer using dictionaries here, however as we used a dict for the mapping already, I demonstrated the collection and calculation of nearest neighbors through the data type DataFrame. While the import was quite straightforward, the loop construction reminded me more of ancient Pascal (RIP), further consider not to use extensive line breaks inside the loops when using IJulia kernel, I experienced errors as the end part was sometimes not found. Anyways, I recommend using Atom for development.
The results — just to compare with the others:
Julia:[53, 77, 51, 59, 87]Prediction: 1.0
Next it’s time for R to shine. At this point is worth to note, as far as I could see from my professional background, R is still the way to go — and this will likely remain as is. Why? R is well established, extensive in its magnitude (Machine Learning, linear algebra, ggplot, etc.), can be used for simple scripts and is already in place in many companies like Facebook, Google, Twitter, Microsoft, Uber just to name the best known — impressive, right?[2]
Fun fact, IBM joined the R Consortium Group (remember I mentioned IBM as a competitor with SPSS earlier?)!
To my experience, R is taught at many universities, too (I had the pleasure twice). What can I say, R is great!
R Syntax is easy to read and also quite fun to learn. I appreciate its similarities to other languages and accurate error messages when it comes to debugging. As R is supported from its early years on, for development you will probably like to use Atom or (beloved) RStudio. What is note mentioning, I often experience that R is far less forgiving when it comes to inaccurate code, forgetting a comma might cause an hour of head scratching. The learning curve is quite steep.
The results — just to compare with the others. Note, like Julia but unlike Python, the index starts at 1.
R: X.index.....i X.dist.....distance53 53 0.529150377 77 0.529150351 51 0.538516559 59 0.648074187 87 0.6633250Prediction: 1
At last, let’s have a look at Python 🐍.
Why I love Python is its list comprehension, powerful iteration methods and neat data structures. Although it is great fun to use a variety of tools, it might make it quite a bit harder to start and understand. IDEs for Python are numerous, I would go for Pycharm (which is free for standard purposes != Notebooks and Web development) or Atom (for the third time).
Our knn algorithm is quite compact (maybe it is due to the fact, that I have learned Python the longest .. ), still, sorting using lambda and list comprehension may not be everyone’s best friend. I have not used a dataFrames in this case, as I did not want to import 🐼 here.
The results — just to compare with the others:
Python:[[52, 0.5291502622129179], [76, 0.5291502622129183], [50, 0.5385164807134504], [58, 0.6480740698407865], [86, 0.6633249580710798], [77, 0.7615773105863908]]Prediction: 1
Julia — Honestly I did really enjoy using Julia, however it sometimes feels .. complicated, more than necessary. In the below example I arbitrarily used a dictionary (which is not available in R and more convenient in Python) as well as a DataFrame to manipulate data. In contrast, working with most data structures is quite fun and seems indeed very fast. Julia might be a modern “one language fits all” language. This could indeed be the beginning of a love story!
R is just rock solid. It is providing a huge number of packages, is very well established and makes fun to code with. Due to its maturity, there is a lot of documentation and many examples out there. Going with R simply can’t be a mistake if you’re into data.
Python is great, it is not the best performing still, it is fast, easy to read and learn and comes with a variety of libraries. The main advantage, in my opinion, is, that Python can be used for so many different purposes. Python often is so intuitive, you will wonder how easy things can be.
Comparing Python and (the other general-purpose language) Julia, it is not unlikely to see a shift towards Julia one day, especially for more than just scientific purposes — but time will tell.
As always, see you next time! Stay safe, stay at home.
[0] Image by Ferdinand Stöhr (Thanks !) — https://unsplash.com/@fellowferdi?utm_source=medium&utm_medium=referral
[1] Julia Case Studies — https://juliacomputing.com/case-studies/
[2] R Users — https://www.datasciencecentral.com/profiles/blogs/list-of-companies-using-r
#Julia #R #Rlang #Python #Numpy #Pandas #DataScience #WebDevelopment #IDE #Google #IBM #Twitter | [
{
"code": null,
"e": 308,
"s": 172,
"text": "Once again, I found myself in the middle of considering learning a new language or simply fostering my knowledge of one I already know."
},
{
"code": null,
"e": 592,
"s": 308,
"text": "Every year seems to be the year of a “new” language and it appears that the talk about the “data science languages” has come back stronger than ever. I will, therefore, provide a quick look at all three languages, Julia, R and Python, while guiding you through a basic KNN algorithm."
},
{
"code": null,
"e": 708,
"s": 592,
"text": "We will address languages in the following order (1) Julia, (2) R and (3) Python. Code can be found embedded below."
},
{
"code": null,
"e": 1121,
"s": 708,
"text": "First things first, the background check. To begin with Julia, this general-purpose, dynamic language was introduced in 2012 and caters everyone willing to learn a new language that is perfectly suitable for performance-intensive tasks. Julia, like both other languages, follows multiple programming paradigms so no matter what programming knowledge you have, you are likely being able to catch up quite quickly."
},
{
"code": null,
"e": 1429,
"s": 1121,
"text": "I personally appreciate the sound implementation of optional typing which may be very handy depending on the purpose of your software. Syntax sometimes seems a bit like a mixture somewhere in between R and Python, but in general, you will not have a hard time to find ways helping yourself if you got stuck."
},
{
"code": null,
"e": 1699,
"s": 1429,
"text": "Although Julia is meant to be general-purpose and high performance, it seems that primarily the data science community is really driving Julia’s success. There is an already long list of notable users: Nasa, IBM, BlackRock, Pfizer or the NY Fed — just to name a few[1]."
},
{
"code": null,
"e": 2298,
"s": 1699,
"text": "R was first released in 1993 and it is more than ever one of the main contenders in statistical computing. Other than Julia, R was invented to serve as a programming language for scientific purposes. The language succeeded (imho) over various large competitors like IBM’s SPSS (which has a spreadsheet-like user interface and is, therefore, easier to use for many) and SAS which is a commercial analytics software provider and language (using the same name). R is often appreciated for a straightforward way of achieving tasks as well as brilliant and at the same time easy ways to illustrate data."
},
{
"code": null,
"e": 2945,
"s": 2298,
"text": "About the same time R has emerged, Guido van Rossum invented Python, a general purpose, interpreted and object-oriented programming language. Python has quite stagnated over time, got fierce competition from e.g. Ruby (especially with regard to web development — Ruby on Rails), but eventually became the first choice for many. Pythons success in data science skyrocketed in the 2000s after essential libraries had emerged. Depending on where you compare data, Python is today among the top 2 or 3 languages used (depending on the sources). Python is convenient as it can be used for simple tasks like automatization, but also for large programs."
},
{
"code": null,
"e": 3126,
"s": 2945,
"text": "For data science purposes Python requires to gear up through Pandas (2008) and Numpy/Scipy (2005, 2001), as the standalone language will not provide you with the necessary tooling."
},
{
"code": null,
"e": 3523,
"s": 3126,
"text": "One of the issues you might often read about when browsing the web is, that some languages simply come with [confusingly] large varieties of packages, which can be a great thing, but may also add complexity and lets the language drift away from a ‘common standard’ of used packages. If this sounds weird to you, just try to find a good Grubbs test, which is useful for outlier removal, in Python."
},
{
"code": null,
"e": 3895,
"s": 3523,
"text": "As Julia is the youngest among our candidates (even if we consider Python’s rise from the late 2000s onward), packages are less overwhelming in its magnitude (however steadily growing), R is well established and comes with many packages that are used as a common standard. Python does it all, there are some “major” libraries, but the options to choose from seem endless."
},
{
"code": null,
"e": 3965,
"s": 3895,
"text": "Enough for now, let’s jump into our data — the IRIS flowers data set:"
},
{
"code": null,
"e": 4188,
"s": 3965,
"text": "In order to make things comparable later on, here is a test data point and its reference class. These two shall provide us with the opportunity to compare an “similar to an existing” data point to our predicted data point."
},
{
"code": null,
"e": 4310,
"s": 4188,
"text": "## Our test data point derived from the reference class## We can assume that the result must be class = 1[7,3,5,1] ~> 1.0"
},
{
"code": null,
"e": 4370,
"s": 4310,
"text": "The reference class, which is a data point in IRIS dataset:"
},
{
"code": null,
"e": 4558,
"s": 4370,
"text": "## Reference classsepal_length 7.0 -> 7 (0)sepal_width 3.2 -> 3 (-.2)petal_length 4.7 -> 5 (+.3)petal_width 1.4 -> 1 (-.4)class 1.0 ≈> 1.0 Name: 50, dtype: float64"
},
{
"code": null,
"e": 4662,
"s": 4558,
"text": "Julia does the start. We will use CSV, DataFrames and Statistics in order to calculate our knn results."
},
{
"code": null,
"e": 4888,
"s": 4662,
"text": "Clearly, renaming columns seems a lot different than we know from R and Python, the dictionary, in contrast, is great to use. One little hint, use double quotes not single ones because Julia won’t handle single quotes (sad!)."
},
{
"code": null,
"e": 5076,
"s": 4888,
"text": "Further, note that the rename! function is followed by an exclamation mark — for a good reason: This function modifies its arguments! So keep this in mind when writing your own functions."
},
{
"code": null,
"e": 5585,
"s": 5076,
"text": "Personally, I prefer using dictionaries here, however as we used a dict for the mapping already, I demonstrated the collection and calculation of nearest neighbors through the data type DataFrame. While the import was quite straightforward, the loop construction reminded me more of ancient Pascal (RIP), further consider not to use extensive line breaks inside the loops when using IJulia kernel, I experienced errors as the end part was sometimes not found. Anyways, I recommend using Atom for development."
},
{
"code": null,
"e": 5632,
"s": 5585,
"text": "The results — just to compare with the others:"
},
{
"code": null,
"e": 5674,
"s": 5632,
"text": "Julia:[53, 77, 51, 59, 87]Prediction: 1.0"
},
{
"code": null,
"e": 6132,
"s": 5674,
"text": "Next it’s time for R to shine. At this point is worth to note, as far as I could see from my professional background, R is still the way to go — and this will likely remain as is. Why? R is well established, extensive in its magnitude (Machine Learning, linear algebra, ggplot, etc.), can be used for simple scripts and is already in place in many companies like Facebook, Google, Twitter, Microsoft, Uber just to name the best known — impressive, right?[2]"
},
{
"code": null,
"e": 6239,
"s": 6132,
"text": "Fun fact, IBM joined the R Consortium Group (remember I mentioned IBM as a competitor with SPSS earlier?)!"
},
{
"code": null,
"e": 6351,
"s": 6239,
"text": "To my experience, R is taught at many universities, too (I had the pleasure twice). What can I say, R is great!"
},
{
"code": null,
"e": 6827,
"s": 6351,
"text": "R Syntax is easy to read and also quite fun to learn. I appreciate its similarities to other languages and accurate error messages when it comes to debugging. As R is supported from its early years on, for development you will probably like to use Atom or (beloved) RStudio. What is note mentioning, I often experience that R is far less forgiving when it comes to inaccurate code, forgetting a comma might cause an hour of head scratching. The learning curve is quite steep."
},
{
"code": null,
"e": 6933,
"s": 6827,
"text": "The results — just to compare with the others. Note, like Julia but unlike Python, the index starts at 1."
},
{
"code": null,
"e": 7165,
"s": 6933,
"text": "R: X.index.....i X.dist.....distance53 53 0.529150377 77 0.529150351 51 0.538516559 59 0.648074187 87 0.6633250Prediction: 1"
},
{
"code": null,
"e": 7205,
"s": 7165,
"text": "At last, let’s have a look at Python 🐍."
},
{
"code": null,
"e": 7570,
"s": 7205,
"text": "Why I love Python is its list comprehension, powerful iteration methods and neat data structures. Although it is great fun to use a variety of tools, it might make it quite a bit harder to start and understand. IDEs for Python are numerous, I would go for Pycharm (which is free for standard purposes != Notebooks and Web development) or Atom (for the third time)."
},
{
"code": null,
"e": 7845,
"s": 7570,
"text": "Our knn algorithm is quite compact (maybe it is due to the fact, that I have learned Python the longest .. ), still, sorting using lambda and list comprehension may not be everyone’s best friend. I have not used a dataFrames in this case, as I did not want to import 🐼 here."
},
{
"code": null,
"e": 7892,
"s": 7845,
"text": "The results — just to compare with the others:"
},
{
"code": null,
"e": 8069,
"s": 7892,
"text": "Python:[[52, 0.5291502622129179], [76, 0.5291502622129183], [50, 0.5385164807134504], [58, 0.6480740698407865], [86, 0.6633249580710798], [77, 0.7615773105863908]]Prediction: 1"
},
{
"code": null,
"e": 8536,
"s": 8069,
"text": "Julia — Honestly I did really enjoy using Julia, however it sometimes feels .. complicated, more than necessary. In the below example I arbitrarily used a dictionary (which is not available in R and more convenient in Python) as well as a DataFrame to manipulate data. In contrast, working with most data structures is quite fun and seems indeed very fast. Julia might be a modern “one language fits all” language. This could indeed be the beginning of a love story!"
},
{
"code": null,
"e": 8796,
"s": 8536,
"text": "R is just rock solid. It is providing a huge number of packages, is very well established and makes fun to code with. Due to its maturity, there is a lot of documentation and many examples out there. Going with R simply can’t be a mistake if you’re into data."
},
{
"code": null,
"e": 9089,
"s": 8796,
"text": "Python is great, it is not the best performing still, it is fast, easy to read and learn and comes with a variety of libraries. The main advantage, in my opinion, is, that Python can be used for so many different purposes. Python often is so intuitive, you will wonder how easy things can be."
},
{
"code": null,
"e": 9283,
"s": 9089,
"text": "Comparing Python and (the other general-purpose language) Julia, it is not unlikely to see a shift towards Julia one day, especially for more than just scientific purposes — but time will tell."
},
{
"code": null,
"e": 9338,
"s": 9283,
"text": "As always, see you next time! Stay safe, stay at home."
},
{
"code": null,
"e": 9453,
"s": 9338,
"text": "[0] Image by Ferdinand Stöhr (Thanks !) — https://unsplash.com/@fellowferdi?utm_source=medium&utm_medium=referral"
},
{
"code": null,
"e": 9519,
"s": 9453,
"text": "[1] Julia Case Studies — https://juliacomputing.com/case-studies/"
},
{
"code": null,
"e": 9609,
"s": 9519,
"text": "[2] R Users — https://www.datasciencecentral.com/profiles/blogs/list-of-companies-using-r"
}
] |
What is NULL check and insertion rule in a DB2 table? | Null in DB2 is defined as nothing. It is an unknown value. If we want to restrict NULL value in any column then the column should be defined with the “NOT NULL” parameter in CREATE TABLE.
The “NOT NULL” will force the user to enter a value for the column. However, if we do not
want to give any value for this column we can also place a “WITH DEFAULT” parameter which will allow DB2 to place the default value in case the user has not provided any value for the “NOT NULL” column.
For example, if we have a column INVOICE_ID which should be not null and also, we want DB2 to insert spaces in this column if the user does not give any value for this column,then we will define the column as below−
CREATE TABLE ORDERS
(ORDER_ID CHAR(15) NOT NULL,
ORDER_DATE DATE,
INVOICE_ID CHAR(15), NOT NULL WITH DEFAULT
ORDER_TOTAL DECIMAL(9,2),
TRANSACTION_ID CHAR(15),
PRIMARY KEY(ORDER_ID),
IN DB4ES01;
The column INVOICE_ID is defined with data type CHAR and the default value taken by DB2 for CHAR is spaces. So in the above case, we have defined INVOICE_ID column as
NOT NULL and it will take default value as spaces when an explicit value is not given for this column. | [
{
"code": null,
"e": 1250,
"s": 1062,
"text": "Null in DB2 is defined as nothing. It is an unknown value. If we want to restrict NULL value in any column then the column should be defined with the “NOT NULL” parameter in CREATE TABLE."
},
{
"code": null,
"e": 1543,
"s": 1250,
"text": "The “NOT NULL” will force the user to enter a value for the column. However, if we do not\nwant to give any value for this column we can also place a “WITH DEFAULT” parameter which will allow DB2 to place the default value in case the user has not provided any value for the “NOT NULL” column."
},
{
"code": null,
"e": 1759,
"s": 1543,
"text": "For example, if we have a column INVOICE_ID which should be not null and also, we want DB2 to insert spaces in this column if the user does not give any value for this column,then we will define the column as below−"
},
{
"code": null,
"e": 1972,
"s": 1759,
"text": "CREATE TABLE ORDERS\n (ORDER_ID CHAR(15) NOT NULL,\n ORDER_DATE DATE,\n INVOICE_ID CHAR(15), NOT NULL WITH DEFAULT\n ORDER_TOTAL DECIMAL(9,2),\n TRANSACTION_ID CHAR(15),\n PRIMARY KEY(ORDER_ID),\nIN DB4ES01;"
},
{
"code": null,
"e": 2242,
"s": 1972,
"text": "The column INVOICE_ID is defined with data type CHAR and the default value taken by DB2 for CHAR is spaces. So in the above case, we have defined INVOICE_ID column as\nNOT NULL and it will take default value as spaces when an explicit value is not given for this column."
}
] |
HTML5 Canvas - Using Images | This tutorial would show how to import an external image into a canvas and then how to draw on that image by using following methods −
beginPath()
This method resets the current path.
moveTo(x, y)
This method creates a new subpath with the given point.
closePath()
This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
drawImage(image, dx, dy)
This method draws the given image onto the canvas. Here image is a reference to an image or canvas object. x and y form the coordinate on the target canvas where our image should be placed.
Following is a simple example which makes use of above mentioned methods to import an image.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
var img = new Image();
img.src = '/images/backdrop.jpg';
img.onload = function() {
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
It will produce the following result −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2743,
"s": 2608,
"text": "This tutorial would show how to import an external image into a canvas and then how to draw on that image by using following methods −"
},
{
"code": null,
"e": 2755,
"s": 2743,
"text": "beginPath()"
},
{
"code": null,
"e": 2792,
"s": 2755,
"text": "This method resets the current path."
},
{
"code": null,
"e": 2805,
"s": 2792,
"text": "moveTo(x, y)"
},
{
"code": null,
"e": 2861,
"s": 2805,
"text": "This method creates a new subpath with the given point."
},
{
"code": null,
"e": 2873,
"s": 2861,
"text": "closePath()"
},
{
"code": null,
"e": 3019,
"s": 2873,
"text": "This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath."
},
{
"code": null,
"e": 3026,
"s": 3019,
"text": "fill()"
},
{
"code": null,
"e": 3086,
"s": 3026,
"text": "This method fills the subpaths with the current fill style."
},
{
"code": null,
"e": 3095,
"s": 3086,
"text": "stroke()"
},
{
"code": null,
"e": 3159,
"s": 3095,
"text": "This method strokes the subpaths with the current stroke style."
},
{
"code": null,
"e": 3184,
"s": 3159,
"text": "drawImage(image, dx, dy)"
},
{
"code": null,
"e": 3374,
"s": 3184,
"text": "This method draws the given image onto the canvas. Here image is a reference to an image or canvas object. x and y form the coordinate on the target canvas where our image should be placed."
},
{
"code": null,
"e": 3467,
"s": 3374,
"text": "Following is a simple example which makes use of above mentioned methods to import an image."
},
{
"code": null,
"e": 4725,
"s": 3467,
"text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <script type = \"text/javascript\">\n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n // Draw shapes\n var img = new Image();\n img.src = '/images/backdrop.jpg';\n \n img.onload = function() {\n ctx.drawImage(img,0,0);\n ctx.beginPath();\n \n ctx.moveTo(30,96);\n ctx.lineTo(70,66);\n \n ctx.lineTo(103,76);\n ctx.lineTo(170,15);\n \n ctx.stroke();\n }\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body onload = \"drawShape();\">\n <canvas id = \"mycanvas\"></canvas>\n </body>\n \n</html>"
},
{
"code": null,
"e": 4764,
"s": 4725,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4797,
"s": 4764,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4811,
"s": 4797,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4846,
"s": 4811,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4860,
"s": 4846,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4895,
"s": 4860,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4912,
"s": 4895,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4947,
"s": 4912,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4978,
"s": 4947,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5011,
"s": 4978,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5042,
"s": 5011,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5077,
"s": 5042,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5108,
"s": 5077,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5115,
"s": 5108,
"text": " Print"
},
{
"code": null,
"e": 5126,
"s": 5115,
"text": " Add Notes"
}
] |
Finding middle element in a linked list | Practice | GeeksforGeeks | Given a singly linked list of N nodes.
The task is to find the middle of the linked list. For example, if the linked list is
1-> 2->3->4->5, then the middle node of the list is 3.
If there are two middle nodes(in case, when N is even), print the second middle element.
For example, if the linked list given is 1->2->3->4->5->6, then the middle node of the list is 4.
Example 1:
Input:
LinkedList: 1->2->3->4->5
Output: 3
Explanation:
Middle of linked list is 3.
Example 2:
Input:
LinkedList: 2->4->6->7->5->1
Output: 7
Explanation:
Middle of linked list is 7.
Your Task:
The task is to complete the function getMiddle() which takes a head reference as the only argument and should return the data at the middle node of the linked list.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 5000
0
mannukhurana1039710 hours ago
Java
int getMiddle(Node head)
{
// Time = O(n/2+1);
// space = O(1)
if(head==null) return -1;
if(head.next==null) return head.data;
Node slow=head;
Node fast=head;
while(fast.next!=null ){
slow = slow.next;
if(fast.next.next==null) return slow.data;
fast = fast.next.next;
}
return slow.data;
}
0
2019sushilkumarkori3 days ago
int getMiddle(Node *head)
{
// Your code here
int n=0;
Node* temp=head;
while(temp!=NULL){
n++;
temp=temp->next;
}
temp = head;
int i=0;
while(temp!=NULL){
i++;
if(i == ((n/2)+1)){
return temp->data;
}
temp=temp->next;
}
}
0
yw0z81sl8pirjq7u6r2ti6ctdqdgrmfgb0qwqvx06 days ago
Java solution:
class Solution{ public static int len(Node node){ int count=0; while(node!=null){ node=node.next; count++; } return count; } int getMiddle(Node head) { // Your code here. int n = len(head); if(n%2!=0){ for(int i =0;i<((n-1)/2);i++){ head=head.next; } return head.data; } else{ for(int i=0;i<n/2;i++){ head=head.next; } return head.data; } }}
0
cascadenienuo6 days ago
Idea→ The idea here is to apply the famous fast and slow pointer algorithm. We know that whenever our fast pointer will reach the end, our slow pointer will be pointing to half the distance (i.e. the middle of the linked list), as the speed of the slow pointer is exactly half that of the fast one.
class Solution{
public:
int getMiddle(Node *head)
{
if(head == NULL)return -1;
Node* fast = head;
Node* slow = head;
while(fast->next!=NULL && fast->next->next!=NULL){
fast = fast->next->next;
slow = slow->next;
}
//This check is just because it is mentioned in the problem that for even length we need to return the second mid.
if(fast->next == NULL)
return slow->data;
return slow->next->data;
}
};
0
cascadenienuo
This comment was deleted.
+1
ritikakumari596736 days ago
// { Driver Code Starts//Initial template for C++
#include <bits/stdc++.h>using namespace std;
struct Node{ int data; struct Node* next; Node(int x){ data = x; next = NULL; }};void printList(Node* node) { while (node != NULL) { cout << node->data <<" "; node = node->next; } cout<<"\n";}
// } Driver Code Ends/* Link list Node struct Node { int data; Node* next; Node(int x){ data = x; next = NULL; } }; */class Solution{ public: /* Should return data of middle node. If linked list is empty, then -1*/ int getMiddle(Node *head) { // Your code here if(head==NULL) { return -1; } Node* temp=head; int count=0; while(temp!=NULL) { temp=temp->next; count++; } int start=0; Node* t=head; while(start!=count/2) { t=t->next; start++; } return t->data; }};
// { Driver Code Starts.
int main() { //code int t; cin>>t; while(t--){ int N; cin>>N; int data; cin>>data; struct Node *head = new Node(data); struct Node *tail = head; for (int i = 0; i < N-1; ++i) { cin>>data; tail->next = new Node(data); tail = tail->next; } Solution ob; cout << ob.getMiddle(head) << endl; } return 0;} // } Driver Code
method-2
// { Driver Code Starts//Initial template for C++
#include <bits/stdc++.h>using namespace std;
struct Node{ int data; struct Node* next; Node(int x){ data = x; next = NULL; }};void printList(Node* node) { while (node != NULL) { cout << node->data <<" "; node = node->next; } cout<<"\n";}
// } Driver Code Ends/* Link list Node struct Node { int data; Node* next; Node(int x){ data = x; next = NULL; } }; */class Solution{ public: /* Should return data of middle node. If linked list is empty, then -1*/ int getMiddle(Node *head) { // Your code here if(head==NULL) { return -1; } Node* slow=head; Node* fast=head; while(fast!=NULL&&fast->next!=NULL) { fast=fast->next->next; slow=slow->next; } return slow->data; }};
// { Driver Code Starts.
int main() { //code int t; cin>>t; while(t--){ int N; cin>>N; int data; cin>>data; struct Node *head = new Node(data); struct Node *tail = head; for (int i = 0; i < N-1; ++i) { cin>>data; tail->next = new Node(data); tail = tail->next; } Solution ob; cout << ob.getMiddle(head) << endl; } return 0;} // } Driver Code Ends
effective way of solving-:
step-1:
take 2 pointer named slow and fast both pointing on head;
step-2 check it while fast≠ null and fast→next→next ≠ null;
step-3
move slow pointer one step means slow to slow→next
and make fast 2step fast to fast→next→next;
step-4
return slow->data and it will return mid value data
its tc-0(n)
0
sudeepgarg6716 days ago
class Solution{ public: /* Should return data of middle node. If linked list is empty, then -1*/ int getMiddle(Node *head) { Node *temp = head; int count = 0; while(temp!=NULL){ count++; temp = temp->next; } int start = 0; Node *temp2 = head; while(start!=count/2){ temp2 = temp2->next; start++; } return temp2->data; }};
0
akaashhardha1 week ago
int getMiddle(Node *head) { Node *head_ref = head; int count = 0; while(head_ref != NULL){ count++; head_ref = head_ref->next; } if(count % 2 == 0){ int mid = count / 2; Node *head_ref1 = head; for(int i = 1 ; i < mid; i++) head_ref1 = head_ref1->next; return head_ref1->next->data; } else{ int mid = count / 2; Node *head_ref2 = head; for(int i = 0 ; i < mid ; i++) head_ref2 = head_ref2->next; return head_ref2->data; } }};
0
09himanshusah1 week ago
JavaScript Solution
class Solution {
/* Should return data of middle node. If linked list is empty, then -1*/
getMiddle(node)
{
//your code here
let slow = node;
let fast = node;
while(fast != null) {
if(fast.next == null) return slow.data;
slow = slow.next;
fast = fast.next.next;
}
return slow.data;
}
}
0
shashankshekhar8891 week ago
def findMid(self, head):
c=0
temp=head
while(temp):
temp=temp.next
c+=1
cur=head
for i in range(c//2):
cur=cur.next
return cur.data
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": 605,
"s": 238,
"text": "Given a singly linked list of N nodes.\nThe task is to find the middle of the linked list. For example, if the linked list is\n1-> 2->3->4->5, then the middle node of the list is 3.\nIf there are two middle nodes(in case, when N is even), print the second middle element.\nFor example, if the linked list given is 1->2->3->4->5->6, then the middle node of the list is 4."
},
{
"code": null,
"e": 616,
"s": 605,
"text": "Example 1:"
},
{
"code": null,
"e": 703,
"s": 616,
"text": "Input:\nLinkedList: 1->2->3->4->5\nOutput: 3 \nExplanation: \nMiddle of linked list is 3.\n"
},
{
"code": null,
"e": 715,
"s": 703,
"text": "Example 2: "
},
{
"code": null,
"e": 805,
"s": 715,
"text": "Input:\nLinkedList: 2->4->6->7->5->1\nOutput: 7 \nExplanation: \nMiddle of linked list is 7.\n"
},
{
"code": null,
"e": 981,
"s": 805,
"text": "Your Task:\nThe task is to complete the function getMiddle() which takes a head reference as the only argument and should return the data at the middle node of the linked list."
},
{
"code": null,
"e": 1045,
"s": 981,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1073,
"s": 1045,
"text": "Constraints:\n1 <= N <= 5000"
},
{
"code": null,
"e": 1075,
"s": 1073,
"text": "0"
},
{
"code": null,
"e": 1105,
"s": 1075,
"text": "mannukhurana1039710 hours ago"
},
{
"code": null,
"e": 1110,
"s": 1105,
"text": "Java"
},
{
"code": null,
"e": 1545,
"s": 1112,
"text": "int getMiddle(Node head)\n {\n // Time = O(n/2+1);\n // space = O(1)\n if(head==null) return -1;\n if(head.next==null) return head.data;\n \n Node slow=head;\n Node fast=head;\n while(fast.next!=null ){\n slow = slow.next;\n if(fast.next.next==null) return slow.data;\n fast = fast.next.next;\n }\n \n return slow.data;\n }"
},
{
"code": null,
"e": 1547,
"s": 1545,
"text": "0"
},
{
"code": null,
"e": 1577,
"s": 1547,
"text": "2019sushilkumarkori3 days ago"
},
{
"code": null,
"e": 1972,
"s": 1577,
"text": " int getMiddle(Node *head)\n {\n // Your code here\n int n=0;\n Node* temp=head;\n while(temp!=NULL){\n n++;\n temp=temp->next;\n }\n temp = head;\n int i=0;\n while(temp!=NULL){\n i++;\n if(i == ((n/2)+1)){\n return temp->data;\n }\n temp=temp->next;\n }\n }"
},
{
"code": null,
"e": 1974,
"s": 1972,
"text": "0"
},
{
"code": null,
"e": 2025,
"s": 1974,
"text": "yw0z81sl8pirjq7u6r2ti6ctdqdgrmfgb0qwqvx06 days ago"
},
{
"code": null,
"e": 2040,
"s": 2025,
"text": "Java solution:"
},
{
"code": null,
"e": 2616,
"s": 2042,
"text": "class Solution{ public static int len(Node node){ int count=0; while(node!=null){ node=node.next; count++; } return count; } int getMiddle(Node head) { // Your code here. int n = len(head); if(n%2!=0){ for(int i =0;i<((n-1)/2);i++){ head=head.next; } return head.data; } else{ for(int i=0;i<n/2;i++){ head=head.next; } return head.data; } }}"
},
{
"code": null,
"e": 2618,
"s": 2616,
"text": "0"
},
{
"code": null,
"e": 2642,
"s": 2618,
"text": "cascadenienuo6 days ago"
},
{
"code": null,
"e": 2941,
"s": 2642,
"text": "Idea→ The idea here is to apply the famous fast and slow pointer algorithm. We know that whenever our fast pointer will reach the end, our slow pointer will be pointing to half the distance (i.e. the middle of the linked list), as the speed of the slow pointer is exactly half that of the fast one."
},
{
"code": null,
"e": 3447,
"s": 2943,
"text": "class Solution{\n public:\n int getMiddle(Node *head)\n {\n if(head == NULL)return -1;\n Node* fast = head;\n Node* slow = head;\n while(fast->next!=NULL && fast->next->next!=NULL){\n fast = fast->next->next;\n slow = slow->next;\n }\n \n//This check is just because it is mentioned in the problem that for even length we need to return the second mid.\n if(fast->next == NULL) \n return slow->data;\n return slow->next->data;\n }\n};"
},
{
"code": null,
"e": 3449,
"s": 3447,
"text": "0"
},
{
"code": null,
"e": 3463,
"s": 3449,
"text": "cascadenienuo"
},
{
"code": null,
"e": 3489,
"s": 3463,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3492,
"s": 3489,
"text": "+1"
},
{
"code": null,
"e": 3520,
"s": 3492,
"text": "ritikakumari596736 days ago"
},
{
"code": null,
"e": 3570,
"s": 3520,
"text": "// { Driver Code Starts//Initial template for C++"
},
{
"code": null,
"e": 3615,
"s": 3570,
"text": "#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 3855,
"s": 3615,
"text": "struct Node{ int data; struct Node* next; Node(int x){ data = x; next = NULL; }};void printList(Node* node) { while (node != NULL) { cout << node->data <<\" \"; node = node->next; } cout<<\"\\n\";}"
},
{
"code": null,
"e": 4493,
"s": 3855,
"text": "// } Driver Code Ends/* Link list Node struct Node { int data; Node* next; Node(int x){ data = x; next = NULL; } }; */class Solution{ public: /* Should return data of middle node. If linked list is empty, then -1*/ int getMiddle(Node *head) { // Your code here if(head==NULL) { return -1; } Node* temp=head; int count=0; while(temp!=NULL) { temp=temp->next; count++; } int start=0; Node* t=head; while(start!=count/2) { t=t->next; start++; } return t->data; }};"
},
{
"code": null,
"e": 4518,
"s": 4493,
"text": "// { Driver Code Starts."
},
{
"code": null,
"e": 4950,
"s": 4518,
"text": "int main() { //code int t; cin>>t; while(t--){ int N; cin>>N; int data; cin>>data; struct Node *head = new Node(data); struct Node *tail = head; for (int i = 0; i < N-1; ++i) { cin>>data; tail->next = new Node(data); tail = tail->next; } Solution ob; cout << ob.getMiddle(head) << endl; } return 0;} // } Driver Code"
},
{
"code": null,
"e": 4959,
"s": 4950,
"text": "method-2"
},
{
"code": null,
"e": 5009,
"s": 4959,
"text": "// { Driver Code Starts//Initial template for C++"
},
{
"code": null,
"e": 5054,
"s": 5009,
"text": "#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 5294,
"s": 5054,
"text": "struct Node{ int data; struct Node* next; Node(int x){ data = x; next = NULL; }};void printList(Node* node) { while (node != NULL) { cout << node->data <<\" \"; node = node->next; } cout<<\"\\n\";}"
},
{
"code": null,
"e": 5872,
"s": 5294,
"text": "// } Driver Code Ends/* Link list Node struct Node { int data; Node* next; Node(int x){ data = x; next = NULL; } }; */class Solution{ public: /* Should return data of middle node. If linked list is empty, then -1*/ int getMiddle(Node *head) { // Your code here if(head==NULL) { return -1; } Node* slow=head; Node* fast=head; while(fast!=NULL&&fast->next!=NULL) { fast=fast->next->next; slow=slow->next; } return slow->data; }};"
},
{
"code": null,
"e": 5897,
"s": 5872,
"text": "// { Driver Code Starts."
},
{
"code": null,
"e": 6334,
"s": 5897,
"text": "int main() { //code int t; cin>>t; while(t--){ int N; cin>>N; int data; cin>>data; struct Node *head = new Node(data); struct Node *tail = head; for (int i = 0; i < N-1; ++i) { cin>>data; tail->next = new Node(data); tail = tail->next; } Solution ob; cout << ob.getMiddle(head) << endl; } return 0;} // } Driver Code Ends"
},
{
"code": null,
"e": 6361,
"s": 6334,
"text": "effective way of solving-:"
},
{
"code": null,
"e": 6369,
"s": 6361,
"text": "step-1:"
},
{
"code": null,
"e": 6428,
"s": 6369,
"text": "take 2 pointer named slow and fast both pointing on head;"
},
{
"code": null,
"e": 6490,
"s": 6428,
"text": "step-2 check it while fast≠ null and fast→next→next ≠ null;"
},
{
"code": null,
"e": 6497,
"s": 6490,
"text": "step-3"
},
{
"code": null,
"e": 6548,
"s": 6497,
"text": "move slow pointer one step means slow to slow→next"
},
{
"code": null,
"e": 6592,
"s": 6548,
"text": "and make fast 2step fast to fast→next→next;"
},
{
"code": null,
"e": 6599,
"s": 6592,
"text": "step-4"
},
{
"code": null,
"e": 6651,
"s": 6599,
"text": "return slow->data and it will return mid value data"
},
{
"code": null,
"e": 6663,
"s": 6651,
"text": "its tc-0(n)"
},
{
"code": null,
"e": 6667,
"s": 6665,
"text": "0"
},
{
"code": null,
"e": 6691,
"s": 6667,
"text": "sudeepgarg6716 days ago"
},
{
"code": null,
"e": 7106,
"s": 6691,
"text": "class Solution{ public: /* Should return data of middle node. If linked list is empty, then -1*/ int getMiddle(Node *head) { Node *temp = head; int count = 0; while(temp!=NULL){ count++; temp = temp->next; } int start = 0; Node *temp2 = head; while(start!=count/2){ temp2 = temp2->next; start++; } return temp2->data; }};"
},
{
"code": null,
"e": 7108,
"s": 7106,
"text": "0"
},
{
"code": null,
"e": 7131,
"s": 7108,
"text": "akaashhardha1 week ago"
},
{
"code": null,
"e": 7761,
"s": 7131,
"text": "int getMiddle(Node *head) { Node *head_ref = head; int count = 0; while(head_ref != NULL){ count++; head_ref = head_ref->next; } if(count % 2 == 0){ int mid = count / 2; Node *head_ref1 = head; for(int i = 1 ; i < mid; i++) head_ref1 = head_ref1->next; return head_ref1->next->data; } else{ int mid = count / 2; Node *head_ref2 = head; for(int i = 0 ; i < mid ; i++) head_ref2 = head_ref2->next; return head_ref2->data; } }};"
},
{
"code": null,
"e": 7763,
"s": 7761,
"text": "0"
},
{
"code": null,
"e": 7787,
"s": 7763,
"text": "09himanshusah1 week ago"
},
{
"code": null,
"e": 7807,
"s": 7787,
"text": "JavaScript Solution"
},
{
"code": null,
"e": 8194,
"s": 7807,
"text": "class Solution {\n /* Should return data of middle node. If linked list is empty, then -1*/\n getMiddle(node)\n {\n //your code here\n let slow = node;\n let fast = node;\n while(fast != null) {\n if(fast.next == null) return slow.data;\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow.data;\n }\n}"
},
{
"code": null,
"e": 8196,
"s": 8194,
"text": "0"
},
{
"code": null,
"e": 8225,
"s": 8196,
"text": "shashankshekhar8891 week ago"
},
{
"code": null,
"e": 8454,
"s": 8225,
"text": "def findMid(self, head):\n c=0\n temp=head\n while(temp):\n temp=temp.next\n c+=1\n cur=head\n for i in range(c//2):\n cur=cur.next\n return cur.data\n "
},
{
"code": null,
"e": 8600,
"s": 8454,
"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": 8636,
"s": 8600,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8646,
"s": 8636,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8656,
"s": 8646,
"text": "\nContest\n"
},
{
"code": null,
"e": 8719,
"s": 8656,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8867,
"s": 8719,
"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": 9075,
"s": 8867,
"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": 9181,
"s": 9075,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Using NLP to improve your Resume | Towards Data Science | Recruiters are using increasingly complicated Software and tools to scan and match Resumes to posted job positions and job specifications. If your Resume (CV) is generic, or the job specification is vague and/or generic, these tools will work against you. AI really is working against your job application, and I am not sure you know it or will accept it! But let me demonstrate some techniques that can help you balance up the odds. Naturally, we will use NLP (Natural Language Processing), Python, and some Altair visuals. Are you ready to fight back?
Consider that you are interested in a good position that you noticed online. How many others would have seen the same job? Have roughly the same experience and qualifications as you? How many applicants might have applied, do you think? Could it be less than 10 or less than 1,000?
Further, consider that the interview panel might be only 5 strong candidates. So how do you ‘weed’ out 995 applications to refine and deliver just 5 strong candidates? This is why I say you need to balance up the odds or be thrown out with the weeds!
I suppose, first off, you could divide up those Resumes into a stack of 3 or 5. Print them off and assign them to human readers. Each reader provides one selection from their pile. With 5 readers that is a bunch of 200 Resumes — go pick the best one or two. Reading those would take a long time and probably only serve to yield an answer in the end. We can use Python to read all those Resumes in minutes!
Reading the article ‘How I used NLP (Spacy) to screen Data Science Resume’ here on Medium demonstrates that just two code lines will collect up the file names of those 1,000 Resumes.
#Function to read resumes from the folder one by onemypath='D:/NLP_Resume/Candidate Resume' onlyfiles = [os.path.join(mypath, f) for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]
The variable ‘onlyfiles’ is a Python list that contains the file names of all those Resumes got using the Python os library. If you study the article, you will also see how your resume can be ranked and eliminated almost automatically based on keyword analysis. Since we are trying to even up the odds, we need to focus on your desired job specification and your current resume. Do they match?
To even up the odds, we want to scan a job description, the Resume, and measure the match. Ideally, we do it so that the output is useful to tune in the game for you.
Since it is your Resume, you likely have that in either PDF or DOCX. There are Python modules available to read most data formats. Figure 1 demonstrates how to read the documents having saved the contents into a text file.
The first step is always to open the file and read the lines. The following step is to convert from a list of strings to a single text, doing some cleaning along the way. Figure 1 creates the variables ‘jobContent’, and ‘cvContent’ and these represent a string object that includes all the text. The next code snippet shows how to read a Word document directly.
import docx2txtresume = docx2txt.process("DAVID MOORE.docx")text_resume = str(resume)
The variable ‘text_resume’ is a string object that holds all the text from the Resume, just like before. You can also use PyPDF2.
import PyPDF2
Suffice it to say that a range of options exists for the practitioner to read the documents converting them to a clean treated text. Those documents could be extensive, hard to read, and frankly dull. You could start with a summary.
I love Gensim and use it frequently.
from gensim.summarization.summarizer import summarizefrom gensim.summarization import keywords
We created the variable ‘resume_text’ by reading a Word file. Let’s make a summary of the Resume and job posting.
print(summarize(text_resume, ratio=0.2))
Gensim.summarization.summarizer.summarize will create a concise summary for you.
summarize(jobContent, ratio=0.2)
Now you can read an overall summary of the job role and your existing Resume! Did you miss anything about the job role that is being highlighted in summary? Small nuanced details can help you sell yourself. Does your summarized document make sense and bring out your essential qualities?Perhaps a concise summary alone is not sufficient. Next, let us measure how similar your Resume is to a job specification. Figure 2 provides the code.
Broadly we make a list of our text objects then create an instance of the sklearn CountVectorizer() class. We also import the cosine_similarity metric, which helps us measure the similarity of the two documents. ‘Your resume matches about 69.44% of the job description’. That sounds wonderful, but I won’t get carried away. Now you can read a summary of the documents and get a similarity measurement. The odds are improving.
Next, we can look at the job description keywords and see which ones are matched in the Resume. Did we miss out on a few keywords that could strengthen the match towards 100%? Over to spacy now. It’s quite a journey so far. Gensim, sklearn and now spacy! I hope you aren’t dizzy!
from spacy.matcher import PhraseMatchermatcher = PhraseMatcher(Spnlp.vocab)from collections import Counterfrom gensim.summarization import keywords
We will use the PhraseMatcher feature of spacy to match critical phrases from the job description to the Resume. Gensim keywords can help to provide those phrases to match. Figure 3 shows how to run the match.
Using the snippet, in Figure 3, provides a list of matched keywords. Figure 4 shows a method to summarize those keyword matches. Using the Counter dictionary from Collections.
The term ‘reporting’ is contained in the job description, and the Resume has 3 hits. What phrases or keywords are in the job posting but aren’t on the CV (resume)? Could we add more? I used Pandas to answer this question — you can see the output in Figure 5.
If this is true, it is also strange. The match was 69.44% at the document level but look at that long list of keywords that aren’t mentioned on the Resume. Figure 6 shows the keywords that are mentioned.
In reality, there are very few keyword matches against the job specification, which leads to my scepticism about the cosine similarity measure of 69.44%. Still, the odds are improving because we can see keywords in the job specification that aren’t in the Resume. Fewer keyword matches mean that you are more likely to wash out with the weeds. Looking at the missing keywords, you could go right ahead, strengthen the Resume, and re-run the analysis. Just peppering your resume with keywords will have a negative consequence, though, and you have to be extremely careful with your art. You might get through an initial automated screening, but you will be eliminated because of a perceived lack of writing skill. We really need to rank phrases and focus on the essential topics or words in the job specification.
Let’s look at ranked phrases next. For this exercise, I will use my own NLP class and some methods I used previously.
from nlp import nlp as nlpLangProcessor = nlp()keywordsJob = LangProcessor.keywords(jobContent)keywordsCV = LangProcessor.keywords(cvContent)
Using my own class, I recovered the ranked phrases from the job and Resume objects we created earlier. The snippet below provides you with the method definition. We are now using the rake module to extract ranked_phrases and scores.
def keywords(self, text): keyword = {} self.rake.extract_keywords_from_text(text) keyword['ranked phrases'] = self.rake.get_ranked_phrases_with_scores() return keyword
Figure 7 provides an illustration of the output of the method call.
‘project management methodology — project management’ is ranked as 31.2, so this is the most crucial topic in the job posting. The critical phrases in the Resume can also be printed with a minor variation.
for item in keywordsCV['ranked phrases'][:10]: print (str(round(item[0],2)) + ' - ' + item[1] )
Reading the top phrases from both the Resume and the job posting, we can ask ourselves is there a match or the degree of the similarity? We can certainly run a sequence to find out! The following code creates a cross-reference between the ranked phrases on the job posting and from the Resume.
sims = []phrases = []for key in keywordsJob['ranked phrases']: rec={} rec['importance'] = key[0] texts = key[1] sims=[] avg_sim=0 for cvkey in keywordsCV['ranked phrases']: cvtext = cvkey[1] sims.append(fuzz.ratio(texts, cvtext)) #sims.append(lev.ratio(texts.lower(),cvtext.lower())) #sims.append(jaccard_similarity(texts,cvtext)) count=0 for s in sims: count=count+s avg_sim = count/len(sims) rec['similarity'] = avg_sim rec['text'] = texts phrases.append(rec)
Note that we are using fuzzy-wuzzy as the match engine. The code also has a Levenshtein ratio and jaccard_similarity function. Figure 8 provides an illustration of what this can look like.
The ‘importance’ variable is the ranked phrase score from the resume. The ‘similarity’ variable is the ratio score from fuzzy-wuzzy. The term ‘project management methodology’ is ranked 31.2 but cross-referencing the rated Resume phrases only scores 22.5 on average. Whilst project management is the top priority for the job, the Resume scores more decisively on different technical items. You see how AI works against your application by doing a similar exercise.
Figure 9 shows another perspective. Working with tokens (words) shows each word’s importance in the job description versus the number of hits in the Resume — the more occurrences of a specific word in the document, the greater the influence. The phrase finance is of low importance to the job description but highly influential in the Resume. Is this a Finance guy looking for an IT job? Words can betray you with the AI!
I am sure by now that you have the picture. Using NLP tools and libraries can help to really understand a job description and measure the relative match. It certainly isn’t robust or gospel, but it does tend to even the odds. Your words matter, but you cannot pepper keywords in a Resume. You really have to write a strong resume and apply for roles that suit you. Text processing and text mining is a big topic, and we only scratch the surface of what can be done. I find text mining and text-based machine learning models to be deadly accurate. Let’s look at some visuals using Altair and then conclude.
I have been using Altair a lot recently and much more so that Seaborn or Matplotlib. The grammar in Altair just clicks with me. I made three visuals to help with the discussion — figure 10 shows keyword importance and influence within the Resume. Using a colour scale, we can see that words like adoption appear twice in the CV but lower priority on the job posting.
Figure 11 shows the cross-reference of ranked topics found on the job posting and those found on the Resume. The most important phrase is ‘project management..’ but that scores weakly in the ranked terms from the CV.
Figure 12 plots similar words. Finance is used 10 times on the Resume but not mentioned at all in the job posting. The word project is mentioned on the Resume(CV) and also appears in the job posting.
Looking at the charts, it seems to me that the Resume and job description are not a good match. Very few shared keywords and the ranked phrases look very different. This is what gets your resume washed out with the weeds!
Reading this article might seem more like a big-budget “shoot ’em dead CGI Hollywood” movie. All the big-name actors generally appear in those blockbusters. The big NLP libraries had a starring role in this article, and we even had cameo appearances by many more, perhaps older and more mature names such as NLTK. We used libraries such as Gensim, Spacy, sklearn and demonstrated their use. With my own class making a guest appearance, wrapping NLTK, rake, textblob and a heap of other modules, all performing and surfacing insights into text analytics,showing you how you could be separated from that opportunity to land your dream job.
Landing that dream job requires a clear and unrelenting focus on detail and careful preparation of the job application, the CV, and cover letter. Using Natural Language processing is not going to change you into the best overall candidate. That is up to you! But it can improve your chances of beating the early rounds powered by AI.
Every fisher man knows that you need good bait! | [
{
"code": null,
"e": 726,
"s": 172,
"text": "Recruiters are using increasingly complicated Software and tools to scan and match Resumes to posted job positions and job specifications. If your Resume (CV) is generic, or the job specification is vague and/or generic, these tools will work against you. AI really is working against your job application, and I am not sure you know it or will accept it! But let me demonstrate some techniques that can help you balance up the odds. Naturally, we will use NLP (Natural Language Processing), Python, and some Altair visuals. Are you ready to fight back?"
},
{
"code": null,
"e": 1008,
"s": 726,
"text": "Consider that you are interested in a good position that you noticed online. How many others would have seen the same job? Have roughly the same experience and qualifications as you? How many applicants might have applied, do you think? Could it be less than 10 or less than 1,000?"
},
{
"code": null,
"e": 1259,
"s": 1008,
"text": "Further, consider that the interview panel might be only 5 strong candidates. So how do you ‘weed’ out 995 applications to refine and deliver just 5 strong candidates? This is why I say you need to balance up the odds or be thrown out with the weeds!"
},
{
"code": null,
"e": 1665,
"s": 1259,
"text": "I suppose, first off, you could divide up those Resumes into a stack of 3 or 5. Print them off and assign them to human readers. Each reader provides one selection from their pile. With 5 readers that is a bunch of 200 Resumes — go pick the best one or two. Reading those would take a long time and probably only serve to yield an answer in the end. We can use Python to read all those Resumes in minutes!"
},
{
"code": null,
"e": 1848,
"s": 1665,
"text": "Reading the article ‘How I used NLP (Spacy) to screen Data Science Resume’ here on Medium demonstrates that just two code lines will collect up the file names of those 1,000 Resumes."
},
{
"code": null,
"e": 2062,
"s": 1848,
"text": "#Function to read resumes from the folder one by onemypath='D:/NLP_Resume/Candidate Resume' onlyfiles = [os.path.join(mypath, f) for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]"
},
{
"code": null,
"e": 2456,
"s": 2062,
"text": "The variable ‘onlyfiles’ is a Python list that contains the file names of all those Resumes got using the Python os library. If you study the article, you will also see how your resume can be ranked and eliminated almost automatically based on keyword analysis. Since we are trying to even up the odds, we need to focus on your desired job specification and your current resume. Do they match?"
},
{
"code": null,
"e": 2623,
"s": 2456,
"text": "To even up the odds, we want to scan a job description, the Resume, and measure the match. Ideally, we do it so that the output is useful to tune in the game for you."
},
{
"code": null,
"e": 2846,
"s": 2623,
"text": "Since it is your Resume, you likely have that in either PDF or DOCX. There are Python modules available to read most data formats. Figure 1 demonstrates how to read the documents having saved the contents into a text file."
},
{
"code": null,
"e": 3208,
"s": 2846,
"text": "The first step is always to open the file and read the lines. The following step is to convert from a list of strings to a single text, doing some cleaning along the way. Figure 1 creates the variables ‘jobContent’, and ‘cvContent’ and these represent a string object that includes all the text. The next code snippet shows how to read a Word document directly."
},
{
"code": null,
"e": 3294,
"s": 3208,
"text": "import docx2txtresume = docx2txt.process(\"DAVID MOORE.docx\")text_resume = str(resume)"
},
{
"code": null,
"e": 3424,
"s": 3294,
"text": "The variable ‘text_resume’ is a string object that holds all the text from the Resume, just like before. You can also use PyPDF2."
},
{
"code": null,
"e": 3438,
"s": 3424,
"text": "import PyPDF2"
},
{
"code": null,
"e": 3671,
"s": 3438,
"text": "Suffice it to say that a range of options exists for the practitioner to read the documents converting them to a clean treated text. Those documents could be extensive, hard to read, and frankly dull. You could start with a summary."
},
{
"code": null,
"e": 3708,
"s": 3671,
"text": "I love Gensim and use it frequently."
},
{
"code": null,
"e": 3803,
"s": 3708,
"text": "from gensim.summarization.summarizer import summarizefrom gensim.summarization import keywords"
},
{
"code": null,
"e": 3917,
"s": 3803,
"text": "We created the variable ‘resume_text’ by reading a Word file. Let’s make a summary of the Resume and job posting."
},
{
"code": null,
"e": 3958,
"s": 3917,
"text": "print(summarize(text_resume, ratio=0.2))"
},
{
"code": null,
"e": 4039,
"s": 3958,
"text": "Gensim.summarization.summarizer.summarize will create a concise summary for you."
},
{
"code": null,
"e": 4072,
"s": 4039,
"text": "summarize(jobContent, ratio=0.2)"
},
{
"code": null,
"e": 4510,
"s": 4072,
"text": "Now you can read an overall summary of the job role and your existing Resume! Did you miss anything about the job role that is being highlighted in summary? Small nuanced details can help you sell yourself. Does your summarized document make sense and bring out your essential qualities?Perhaps a concise summary alone is not sufficient. Next, let us measure how similar your Resume is to a job specification. Figure 2 provides the code."
},
{
"code": null,
"e": 4936,
"s": 4510,
"text": "Broadly we make a list of our text objects then create an instance of the sklearn CountVectorizer() class. We also import the cosine_similarity metric, which helps us measure the similarity of the two documents. ‘Your resume matches about 69.44% of the job description’. That sounds wonderful, but I won’t get carried away. Now you can read a summary of the documents and get a similarity measurement. The odds are improving."
},
{
"code": null,
"e": 5216,
"s": 4936,
"text": "Next, we can look at the job description keywords and see which ones are matched in the Resume. Did we miss out on a few keywords that could strengthen the match towards 100%? Over to spacy now. It’s quite a journey so far. Gensim, sklearn and now spacy! I hope you aren’t dizzy!"
},
{
"code": null,
"e": 5364,
"s": 5216,
"text": "from spacy.matcher import PhraseMatchermatcher = PhraseMatcher(Spnlp.vocab)from collections import Counterfrom gensim.summarization import keywords"
},
{
"code": null,
"e": 5574,
"s": 5364,
"text": "We will use the PhraseMatcher feature of spacy to match critical phrases from the job description to the Resume. Gensim keywords can help to provide those phrases to match. Figure 3 shows how to run the match."
},
{
"code": null,
"e": 5750,
"s": 5574,
"text": "Using the snippet, in Figure 3, provides a list of matched keywords. Figure 4 shows a method to summarize those keyword matches. Using the Counter dictionary from Collections."
},
{
"code": null,
"e": 6009,
"s": 5750,
"text": "The term ‘reporting’ is contained in the job description, and the Resume has 3 hits. What phrases or keywords are in the job posting but aren’t on the CV (resume)? Could we add more? I used Pandas to answer this question — you can see the output in Figure 5."
},
{
"code": null,
"e": 6213,
"s": 6009,
"text": "If this is true, it is also strange. The match was 69.44% at the document level but look at that long list of keywords that aren’t mentioned on the Resume. Figure 6 shows the keywords that are mentioned."
},
{
"code": null,
"e": 7026,
"s": 6213,
"text": "In reality, there are very few keyword matches against the job specification, which leads to my scepticism about the cosine similarity measure of 69.44%. Still, the odds are improving because we can see keywords in the job specification that aren’t in the Resume. Fewer keyword matches mean that you are more likely to wash out with the weeds. Looking at the missing keywords, you could go right ahead, strengthen the Resume, and re-run the analysis. Just peppering your resume with keywords will have a negative consequence, though, and you have to be extremely careful with your art. You might get through an initial automated screening, but you will be eliminated because of a perceived lack of writing skill. We really need to rank phrases and focus on the essential topics or words in the job specification."
},
{
"code": null,
"e": 7144,
"s": 7026,
"text": "Let’s look at ranked phrases next. For this exercise, I will use my own NLP class and some methods I used previously."
},
{
"code": null,
"e": 7286,
"s": 7144,
"text": "from nlp import nlp as nlpLangProcessor = nlp()keywordsJob = LangProcessor.keywords(jobContent)keywordsCV = LangProcessor.keywords(cvContent)"
},
{
"code": null,
"e": 7519,
"s": 7286,
"text": "Using my own class, I recovered the ranked phrases from the job and Resume objects we created earlier. The snippet below provides you with the method definition. We are now using the rake module to extract ranked_phrases and scores."
},
{
"code": null,
"e": 7687,
"s": 7519,
"text": "def keywords(self, text): keyword = {} self.rake.extract_keywords_from_text(text) keyword['ranked phrases'] = self.rake.get_ranked_phrases_with_scores() return keyword"
},
{
"code": null,
"e": 7755,
"s": 7687,
"text": "Figure 7 provides an illustration of the output of the method call."
},
{
"code": null,
"e": 7961,
"s": 7755,
"text": "‘project management methodology — project management’ is ranked as 31.2, so this is the most crucial topic in the job posting. The critical phrases in the Resume can also be printed with a minor variation."
},
{
"code": null,
"e": 8057,
"s": 7961,
"text": "for item in keywordsCV['ranked phrases'][:10]: print (str(round(item[0],2)) + ' - ' + item[1] )"
},
{
"code": null,
"e": 8351,
"s": 8057,
"text": "Reading the top phrases from both the Resume and the job posting, we can ask ourselves is there a match or the degree of the similarity? We can certainly run a sequence to find out! The following code creates a cross-reference between the ranked phrases on the job posting and from the Resume."
},
{
"code": null,
"e": 8817,
"s": 8351,
"text": "sims = []phrases = []for key in keywordsJob['ranked phrases']: rec={} rec['importance'] = key[0] texts = key[1] sims=[] avg_sim=0 for cvkey in keywordsCV['ranked phrases']: cvtext = cvkey[1] sims.append(fuzz.ratio(texts, cvtext)) #sims.append(lev.ratio(texts.lower(),cvtext.lower())) #sims.append(jaccard_similarity(texts,cvtext)) count=0 for s in sims: count=count+s avg_sim = count/len(sims) rec['similarity'] = avg_sim rec['text'] = texts phrases.append(rec)"
},
{
"code": null,
"e": 9006,
"s": 8817,
"text": "Note that we are using fuzzy-wuzzy as the match engine. The code also has a Levenshtein ratio and jaccard_similarity function. Figure 8 provides an illustration of what this can look like."
},
{
"code": null,
"e": 9470,
"s": 9006,
"text": "The ‘importance’ variable is the ranked phrase score from the resume. The ‘similarity’ variable is the ratio score from fuzzy-wuzzy. The term ‘project management methodology’ is ranked 31.2 but cross-referencing the rated Resume phrases only scores 22.5 on average. Whilst project management is the top priority for the job, the Resume scores more decisively on different technical items. You see how AI works against your application by doing a similar exercise."
},
{
"code": null,
"e": 9892,
"s": 9470,
"text": "Figure 9 shows another perspective. Working with tokens (words) shows each word’s importance in the job description versus the number of hits in the Resume — the more occurrences of a specific word in the document, the greater the influence. The phrase finance is of low importance to the job description but highly influential in the Resume. Is this a Finance guy looking for an IT job? Words can betray you with the AI!"
},
{
"code": null,
"e": 10498,
"s": 9892,
"text": "I am sure by now that you have the picture. Using NLP tools and libraries can help to really understand a job description and measure the relative match. It certainly isn’t robust or gospel, but it does tend to even the odds. Your words matter, but you cannot pepper keywords in a Resume. You really have to write a strong resume and apply for roles that suit you. Text processing and text mining is a big topic, and we only scratch the surface of what can be done. I find text mining and text-based machine learning models to be deadly accurate. Let’s look at some visuals using Altair and then conclude."
},
{
"code": null,
"e": 10865,
"s": 10498,
"text": "I have been using Altair a lot recently and much more so that Seaborn or Matplotlib. The grammar in Altair just clicks with me. I made three visuals to help with the discussion — figure 10 shows keyword importance and influence within the Resume. Using a colour scale, we can see that words like adoption appear twice in the CV but lower priority on the job posting."
},
{
"code": null,
"e": 11082,
"s": 10865,
"text": "Figure 11 shows the cross-reference of ranked topics found on the job posting and those found on the Resume. The most important phrase is ‘project management..’ but that scores weakly in the ranked terms from the CV."
},
{
"code": null,
"e": 11282,
"s": 11082,
"text": "Figure 12 plots similar words. Finance is used 10 times on the Resume but not mentioned at all in the job posting. The word project is mentioned on the Resume(CV) and also appears in the job posting."
},
{
"code": null,
"e": 11504,
"s": 11282,
"text": "Looking at the charts, it seems to me that the Resume and job description are not a good match. Very few shared keywords and the ranked phrases look very different. This is what gets your resume washed out with the weeds!"
},
{
"code": null,
"e": 12142,
"s": 11504,
"text": "Reading this article might seem more like a big-budget “shoot ’em dead CGI Hollywood” movie. All the big-name actors generally appear in those blockbusters. The big NLP libraries had a starring role in this article, and we even had cameo appearances by many more, perhaps older and more mature names such as NLTK. We used libraries such as Gensim, Spacy, sklearn and demonstrated their use. With my own class making a guest appearance, wrapping NLTK, rake, textblob and a heap of other modules, all performing and surfacing insights into text analytics,showing you how you could be separated from that opportunity to land your dream job."
},
{
"code": null,
"e": 12476,
"s": 12142,
"text": "Landing that dream job requires a clear and unrelenting focus on detail and careful preparation of the job application, the CV, and cover letter. Using Natural Language processing is not going to change you into the best overall candidate. That is up to you! But it can improve your chances of beating the early rounds powered by AI."
}
] |
Check if a string has white space in JavaScript? | To check whitespace in a string, use the concept of indexOf(‘ ’). Following is the code −
function stringHasTheWhiteSpaceOrNot(value){
return value.indexOf(' ') >= 0;
}
var whiteSpace=stringHasTheWhiteSpaceOrNot("MyNameis John");
if(whiteSpace==true){
console.log("The string has whitespace");
} else {
console.log("The string does not have whitespace");
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo108.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo108.js
The string has whitespace | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "To check whitespace in a string, use the concept of indexOf(‘ ’). Following is the code −"
},
{
"code": null,
"e": 1440,
"s": 1152,
"text": "function stringHasTheWhiteSpaceOrNot(value){\n return value.indexOf(' ') >= 0;\n}\nvar whiteSpace=stringHasTheWhiteSpaceOrNot(\"MyNameis John\");\n if(whiteSpace==true){\n console.log(\"The string has whitespace\");\n } else {\n console.log(\"The string does not have whitespace\");\n}"
},
{
"code": null,
"e": 1506,
"s": 1440,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1524,
"s": 1506,
"text": "node fileName.js."
},
{
"code": null,
"e": 1558,
"s": 1524,
"text": "Here, my file name is demo108.js."
},
{
"code": null,
"e": 1599,
"s": 1558,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1675,
"s": 1599,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo108.js\nThe string has whitespace"
}
] |
AI and Real State: Predicting Rental Prices in Amsterdam | Towards Data Science | Renting or buying a new house, whether you are a university student or a middle-class family, is always a daunting process that often seems impulsive or risky (a true economic market for lemons).
If the renting itself is already hard, doing it in Amsterdam doesn’t make it any easier. With increasing city regulations, long waitlists for student housing and overpopulation, renting an apartment in Amsterdam leaves many desperate for the first opportunity available, becoming vulnerable to scams and overpriced contracts.
In this tutorial, I will go through an entire Data Science project for the rental market of Amsterdam, from the basics of gathering data, data cleaning, visualization, up until using machine-learning and hyperparameter tuning to develop valuation models for the city’s houses. There are also a lot of discussions about interesting machine learning topics along the way, such as the curse of dimensionality and multicollinearity. Feel free to adapt the code and apply the project in your city to understand a bit more of where you stand as a renter/buyer!
The actual statistical methods you employ in your analysis should be your value-judgment and I will link deeper explanations to all the methods I apply, so make sure you check them out!
With (high-quality) data, it’s the more, the merrier. Machine-learning is a special field of statistics where we apply computer algorithms to very very large datasets. After you have established the questions you want answered (should I rent? should I buy? should I move to another city?) you can start looking for websites that will contain the data that you need to answer them.
In my case, I wanted to find a good-value apartment in Amsterdam. Therefore, I searched for rental websites in the city of Amsterdam. Simple right? However, always check their terms of service and robots.txt to make sure that you are allowed to scrape their data respectfully. (we will talk about what this means later on in the tutorial). For this project, I will use the Amsterdam rental website Pararius.
Find the listing page you want to get your data from. Click inspect to learn more about how data is structured in their website. Once you click, the sidebar will show the HTML storage where the data is located. In the following example, the data I need is mainly inside the box <li class=search-list__item search-list__item — listing> this means that I will refer to this data using this information later in the code. At this moment, we don’t need to specify if we want price, location, zipcodes...we only want to know the “box” where all this data is.
Now, we are going to get started with the coding! As with any web-scraping, we will be starting with making requests to the website we chose previously so that they can provide us with the data we want.
We should keep in mind that making a request to a website is similar to refreshing our browser on that specific page: it adds traffic to their servers and may overwhelm them if done in robot high rates! I added random sleep times to the code so the script will stop a few seconds before scraping more pages.
If you are particularly interested in how requests and headers work, you can also make your requests with fully randomised headers. This will not be necessary for most websites (and should not break their TOS) but if you would like to add security and anonymity into your code, this is my solution for (as much as possible) anonymous headers:
After scraping all the desired pages, you can run:
len(houses)
to find out exactly how many house ads were collected in total. Because we are training a model with this data later on, you should aim for at least 1000 housing ads.
After you have gathered all the data, you should do a few print commands to make sure that everything worked out:
print(response) will print if the request was successful (i.e. we were not blocked by the website)
len(houses) will print how many house ads you successfully scraped
print(house_data[1]) will print the second ad block you scraped in HTML format. I always prefer to look at the second one because the first might contain headers and confusing bits for the next part of our analysis: the data cleaning.
When I execute print(house_data[1]) I get this in my Jupyter Lab:
Ok, don’t run away from this tutorial just yet. What you’re seeing here is the beautiful HTML script that was scraped from your listing website! Look further down into it:
We can actually recognise a few things there! The apartment in this ad block seems to be located at 1078 RA Amsterdam, it costs 1500 euros a month and is 60m2! For the data cleaning, we need to find this information in the soup of HTML and write down where they are located (just like we did earlier with the website!)
For example: to get the price, your need to search for <span class =listing-search-item__price> and to get the location you need: <div class =listing-search-item__location>. You should do the same with all the information that you need for your analysis. However, just looking for the HTML tag and class can return more information than you’d like. Make sure to try adding [0], [1],[2], ...to test which parameter will give you exactly the line you are looking for.
A lot of times, even after finding the right line, there will be extra characters that you want to clean out of the data frame, such as letters in the rent price, or whitespaces in the postcode. Check out the amazing regex tester (https://regex101.com/) to know how to str.replace() your problem away. A few examples:
to delete non-digit characters:
df["column name"].str.replace("\d","")
to delete digit characters:
df["column name"].str.replace("\D","")
to delete the word “new” :
df["column name"].str.replace("new","")
This is how our data frame looks like after cleaning:
It is not only important to have the data, but also know how to use it. What is important for tenants? What can make the difference in rental prices? Depending on the data you scraped earlier, these variables might be available to you:
Surface Size
Number of Bedrooms
If the apartment comes furnished (binary)
If the price is inclusive of utility bills (binary)
Distance to City Center
Trendiness of the neighbourhood
Rental Agency (binary)
Temporary vs. Long term contracts. (binary)
On this tutorial, we will focus on how measure these variables. I won’t be able to use furniture, utility bills or length of contracts for this analysis as that data is not available from the website I am using, but if those are available to you I highly recommend including them.
Location, location, location. Does the location of apartments really matter that much when renting a house? Many people in Amsterdam would agree, as driving cars is impractical in the charming medieval streets, public transport is not very affordable and biking under windy rain just sucks.
But how do you differentiate that effect on rental prices? Geolocation! In this tutorial, we will use Nominatim. We will use this to get the coordinates of every apartment in our dataset and later compare them with a (desirable) point in the city.
Here’s the code:
The idea here is to get a latitude and longitude for each address in your data frame, so we can calculate the distances as precisely as possible. This is what you should end up with:
It should be noted that the columns point, location, and altitude will be deleted. Point is only needed to obtain the latitude and longitude points and altitude is not needed since we are researching houses in The Netherlands!(but would be an interesting factor to take into account if you live in Switzerland, for example).
Let’s calculate the distance: by now, you should have chosen a point in your city to calculate the distance between the apartments and this specific point. For Amsterdam, I chose the Amsterdam Centraal station with the following coordinates (centre point):
After choosing my point and getting its coordinates (on Nominatim as well), you will create two columns with the latitude (52.370216) and the longitude (4.895168) of that point.
If you are analysing a bigger city that has multiple locations that are considered desirable, you can also run this code as many times as needed with different geographical points. (Don’t forget to change the column names so you don’t overwrite the previous point!).
For example, there is a financial district close to the Amsterdam Zuid station that could be equally (or even more) relevant to working tenants than living close to the city center. Measuring these various scenarios is more important if you are using methods similar to multiple linear regressions rather than machine-learning statistical algorithms because they are inherently better at recognising non-linear relationships and clusters. For this reason, I won’t include it in this analysis but it is an interesting factor to weight in depending on the statistical method being used.
Now that we have the geolocations of all the apartments in our dataset, we can further visualize how their rental prices are placed geographically and spot any trends that might be relevant for our analysis. We will do this with Google Maps, with the package gmaps for Jupyter:
conda install gmaps ## to install the google maps package
You will also need a Google Maps API key that is easily requested (and free for most purposes). You can click here to request it.
With the simple code below, we can request an interactive google maps on a Jupyter Notebook (sometimes it does not work correctly with JupyterLab), and output a heat map layer that will tell us where the highest rents of the city are.
We should get this beautiful geographical representation of rental prices in Amsterdam:
Analysis of the heat map: As expected, most of the higher rent prices are concentrated around the city center, specifically De Wallen, and also around the outer neighbourhoods such De Pijp and around the city park, Vondelpark, where there is a concentration of luxury houses. The further out neighbourhoods of Nieuw-West, Zuidoost, Ijburg and Noord appear to have lower rental prices represented in green. Location seems to have a strong effect on rental prices, but it is definitely not the sole factor.
For more examples and tutorials on gmaps click here.
We should also take a look on how the variables in our data frame relate to house prices. This is the code to check the relationship between house prices and surface area:
import matplotlib.pyplot as pltplt.figure()plt.scatter(amsmodel1['surface'],amsmodel1['house_price'], s=20, edgecolor="black",c="darkorange", label="surface")plt.xlabel("Surface Area")plt.ylabel("House Price")plt.title("Surface Area vs. House Price")plt.legend()plt.show()
When it comes to the surface area of the apartment, there is a very clear upwards sloping trend relationship between the two! However it should be noted that:
As the house gets bigger, the marginal price of an additional square meter decreases dramatically. Thus, almost always going for a bigger house (if you can afford it) will actually get you more bang for your buck.
This is code to check the relationship between house prices and number of bedrooms:
import matplotlib.pyplot as pltplt.figure()plt.scatter(amsmodel1['bedrooms'],amsmodel1['house_price'], s=20, edgecolor="black",c="darkorange", label="bedrooms")plt.xlabel("Bedrooms")plt.ylabel("House Price")plt.title("Bedrooms vs. House Price")plt.legend()plt.show()
In a somewhat similar conclusion to the surface area, the more bedrooms a house has, the higher the rental price should be. However, that is also not the only factor as there are 5-room apartments going for as little as $3000 a month and as high as $10000.
If you look into your data frame now, you will notice a lot of columns that were “step” columns in order to get more information about the houses. We can delete all these columns as we will not be using them anymore.
del df5['address']del df5['address2']del df5['altitude']del df5['latitude']del df5['longitude']del df5['point']del df5['lat2']del df5['lon2']del df5['coord1']del df5['coord2']del df5['location']
If we were running multiple linear regressions (or variants of one), we would have to check for independent variables with high correlations with each other. One way we can do this is through a correlation matrix:
As we can see in the correlation matrix below, there are two independent variables that show some multicollinearity (r > 0.7) : bedrooms and surface area. This makes sense since the bigger a house is, the more bedrooms it will usually have.
One way to solve this issue is to combine the two variables into one, such as creating a new variable for the square space per bedroom:
amsmodel1['surface_per_bedroom'] = amsmodel1['surface']/amsmodel1['bedrooms']
After deleting both surface and bedrooms variables, this is what our correlation matrix looks like:
This process eliminated multicollinearity from the dataset successfully. However, for most machine-learning algorithms, we never need to check for high correlations between variables — multicollinearity does not affect the accuracy of machine learning models, especially ensemble learning models such as the random forest algorithm.
At every point of the decision tree, the algorithm will make the best split that will predict the target variable more accurately, regardless of how the independent variables correlate with other. Additionally, for regression models the purpose is to understand the effect of a specific variable, whereas in machine learning, we are much more interested in the predictive power of the model. If you would like to read more on this, here is a great discussion on the subject: https://stats.stackexchange.com/questions/168622/why-is-multicollinearity-not-checked-in-modern-statistics-machine-learning
In every large city, a few neighbourhoods seem to be very popular (and thus have exceptionally high rents) even though they are not close to the city center, or necessarily populated by bigger apartments. An example that can be found in our Google Maps heat map would be De Pijp, that is outside the Amsterdam ring and mainly offers small and non-renovated apartments, but has a higher rents average than the apartments on the right side of the Centraal Station.
How do we measure the effect of popularity in a quantitative way?
One way is by using Yelp! Popular neighbourhoods tend to have popular bars and restaurants, with high ratings and potentially also high prices. Most people that pay higher rents to live in De Pijp justify it with:
“that’s where the life of the city is!”
“that’s where all the cool bars and restaurants are”.
Yelp can help us by giving us hundreds of restaurants and telling us exactly how well-rated they are and how much they cost in a standardised and easily quantifiable way: $ are cheap eats, $$ and $$$ are in the middle, and $$$$ are expensive. Furthermore, this also helps us understand the neighbourhoods that may not be popular at the moment, but are traditionally richer areas (with a lot of $$$$ restaurants) that consequently charge higher rents.
You will need to register for the Yelp API, and replace my api_key with yours, and also replace location with the city you are analysing. It is also possible to build a second outer loop to get data from different cities. If you have a data frame with the column city, you can transform that column into a list and iterate the requests over that list!
After gathering the data from Yelp, we need to match that with the rental data that we already have. Here’s how to do it:
After mapping the yelp data into our data frame, dropping any empty rows and checking how many columns we have, this is how the data frame looks like:
Now that we have a dataset with more information on yelp prices and ratings, we can visualize their relationships with house prices to understand whether this metric will likely improve our model or not.
The following code scatter plot yelp ratings against house prices:
import matplotlib.pyplot as pltplt.figure()plt.scatter(amsmodel1['yelp_ratings'],amsmodel1['house_price'], s=20, edgecolor="black",c="darkorange", label = "yelp")plt.xlabel("Yelp Ratings")plt.ylabel("House Price")plt.title("Yelp Ratings vs. House Price")plt.legend()plt.show()
The following code scatter plot yelp prices against house prices:
import matplotlib.pyplot as pltplt.figure()plt.scatter(amsmodel1['yelp_prices'],amsmodel1['house_price'], s=20, edgecolor="black",c="darkorange", label="yelp")plt.xlabel("Yelp Prices")plt.ylabel("House Price")plt.title("Yelp Prices vs. House Price")plt.legend()plt.show()
There definitely does not seem to be a strong linear relationship here when inspecting only the relationship between the two variables. Hopefully, we will be able to judge with the machine-learning algorithm if adding these variables have a resulting effect, albeit more complex that linear, on house prices after all.
Are we finally ready for to train the model? Nope. Our model will only take values in integer type, and right now we have a few columns that are categorical (or in other words, don’t make sense numerically but as categories for our apartments). We need to create something called dummy variables to represent these categories in a way that the computer can understand numerically.
Here’s a quick (but great) explanation about dummy variables and what they do: https://medium.com/@brian.collins0409/dummy-variables-done-right-588f58596aea
Here’s the code:
Now we have a staggering amount of 327 columns! In data science projects, we should criticise every step of our analysis to prevent bias and other misinterpretations. With data frames with high-dimensionality, we need to consider the curse of dimensionality which can confuse machine-learning methods due to the points being so far apart that they all look the same (and thus no conclusion/differentiation can really be made from the analysis). If our dataset suffers from this problem, it could decrease our accuracy results in the random forest algorithm.
The most accepted rule of thumb is that we should have at least 5 training data points for every feature in our dataset. In this project, we have:
training data set = 3376*80% ration training points/features = 2700.8/327 = 8.26
which (fortunately) passes our 5 training data to feature ratio rule!
At this point, our data frame should be looking like this:
We have 3376 rows, 327 columns, and data about the house prices, number of bedrooms, surface area, distance from the city center, mean yelp prices and ratings of their areas, dummy variables for postcodes and dummy variables for rental agencies.
The Random Forest algorithm is an ensemble learning method that builds decision trees, splitting the data and testing each decision to understand the weight of each feature, hopefully achieving the true effects of the features of dataset against the target (in this case, the house prices). Here is a great article about this algorithm.
With random forest, I will also combine the K-Fold (with K = 10) Cross Validation approach, which means we will be slicing the data into ten parts, training 9 parts and testing it against the 10th part, and using a different slice of that ten-piece pie as the testing data in each iteration, maximising the size of our dataset to obtain better results. More about Cross Validation here.
For this project, I will be using the open source package sklearn to apply the algorithm to the dataset. Here’s the code:
After a few minutes, you should start getting a few results. These are the results I got for this dataset:
An average accuracy of 94.75% is not bad, but would it be possible to increase the efficacy of the model? We can try different Hyperparameter Tuning settings to possibly increase the accuracy rate by a few percentage points:
This part of the article is heavily based on this article: Hyperparameter Tuning the Random Forest in Python, you should definitely check it out for a deeper understanding of the code.
Sklearn has the great feature RandomizedSearchCV that tests different parameters and recommends which parameters are likely to maximize the accuracy results of the model.
The code first specifies what are the choices for each parameter that should be tested by the feature:
And we fit the Random Forest Regressor into the RandomizedSearchCV, and it searches across 100 combinations 3 times, and returns the best parameters.
These are the results for the best parameters we get for this model:
{'n_estimators': 400, 'min_samples_split': 2, 'min_samples_leaf': 1, 'max_features': 'sqrt', 'max_depth': None, 'bootstrap': False}
We go back to the original code and include these parameters:
Increasing our accuracy rates to 98.30%!
If you open the image tree.png, you should get something like this:
This is the graph representing all of the random forest’s algorithm decisions, including splits, branches, leaves, mean standard errors, number of samples and predicted values for each split. It’s not extremely useful (or time-efficient) to look through each tree split, but it very interesting to look at a few and see if they make sense to you.
The feature importance bar plot is an sklearn option that is a bit more efficient in understanding the algorithm’s findings. First, we define that we would like to see only the features that determine more than 0.5% of our prediction results, and we will also create a list of these features.
The list_of_index will return a list with the arrays of the column numbers that are the most important. Transforming the list correctly proved be a bit challenging due to the format of the output, so I just redefined the list with the corresponding correct columns.
list_of_index = [0,1,2,3,4,24,97,249,280,308]
Next we need to get the columns and column labels:
And finally this is code for the matplotlib bar plot:
This is the resulting graph:
Analysis of the Feature Importance graph: Contrary to popular belief, location (represented by the variable dist) is the second most important effect. Surface area, instead, is by far the most important factor into determining rental prices in Amsterdam. The number of bedrooms, yelp ratings, yelp prices and a few rental agencies also place a significant effect. Living in the specific postcode 1071 (which indeed is a luxurious postcode to have in Amsterdam, considering it is the neighbourhood of many celebrities) can add a significant amount to your rental bill, everything else being equal.
What if we analyse rental price of houses per square meter, instead of absolute prices? By adding the following code to the process immediately before the algorithm:
and running the Random Forest again, we obtain the following results:
With an average accuracy of 98.309%, measuring the price by square meter increases the model’s accuracy rate slightly from the 98.30% we obtained earlier. The feature list also changes:
It still features surface area and location as primary factors in determining the rental price, but decrease their relative importances and increase the relative importance of yelp ratings and prices, while also adding more rental agencies to the list of agencies that can influence (positively or negatively) the rental price of an Amsterdam home, everything else being equal.
We have the model, and we understand how it works. However, we already know the prices of the listed apartments and we have a fairly good idea about whether it is worth the price tag or not. How can this project be useful to someone who already knows the real state market in Amsterdam?
The true beauty of the model lies on its prediction power. While a real state developer may intuitively know the ballpark of how much an apartment should be worth, we now also have a quantitative tool that can analyse a sample of the market and output a precise price that could bring the expertise of a real state landlord or long-time Amsterdam resident to new renters and buyers.
Here’s how to make predictions with the trained model:
The prediction above is for an apartment with 1 bedroom, 45 sq. meters, that has the postcode 1018 and is being rented from the real state agency JLG Real Estate. We can query the yelp_prices and yelp_ratings data frames from the corresponding postcode 1018 to specify them in the prediction.
For this specific apartment, the predicted rental price is $1530, which is extremely close to the real rent price being paid for the apartment ($1538), even though the model has never this data point, and the apartment has not been listed for more than a year.
This project showed me that understanding the real state market in Amsterdam is definitely more complex than simply looking at postcodes and the square meterage of the apartment. Although these two features are the most important, you can easily be paying more money for the same apartment just because you used an specific rental agency, decided to live in a neighbourhood with good restaurants, or wanted to be neighbours with celebrities (ok, that one is not that shocking).
Hopefully, I have been able to shed a bit more light into the inner workings of this market and help a few people predict how much they should be paying for their new homes. Thank you for reading!
Webscraping Algorithm: https://towardsdatascience.com/looking-for-a-house-build-a-web-scraper-to-help-you-5ab25badc83e
Random Forest Visualization: https://towardsdatascience.com/how-to-visualize-a-decision-tree-from-a-random-forest-in-python-using-scikit-learn-38ad2d75f21c
Hyperparameter Tuning: https://towardsdatascience.com/hyperparameter-tuning-the-random-forest-in-python-using-scikit-learn-28d2aa77dd74 | [
{
"code": null,
"e": 368,
"s": 172,
"text": "Renting or buying a new house, whether you are a university student or a middle-class family, is always a daunting process that often seems impulsive or risky (a true economic market for lemons)."
},
{
"code": null,
"e": 694,
"s": 368,
"text": "If the renting itself is already hard, doing it in Amsterdam doesn’t make it any easier. With increasing city regulations, long waitlists for student housing and overpopulation, renting an apartment in Amsterdam leaves many desperate for the first opportunity available, becoming vulnerable to scams and overpriced contracts."
},
{
"code": null,
"e": 1249,
"s": 694,
"text": "In this tutorial, I will go through an entire Data Science project for the rental market of Amsterdam, from the basics of gathering data, data cleaning, visualization, up until using machine-learning and hyperparameter tuning to develop valuation models for the city’s houses. There are also a lot of discussions about interesting machine learning topics along the way, such as the curse of dimensionality and multicollinearity. Feel free to adapt the code and apply the project in your city to understand a bit more of where you stand as a renter/buyer!"
},
{
"code": null,
"e": 1435,
"s": 1249,
"text": "The actual statistical methods you employ in your analysis should be your value-judgment and I will link deeper explanations to all the methods I apply, so make sure you check them out!"
},
{
"code": null,
"e": 1816,
"s": 1435,
"text": "With (high-quality) data, it’s the more, the merrier. Machine-learning is a special field of statistics where we apply computer algorithms to very very large datasets. After you have established the questions you want answered (should I rent? should I buy? should I move to another city?) you can start looking for websites that will contain the data that you need to answer them."
},
{
"code": null,
"e": 2224,
"s": 1816,
"text": "In my case, I wanted to find a good-value apartment in Amsterdam. Therefore, I searched for rental websites in the city of Amsterdam. Simple right? However, always check their terms of service and robots.txt to make sure that you are allowed to scrape their data respectfully. (we will talk about what this means later on in the tutorial). For this project, I will use the Amsterdam rental website Pararius."
},
{
"code": null,
"e": 2778,
"s": 2224,
"text": "Find the listing page you want to get your data from. Click inspect to learn more about how data is structured in their website. Once you click, the sidebar will show the HTML storage where the data is located. In the following example, the data I need is mainly inside the box <li class=search-list__item search-list__item — listing> this means that I will refer to this data using this information later in the code. At this moment, we don’t need to specify if we want price, location, zipcodes...we only want to know the “box” where all this data is."
},
{
"code": null,
"e": 2981,
"s": 2778,
"text": "Now, we are going to get started with the coding! As with any web-scraping, we will be starting with making requests to the website we chose previously so that they can provide us with the data we want."
},
{
"code": null,
"e": 3289,
"s": 2981,
"text": "We should keep in mind that making a request to a website is similar to refreshing our browser on that specific page: it adds traffic to their servers and may overwhelm them if done in robot high rates! I added random sleep times to the code so the script will stop a few seconds before scraping more pages."
},
{
"code": null,
"e": 3632,
"s": 3289,
"text": "If you are particularly interested in how requests and headers work, you can also make your requests with fully randomised headers. This will not be necessary for most websites (and should not break their TOS) but if you would like to add security and anonymity into your code, this is my solution for (as much as possible) anonymous headers:"
},
{
"code": null,
"e": 3683,
"s": 3632,
"text": "After scraping all the desired pages, you can run:"
},
{
"code": null,
"e": 3695,
"s": 3683,
"text": "len(houses)"
},
{
"code": null,
"e": 3862,
"s": 3695,
"text": "to find out exactly how many house ads were collected in total. Because we are training a model with this data later on, you should aim for at least 1000 housing ads."
},
{
"code": null,
"e": 3976,
"s": 3862,
"text": "After you have gathered all the data, you should do a few print commands to make sure that everything worked out:"
},
{
"code": null,
"e": 4075,
"s": 3976,
"text": "print(response) will print if the request was successful (i.e. we were not blocked by the website)"
},
{
"code": null,
"e": 4142,
"s": 4075,
"text": "len(houses) will print how many house ads you successfully scraped"
},
{
"code": null,
"e": 4377,
"s": 4142,
"text": "print(house_data[1]) will print the second ad block you scraped in HTML format. I always prefer to look at the second one because the first might contain headers and confusing bits for the next part of our analysis: the data cleaning."
},
{
"code": null,
"e": 4443,
"s": 4377,
"text": "When I execute print(house_data[1]) I get this in my Jupyter Lab:"
},
{
"code": null,
"e": 4615,
"s": 4443,
"text": "Ok, don’t run away from this tutorial just yet. What you’re seeing here is the beautiful HTML script that was scraped from your listing website! Look further down into it:"
},
{
"code": null,
"e": 4934,
"s": 4615,
"text": "We can actually recognise a few things there! The apartment in this ad block seems to be located at 1078 RA Amsterdam, it costs 1500 euros a month and is 60m2! For the data cleaning, we need to find this information in the soup of HTML and write down where they are located (just like we did earlier with the website!)"
},
{
"code": null,
"e": 5400,
"s": 4934,
"text": "For example: to get the price, your need to search for <span class =listing-search-item__price> and to get the location you need: <div class =listing-search-item__location>. You should do the same with all the information that you need for your analysis. However, just looking for the HTML tag and class can return more information than you’d like. Make sure to try adding [0], [1],[2], ...to test which parameter will give you exactly the line you are looking for."
},
{
"code": null,
"e": 5718,
"s": 5400,
"text": "A lot of times, even after finding the right line, there will be extra characters that you want to clean out of the data frame, such as letters in the rent price, or whitespaces in the postcode. Check out the amazing regex tester (https://regex101.com/) to know how to str.replace() your problem away. A few examples:"
},
{
"code": null,
"e": 5750,
"s": 5718,
"text": "to delete non-digit characters:"
},
{
"code": null,
"e": 5789,
"s": 5750,
"text": "df[\"column name\"].str.replace(\"\\d\",\"\")"
},
{
"code": null,
"e": 5817,
"s": 5789,
"text": "to delete digit characters:"
},
{
"code": null,
"e": 5856,
"s": 5817,
"text": "df[\"column name\"].str.replace(\"\\D\",\"\")"
},
{
"code": null,
"e": 5883,
"s": 5856,
"text": "to delete the word “new” :"
},
{
"code": null,
"e": 5923,
"s": 5883,
"text": "df[\"column name\"].str.replace(\"new\",\"\")"
},
{
"code": null,
"e": 5977,
"s": 5923,
"text": "This is how our data frame looks like after cleaning:"
},
{
"code": null,
"e": 6213,
"s": 5977,
"text": "It is not only important to have the data, but also know how to use it. What is important for tenants? What can make the difference in rental prices? Depending on the data you scraped earlier, these variables might be available to you:"
},
{
"code": null,
"e": 6226,
"s": 6213,
"text": "Surface Size"
},
{
"code": null,
"e": 6245,
"s": 6226,
"text": "Number of Bedrooms"
},
{
"code": null,
"e": 6287,
"s": 6245,
"text": "If the apartment comes furnished (binary)"
},
{
"code": null,
"e": 6339,
"s": 6287,
"text": "If the price is inclusive of utility bills (binary)"
},
{
"code": null,
"e": 6363,
"s": 6339,
"text": "Distance to City Center"
},
{
"code": null,
"e": 6395,
"s": 6363,
"text": "Trendiness of the neighbourhood"
},
{
"code": null,
"e": 6418,
"s": 6395,
"text": "Rental Agency (binary)"
},
{
"code": null,
"e": 6462,
"s": 6418,
"text": "Temporary vs. Long term contracts. (binary)"
},
{
"code": null,
"e": 6743,
"s": 6462,
"text": "On this tutorial, we will focus on how measure these variables. I won’t be able to use furniture, utility bills or length of contracts for this analysis as that data is not available from the website I am using, but if those are available to you I highly recommend including them."
},
{
"code": null,
"e": 7034,
"s": 6743,
"text": "Location, location, location. Does the location of apartments really matter that much when renting a house? Many people in Amsterdam would agree, as driving cars is impractical in the charming medieval streets, public transport is not very affordable and biking under windy rain just sucks."
},
{
"code": null,
"e": 7282,
"s": 7034,
"text": "But how do you differentiate that effect on rental prices? Geolocation! In this tutorial, we will use Nominatim. We will use this to get the coordinates of every apartment in our dataset and later compare them with a (desirable) point in the city."
},
{
"code": null,
"e": 7299,
"s": 7282,
"text": "Here’s the code:"
},
{
"code": null,
"e": 7482,
"s": 7299,
"text": "The idea here is to get a latitude and longitude for each address in your data frame, so we can calculate the distances as precisely as possible. This is what you should end up with:"
},
{
"code": null,
"e": 7807,
"s": 7482,
"text": "It should be noted that the columns point, location, and altitude will be deleted. Point is only needed to obtain the latitude and longitude points and altitude is not needed since we are researching houses in The Netherlands!(but would be an interesting factor to take into account if you live in Switzerland, for example)."
},
{
"code": null,
"e": 8064,
"s": 7807,
"text": "Let’s calculate the distance: by now, you should have chosen a point in your city to calculate the distance between the apartments and this specific point. For Amsterdam, I chose the Amsterdam Centraal station with the following coordinates (centre point):"
},
{
"code": null,
"e": 8242,
"s": 8064,
"text": "After choosing my point and getting its coordinates (on Nominatim as well), you will create two columns with the latitude (52.370216) and the longitude (4.895168) of that point."
},
{
"code": null,
"e": 8509,
"s": 8242,
"text": "If you are analysing a bigger city that has multiple locations that are considered desirable, you can also run this code as many times as needed with different geographical points. (Don’t forget to change the column names so you don’t overwrite the previous point!)."
},
{
"code": null,
"e": 9094,
"s": 8509,
"text": "For example, there is a financial district close to the Amsterdam Zuid station that could be equally (or even more) relevant to working tenants than living close to the city center. Measuring these various scenarios is more important if you are using methods similar to multiple linear regressions rather than machine-learning statistical algorithms because they are inherently better at recognising non-linear relationships and clusters. For this reason, I won’t include it in this analysis but it is an interesting factor to weight in depending on the statistical method being used."
},
{
"code": null,
"e": 9372,
"s": 9094,
"text": "Now that we have the geolocations of all the apartments in our dataset, we can further visualize how their rental prices are placed geographically and spot any trends that might be relevant for our analysis. We will do this with Google Maps, with the package gmaps for Jupyter:"
},
{
"code": null,
"e": 9430,
"s": 9372,
"text": "conda install gmaps ## to install the google maps package"
},
{
"code": null,
"e": 9560,
"s": 9430,
"text": "You will also need a Google Maps API key that is easily requested (and free for most purposes). You can click here to request it."
},
{
"code": null,
"e": 9795,
"s": 9560,
"text": "With the simple code below, we can request an interactive google maps on a Jupyter Notebook (sometimes it does not work correctly with JupyterLab), and output a heat map layer that will tell us where the highest rents of the city are."
},
{
"code": null,
"e": 9883,
"s": 9795,
"text": "We should get this beautiful geographical representation of rental prices in Amsterdam:"
},
{
"code": null,
"e": 10388,
"s": 9883,
"text": "Analysis of the heat map: As expected, most of the higher rent prices are concentrated around the city center, specifically De Wallen, and also around the outer neighbourhoods such De Pijp and around the city park, Vondelpark, where there is a concentration of luxury houses. The further out neighbourhoods of Nieuw-West, Zuidoost, Ijburg and Noord appear to have lower rental prices represented in green. Location seems to have a strong effect on rental prices, but it is definitely not the sole factor."
},
{
"code": null,
"e": 10441,
"s": 10388,
"text": "For more examples and tutorials on gmaps click here."
},
{
"code": null,
"e": 10613,
"s": 10441,
"text": "We should also take a look on how the variables in our data frame relate to house prices. This is the code to check the relationship between house prices and surface area:"
},
{
"code": null,
"e": 10886,
"s": 10613,
"text": "import matplotlib.pyplot as pltplt.figure()plt.scatter(amsmodel1['surface'],amsmodel1['house_price'], s=20, edgecolor=\"black\",c=\"darkorange\", label=\"surface\")plt.xlabel(\"Surface Area\")plt.ylabel(\"House Price\")plt.title(\"Surface Area vs. House Price\")plt.legend()plt.show()"
},
{
"code": null,
"e": 11045,
"s": 10886,
"text": "When it comes to the surface area of the apartment, there is a very clear upwards sloping trend relationship between the two! However it should be noted that:"
},
{
"code": null,
"e": 11259,
"s": 11045,
"text": "As the house gets bigger, the marginal price of an additional square meter decreases dramatically. Thus, almost always going for a bigger house (if you can afford it) will actually get you more bang for your buck."
},
{
"code": null,
"e": 11343,
"s": 11259,
"text": "This is code to check the relationship between house prices and number of bedrooms:"
},
{
"code": null,
"e": 11610,
"s": 11343,
"text": "import matplotlib.pyplot as pltplt.figure()plt.scatter(amsmodel1['bedrooms'],amsmodel1['house_price'], s=20, edgecolor=\"black\",c=\"darkorange\", label=\"bedrooms\")plt.xlabel(\"Bedrooms\")plt.ylabel(\"House Price\")plt.title(\"Bedrooms vs. House Price\")plt.legend()plt.show()"
},
{
"code": null,
"e": 11867,
"s": 11610,
"text": "In a somewhat similar conclusion to the surface area, the more bedrooms a house has, the higher the rental price should be. However, that is also not the only factor as there are 5-room apartments going for as little as $3000 a month and as high as $10000."
},
{
"code": null,
"e": 12084,
"s": 11867,
"text": "If you look into your data frame now, you will notice a lot of columns that were “step” columns in order to get more information about the houses. We can delete all these columns as we will not be using them anymore."
},
{
"code": null,
"e": 12279,
"s": 12084,
"text": "del df5['address']del df5['address2']del df5['altitude']del df5['latitude']del df5['longitude']del df5['point']del df5['lat2']del df5['lon2']del df5['coord1']del df5['coord2']del df5['location']"
},
{
"code": null,
"e": 12493,
"s": 12279,
"text": "If we were running multiple linear regressions (or variants of one), we would have to check for independent variables with high correlations with each other. One way we can do this is through a correlation matrix:"
},
{
"code": null,
"e": 12734,
"s": 12493,
"text": "As we can see in the correlation matrix below, there are two independent variables that show some multicollinearity (r > 0.7) : bedrooms and surface area. This makes sense since the bigger a house is, the more bedrooms it will usually have."
},
{
"code": null,
"e": 12870,
"s": 12734,
"text": "One way to solve this issue is to combine the two variables into one, such as creating a new variable for the square space per bedroom:"
},
{
"code": null,
"e": 12948,
"s": 12870,
"text": "amsmodel1['surface_per_bedroom'] = amsmodel1['surface']/amsmodel1['bedrooms']"
},
{
"code": null,
"e": 13048,
"s": 12948,
"text": "After deleting both surface and bedrooms variables, this is what our correlation matrix looks like:"
},
{
"code": null,
"e": 13381,
"s": 13048,
"text": "This process eliminated multicollinearity from the dataset successfully. However, for most machine-learning algorithms, we never need to check for high correlations between variables — multicollinearity does not affect the accuracy of machine learning models, especially ensemble learning models such as the random forest algorithm."
},
{
"code": null,
"e": 13980,
"s": 13381,
"text": "At every point of the decision tree, the algorithm will make the best split that will predict the target variable more accurately, regardless of how the independent variables correlate with other. Additionally, for regression models the purpose is to understand the effect of a specific variable, whereas in machine learning, we are much more interested in the predictive power of the model. If you would like to read more on this, here is a great discussion on the subject: https://stats.stackexchange.com/questions/168622/why-is-multicollinearity-not-checked-in-modern-statistics-machine-learning"
},
{
"code": null,
"e": 14443,
"s": 13980,
"text": "In every large city, a few neighbourhoods seem to be very popular (and thus have exceptionally high rents) even though they are not close to the city center, or necessarily populated by bigger apartments. An example that can be found in our Google Maps heat map would be De Pijp, that is outside the Amsterdam ring and mainly offers small and non-renovated apartments, but has a higher rents average than the apartments on the right side of the Centraal Station."
},
{
"code": null,
"e": 14509,
"s": 14443,
"text": "How do we measure the effect of popularity in a quantitative way?"
},
{
"code": null,
"e": 14723,
"s": 14509,
"text": "One way is by using Yelp! Popular neighbourhoods tend to have popular bars and restaurants, with high ratings and potentially also high prices. Most people that pay higher rents to live in De Pijp justify it with:"
},
{
"code": null,
"e": 14763,
"s": 14723,
"text": "“that’s where the life of the city is!”"
},
{
"code": null,
"e": 14817,
"s": 14763,
"text": "“that’s where all the cool bars and restaurants are”."
},
{
"code": null,
"e": 15268,
"s": 14817,
"text": "Yelp can help us by giving us hundreds of restaurants and telling us exactly how well-rated they are and how much they cost in a standardised and easily quantifiable way: $ are cheap eats, $$ and $$$ are in the middle, and $$$$ are expensive. Furthermore, this also helps us understand the neighbourhoods that may not be popular at the moment, but are traditionally richer areas (with a lot of $$$$ restaurants) that consequently charge higher rents."
},
{
"code": null,
"e": 15620,
"s": 15268,
"text": "You will need to register for the Yelp API, and replace my api_key with yours, and also replace location with the city you are analysing. It is also possible to build a second outer loop to get data from different cities. If you have a data frame with the column city, you can transform that column into a list and iterate the requests over that list!"
},
{
"code": null,
"e": 15742,
"s": 15620,
"text": "After gathering the data from Yelp, we need to match that with the rental data that we already have. Here’s how to do it:"
},
{
"code": null,
"e": 15893,
"s": 15742,
"text": "After mapping the yelp data into our data frame, dropping any empty rows and checking how many columns we have, this is how the data frame looks like:"
},
{
"code": null,
"e": 16097,
"s": 15893,
"text": "Now that we have a dataset with more information on yelp prices and ratings, we can visualize their relationships with house prices to understand whether this metric will likely improve our model or not."
},
{
"code": null,
"e": 16164,
"s": 16097,
"text": "The following code scatter plot yelp ratings against house prices:"
},
{
"code": null,
"e": 16441,
"s": 16164,
"text": "import matplotlib.pyplot as pltplt.figure()plt.scatter(amsmodel1['yelp_ratings'],amsmodel1['house_price'], s=20, edgecolor=\"black\",c=\"darkorange\", label = \"yelp\")plt.xlabel(\"Yelp Ratings\")plt.ylabel(\"House Price\")plt.title(\"Yelp Ratings vs. House Price\")plt.legend()plt.show()"
},
{
"code": null,
"e": 16507,
"s": 16441,
"text": "The following code scatter plot yelp prices against house prices:"
},
{
"code": null,
"e": 16779,
"s": 16507,
"text": "import matplotlib.pyplot as pltplt.figure()plt.scatter(amsmodel1['yelp_prices'],amsmodel1['house_price'], s=20, edgecolor=\"black\",c=\"darkorange\", label=\"yelp\")plt.xlabel(\"Yelp Prices\")plt.ylabel(\"House Price\")plt.title(\"Yelp Prices vs. House Price\")plt.legend()plt.show()"
},
{
"code": null,
"e": 17098,
"s": 16779,
"text": "There definitely does not seem to be a strong linear relationship here when inspecting only the relationship between the two variables. Hopefully, we will be able to judge with the machine-learning algorithm if adding these variables have a resulting effect, albeit more complex that linear, on house prices after all."
},
{
"code": null,
"e": 17479,
"s": 17098,
"text": "Are we finally ready for to train the model? Nope. Our model will only take values in integer type, and right now we have a few columns that are categorical (or in other words, don’t make sense numerically but as categories for our apartments). We need to create something called dummy variables to represent these categories in a way that the computer can understand numerically."
},
{
"code": null,
"e": 17636,
"s": 17479,
"text": "Here’s a quick (but great) explanation about dummy variables and what they do: https://medium.com/@brian.collins0409/dummy-variables-done-right-588f58596aea"
},
{
"code": null,
"e": 17653,
"s": 17636,
"text": "Here’s the code:"
},
{
"code": null,
"e": 18211,
"s": 17653,
"text": "Now we have a staggering amount of 327 columns! In data science projects, we should criticise every step of our analysis to prevent bias and other misinterpretations. With data frames with high-dimensionality, we need to consider the curse of dimensionality which can confuse machine-learning methods due to the points being so far apart that they all look the same (and thus no conclusion/differentiation can really be made from the analysis). If our dataset suffers from this problem, it could decrease our accuracy results in the random forest algorithm."
},
{
"code": null,
"e": 18358,
"s": 18211,
"text": "The most accepted rule of thumb is that we should have at least 5 training data points for every feature in our dataset. In this project, we have:"
},
{
"code": null,
"e": 18439,
"s": 18358,
"text": "training data set = 3376*80% ration training points/features = 2700.8/327 = 8.26"
},
{
"code": null,
"e": 18509,
"s": 18439,
"text": "which (fortunately) passes our 5 training data to feature ratio rule!"
},
{
"code": null,
"e": 18568,
"s": 18509,
"text": "At this point, our data frame should be looking like this:"
},
{
"code": null,
"e": 18814,
"s": 18568,
"text": "We have 3376 rows, 327 columns, and data about the house prices, number of bedrooms, surface area, distance from the city center, mean yelp prices and ratings of their areas, dummy variables for postcodes and dummy variables for rental agencies."
},
{
"code": null,
"e": 19151,
"s": 18814,
"text": "The Random Forest algorithm is an ensemble learning method that builds decision trees, splitting the data and testing each decision to understand the weight of each feature, hopefully achieving the true effects of the features of dataset against the target (in this case, the house prices). Here is a great article about this algorithm."
},
{
"code": null,
"e": 19538,
"s": 19151,
"text": "With random forest, I will also combine the K-Fold (with K = 10) Cross Validation approach, which means we will be slicing the data into ten parts, training 9 parts and testing it against the 10th part, and using a different slice of that ten-piece pie as the testing data in each iteration, maximising the size of our dataset to obtain better results. More about Cross Validation here."
},
{
"code": null,
"e": 19660,
"s": 19538,
"text": "For this project, I will be using the open source package sklearn to apply the algorithm to the dataset. Here’s the code:"
},
{
"code": null,
"e": 19767,
"s": 19660,
"text": "After a few minutes, you should start getting a few results. These are the results I got for this dataset:"
},
{
"code": null,
"e": 19992,
"s": 19767,
"text": "An average accuracy of 94.75% is not bad, but would it be possible to increase the efficacy of the model? We can try different Hyperparameter Tuning settings to possibly increase the accuracy rate by a few percentage points:"
},
{
"code": null,
"e": 20177,
"s": 19992,
"text": "This part of the article is heavily based on this article: Hyperparameter Tuning the Random Forest in Python, you should definitely check it out for a deeper understanding of the code."
},
{
"code": null,
"e": 20348,
"s": 20177,
"text": "Sklearn has the great feature RandomizedSearchCV that tests different parameters and recommends which parameters are likely to maximize the accuracy results of the model."
},
{
"code": null,
"e": 20451,
"s": 20348,
"text": "The code first specifies what are the choices for each parameter that should be tested by the feature:"
},
{
"code": null,
"e": 20601,
"s": 20451,
"text": "And we fit the Random Forest Regressor into the RandomizedSearchCV, and it searches across 100 combinations 3 times, and returns the best parameters."
},
{
"code": null,
"e": 20670,
"s": 20601,
"text": "These are the results for the best parameters we get for this model:"
},
{
"code": null,
"e": 20802,
"s": 20670,
"text": "{'n_estimators': 400, 'min_samples_split': 2, 'min_samples_leaf': 1, 'max_features': 'sqrt', 'max_depth': None, 'bootstrap': False}"
},
{
"code": null,
"e": 20864,
"s": 20802,
"text": "We go back to the original code and include these parameters:"
},
{
"code": null,
"e": 20905,
"s": 20864,
"text": "Increasing our accuracy rates to 98.30%!"
},
{
"code": null,
"e": 20973,
"s": 20905,
"text": "If you open the image tree.png, you should get something like this:"
},
{
"code": null,
"e": 21320,
"s": 20973,
"text": "This is the graph representing all of the random forest’s algorithm decisions, including splits, branches, leaves, mean standard errors, number of samples and predicted values for each split. It’s not extremely useful (or time-efficient) to look through each tree split, but it very interesting to look at a few and see if they make sense to you."
},
{
"code": null,
"e": 21613,
"s": 21320,
"text": "The feature importance bar plot is an sklearn option that is a bit more efficient in understanding the algorithm’s findings. First, we define that we would like to see only the features that determine more than 0.5% of our prediction results, and we will also create a list of these features."
},
{
"code": null,
"e": 21879,
"s": 21613,
"text": "The list_of_index will return a list with the arrays of the column numbers that are the most important. Transforming the list correctly proved be a bit challenging due to the format of the output, so I just redefined the list with the corresponding correct columns."
},
{
"code": null,
"e": 21925,
"s": 21879,
"text": "list_of_index = [0,1,2,3,4,24,97,249,280,308]"
},
{
"code": null,
"e": 21976,
"s": 21925,
"text": "Next we need to get the columns and column labels:"
},
{
"code": null,
"e": 22030,
"s": 21976,
"text": "And finally this is code for the matplotlib bar plot:"
},
{
"code": null,
"e": 22059,
"s": 22030,
"text": "This is the resulting graph:"
},
{
"code": null,
"e": 22656,
"s": 22059,
"text": "Analysis of the Feature Importance graph: Contrary to popular belief, location (represented by the variable dist) is the second most important effect. Surface area, instead, is by far the most important factor into determining rental prices in Amsterdam. The number of bedrooms, yelp ratings, yelp prices and a few rental agencies also place a significant effect. Living in the specific postcode 1071 (which indeed is a luxurious postcode to have in Amsterdam, considering it is the neighbourhood of many celebrities) can add a significant amount to your rental bill, everything else being equal."
},
{
"code": null,
"e": 22822,
"s": 22656,
"text": "What if we analyse rental price of houses per square meter, instead of absolute prices? By adding the following code to the process immediately before the algorithm:"
},
{
"code": null,
"e": 22892,
"s": 22822,
"text": "and running the Random Forest again, we obtain the following results:"
},
{
"code": null,
"e": 23078,
"s": 22892,
"text": "With an average accuracy of 98.309%, measuring the price by square meter increases the model’s accuracy rate slightly from the 98.30% we obtained earlier. The feature list also changes:"
},
{
"code": null,
"e": 23456,
"s": 23078,
"text": "It still features surface area and location as primary factors in determining the rental price, but decrease their relative importances and increase the relative importance of yelp ratings and prices, while also adding more rental agencies to the list of agencies that can influence (positively or negatively) the rental price of an Amsterdam home, everything else being equal."
},
{
"code": null,
"e": 23743,
"s": 23456,
"text": "We have the model, and we understand how it works. However, we already know the prices of the listed apartments and we have a fairly good idea about whether it is worth the price tag or not. How can this project be useful to someone who already knows the real state market in Amsterdam?"
},
{
"code": null,
"e": 24126,
"s": 23743,
"text": "The true beauty of the model lies on its prediction power. While a real state developer may intuitively know the ballpark of how much an apartment should be worth, we now also have a quantitative tool that can analyse a sample of the market and output a precise price that could bring the expertise of a real state landlord or long-time Amsterdam resident to new renters and buyers."
},
{
"code": null,
"e": 24181,
"s": 24126,
"text": "Here’s how to make predictions with the trained model:"
},
{
"code": null,
"e": 24474,
"s": 24181,
"text": "The prediction above is for an apartment with 1 bedroom, 45 sq. meters, that has the postcode 1018 and is being rented from the real state agency JLG Real Estate. We can query the yelp_prices and yelp_ratings data frames from the corresponding postcode 1018 to specify them in the prediction."
},
{
"code": null,
"e": 24735,
"s": 24474,
"text": "For this specific apartment, the predicted rental price is $1530, which is extremely close to the real rent price being paid for the apartment ($1538), even though the model has never this data point, and the apartment has not been listed for more than a year."
},
{
"code": null,
"e": 25213,
"s": 24735,
"text": "This project showed me that understanding the real state market in Amsterdam is definitely more complex than simply looking at postcodes and the square meterage of the apartment. Although these two features are the most important, you can easily be paying more money for the same apartment just because you used an specific rental agency, decided to live in a neighbourhood with good restaurants, or wanted to be neighbours with celebrities (ok, that one is not that shocking)."
},
{
"code": null,
"e": 25410,
"s": 25213,
"text": "Hopefully, I have been able to shed a bit more light into the inner workings of this market and help a few people predict how much they should be paying for their new homes. Thank you for reading!"
},
{
"code": null,
"e": 25529,
"s": 25410,
"text": "Webscraping Algorithm: https://towardsdatascience.com/looking-for-a-house-build-a-web-scraper-to-help-you-5ab25badc83e"
},
{
"code": null,
"e": 25685,
"s": 25529,
"text": "Random Forest Visualization: https://towardsdatascience.com/how-to-visualize-a-decision-tree-from-a-random-forest-in-python-using-scikit-learn-38ad2d75f21c"
}
] |
How to perform double click on an element in Selenium? | We can perform double click on elements in Selenium with the help of Actions class. In order to perform the double click action we will use moveToElement() method, then use doubleClick() method. Finally use build().perform() to execute all the steps.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DoubleClick{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/questions/index.php";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// doubleClick() method for double click to an element after moving to
//element to with the moveToElement()
Actions a = new Actions(driver);
a.moveToElement(driver.findElement(By.xpath(“input[@type=’text’]))).
doubleClick().
build().perform();
driver.quit();
}
} | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "We can perform double click on elements in Selenium with the help of Actions class. In order to perform the double click action we will use moveToElement() method, then use doubleClick() method. Finally use build().perform() to execute all the steps."
},
{
"code": null,
"e": 2342,
"s": 1313,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.interactions.Action;\nimport org.openqa.selenium.interactions.Actions;\nimport java.util.concurrent.TimeUnit;\npublic class DoubleClick{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/questions/index.php\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // doubleClick() method for double click to an element after moving to\n //element to with the moveToElement()\n Actions a = new Actions(driver);\n a.moveToElement(driver.findElement(By.xpath(“input[@type=’text’]))).\n doubleClick().\n build().perform();\n driver.quit();\n }\n}"
}
] |
Count the number of elements in a HashSet in Java | To count the number of elements in a HashSet, use the size() method.
Create HashSet −
String strArr[] = { "P", "Q", "R" };
Set s = new HashSet(Arrays.asList(strArr));
Let us now count the number of elements in the above Set −
s.size()
The following is an example to count the number of elements in a HashSet −
Live Demo
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static void main(String[] a) {
String strArr[] = { "P", "Q", "R" };
Set s = new HashSet(Arrays.asList(strArr));
System.out.println("Elements: "+s);
System.out.println("Number of Elements: "+s.size());
}
}
Elements: [P, Q, R]
Number of Elements: 3
Let us see another example −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
hs.add("N");
System.out.println("Elements: "+hs);
System.out.println("Number of Elements: "+hs.size());
}
}
Elements: [A, B, C, D, E, F, K, M, N]
Number of Elements: 9 | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To count the number of elements in a HashSet, use the size() method."
},
{
"code": null,
"e": 1148,
"s": 1131,
"text": "Create HashSet −"
},
{
"code": null,
"e": 1229,
"s": 1148,
"text": "String strArr[] = { \"P\", \"Q\", \"R\" };\nSet s = new HashSet(Arrays.asList(strArr));"
},
{
"code": null,
"e": 1288,
"s": 1229,
"text": "Let us now count the number of elements in the above Set −"
},
{
"code": null,
"e": 1297,
"s": 1288,
"text": "s.size()"
},
{
"code": null,
"e": 1372,
"s": 1297,
"text": "The following is an example to count the number of elements in a HashSet −"
},
{
"code": null,
"e": 1383,
"s": 1372,
"text": " Live Demo"
},
{
"code": null,
"e": 1718,
"s": 1383,
"text": "import java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\npublic class Demo {\n public static void main(String[] a) {\n String strArr[] = { \"P\", \"Q\", \"R\" };\n Set s = new HashSet(Arrays.asList(strArr));\n System.out.println(\"Elements: \"+s);\n System.out.println(\"Number of Elements: \"+s.size());\n }\n}"
},
{
"code": null,
"e": 1760,
"s": 1718,
"text": "Elements: [P, Q, R]\nNumber of Elements: 3"
},
{
"code": null,
"e": 1789,
"s": 1760,
"text": "Let us see another example −"
},
{
"code": null,
"e": 1800,
"s": 1789,
"text": " Live Demo"
},
{
"code": null,
"e": 2264,
"s": 1800,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // create a hash set\n HashSet hs = new HashSet();\n // add elements to the hash set\n hs.add(\"B\");\n hs.add(\"A\");\n hs.add(\"D\");\n hs.add(\"E\");\n hs.add(\"C\");\n hs.add(\"F\");\n hs.add(\"K\");\n hs.add(\"M\");\n hs.add(\"N\");\n System.out.println(\"Elements: \"+hs);\n System.out.println(\"Number of Elements: \"+hs.size());\n }\n}"
},
{
"code": null,
"e": 2324,
"s": 2264,
"text": "Elements: [A, B, C, D, E, F, K, M, N]\nNumber of Elements: 9"
}
] |
Finding the Frobenius Norm of a given matrix - GeeksforGeeks | 06 May, 2021
Given an M * N matrix, the task is to find the Frobenius Norm of the matrix. The Frobenius Norm of a matrix is defined as the square root of the sum of the squares of the elements of the matrix.Example:
Input: mat[][] = {{1, 2}, {3, 4}} Output: 5.47723 sqrt(12 + 22 + 32 + 42) = sqrt(30) = 5.47723Input: mat[][] = {{1, 4, 6}, {7, 9, 10}} Output: 16.8226
Approach: Find the sum of squares of the elements of the matrix and then print the square root of the calculated value.Below is the implementation of the above approach:
CPP
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int row = 2, col = 2; // Function to return the Frobenius// Norm of the given matrixfloat frobeniusNorm(int mat[row][col]){ // To store the sum of squares of the // elements of the given matrix int sumSq = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { sumSq += pow(mat[i][j], 2); } } // Return the square root of // the sum of squares float res = sqrt(sumSq); return res;} // Driver codeint main(){ int mat[row][col] = { { 1, 2 }, { 3, 4 } }; cout << frobeniusNorm(mat); return 0;}
// Java implementation of the approachclass GFG{ final static int row = 2, col = 2; // Function to return the Frobenius // Norm of the given matrix static float frobeniusNorm(int mat[][]) { // To store the sum of squares of the // elements of the given matrix int sumSq = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { sumSq += (int)Math.pow(mat[i][j], 2); } } // Return the square root of // the sum of squares float res = (float)Math.sqrt(sumSq); return res; } // Driver code public static void main (String[] args) { int mat[][] = { { 1, 2 }, { 3, 4 } }; System.out.println(frobeniusNorm(mat)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approachfrom math import sqrtrow = 2col = 2 # Function to return the Frobenius# Norm of the given matrixdef frobeniusNorm(mat): # To store the sum of squares of the # elements of the given matrix sumSq = 0 for i in range(row): for j in range(col): sumSq += pow(mat[i][j], 2) # Return the square root of # the sum of squares res = sqrt(sumSq) return round(res, 5) # Driver code mat = [ [ 1, 2 ], [ 3, 4 ] ] print(frobeniusNorm(mat)) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System; class GFG{ static int row = 2, col = 2; // Function to return the Frobenius // Norm of the given matrix static float frobeniusNorm(int [,]mat) { // To store the sum of squares of the // elements of the given matrix int sumSq = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { sumSq += (int)Math.Pow(mat[i, j], 2); } } // Return the square root of // the sum of squares float res = (float)Math.Sqrt(sumSq); return res; } // Driver code public static void Main () { int [,]mat = { { 1, 2 }, { 3, 4 } }; Console.WriteLine(frobeniusNorm(mat)); }} // This code is contributed by AnkitRai01
<script> // JavaScript implementation of the approach let row = 2, col = 2; // Function to return the Frobenius // Norm of the given matrix function frobeniusNorm(mat) { // To store the sum of squares of the // elements of the given matrix let sumSq = 0; for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { sumSq += parseInt(Math.pow(mat[i][j], 2)); } } // Return the square root of // the sum of squares let res = parseFloat(Math.sqrt(sumSq)); return res; } // Driver code let mat = [[ 1, 2 ], [ 3, 4 ]]; document.write(frobeniusNorm(mat).toFixed(5)); // This code is contributed by sravan kumar </script>
5.47723
mohit kumar 29
ankthon
sravankumar8128
Arrays
C Programs
Matrix
Technical Scripter
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Building Heap from Array
Reversal algorithm for array rotation
Program to find sum of elements in a given array
Strings in C
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses | [
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 25025,
"s": 24820,
"text": "Given an M * N matrix, the task is to find the Frobenius Norm of the matrix. The Frobenius Norm of a matrix is defined as the square root of the sum of the squares of the elements of the matrix.Example: "
},
{
"code": null,
"e": 25178,
"s": 25025,
"text": "Input: mat[][] = {{1, 2}, {3, 4}} Output: 5.47723 sqrt(12 + 22 + 32 + 42) = sqrt(30) = 5.47723Input: mat[][] = {{1, 4, 6}, {7, 9, 10}} Output: 16.8226 "
},
{
"code": null,
"e": 25350,
"s": 25178,
"text": "Approach: Find the sum of squares of the elements of the matrix and then print the square root of the calculated value.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25354,
"s": 25350,
"text": "CPP"
},
{
"code": null,
"e": 25359,
"s": 25354,
"text": "Java"
},
{
"code": null,
"e": 25367,
"s": 25359,
"text": "Python3"
},
{
"code": null,
"e": 25370,
"s": 25367,
"text": "C#"
},
{
"code": null,
"e": 25381,
"s": 25370,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int row = 2, col = 2; // Function to return the Frobenius// Norm of the given matrixfloat frobeniusNorm(int mat[row][col]){ // To store the sum of squares of the // elements of the given matrix int sumSq = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { sumSq += pow(mat[i][j], 2); } } // Return the square root of // the sum of squares float res = sqrt(sumSq); return res;} // Driver codeint main(){ int mat[row][col] = { { 1, 2 }, { 3, 4 } }; cout << frobeniusNorm(mat); return 0;}",
"e": 26037,
"s": 25381,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ final static int row = 2, col = 2; // Function to return the Frobenius // Norm of the given matrix static float frobeniusNorm(int mat[][]) { // To store the sum of squares of the // elements of the given matrix int sumSq = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { sumSq += (int)Math.pow(mat[i][j], 2); } } // Return the square root of // the sum of squares float res = (float)Math.sqrt(sumSq); return res; } // Driver code public static void main (String[] args) { int mat[][] = { { 1, 2 }, { 3, 4 } }; System.out.println(frobeniusNorm(mat)); }} // This code is contributed by AnkitRai01",
"e": 26897,
"s": 26037,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom math import sqrtrow = 2col = 2 # Function to return the Frobenius# Norm of the given matrixdef frobeniusNorm(mat): # To store the sum of squares of the # elements of the given matrix sumSq = 0 for i in range(row): for j in range(col): sumSq += pow(mat[i][j], 2) # Return the square root of # the sum of squares res = sqrt(sumSq) return round(res, 5) # Driver code mat = [ [ 1, 2 ], [ 3, 4 ] ] print(frobeniusNorm(mat)) # This code is contributed by mohit kumar 29",
"e": 27450,
"s": 26897,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int row = 2, col = 2; // Function to return the Frobenius // Norm of the given matrix static float frobeniusNorm(int [,]mat) { // To store the sum of squares of the // elements of the given matrix int sumSq = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { sumSq += (int)Math.Pow(mat[i, j], 2); } } // Return the square root of // the sum of squares float res = (float)Math.Sqrt(sumSq); return res; } // Driver code public static void Main () { int [,]mat = { { 1, 2 }, { 3, 4 } }; Console.WriteLine(frobeniusNorm(mat)); }} // This code is contributed by AnkitRai01",
"e": 28295,
"s": 27450,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach let row = 2, col = 2; // Function to return the Frobenius // Norm of the given matrix function frobeniusNorm(mat) { // To store the sum of squares of the // elements of the given matrix let sumSq = 0; for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { sumSq += parseInt(Math.pow(mat[i][j], 2)); } } // Return the square root of // the sum of squares let res = parseFloat(Math.sqrt(sumSq)); return res; } // Driver code let mat = [[ 1, 2 ], [ 3, 4 ]]; document.write(frobeniusNorm(mat).toFixed(5)); // This code is contributed by sravan kumar </script>",
"e": 29102,
"s": 28295,
"text": null
},
{
"code": null,
"e": 29110,
"s": 29102,
"text": "5.47723"
},
{
"code": null,
"e": 29127,
"s": 29112,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29135,
"s": 29127,
"text": "ankthon"
},
{
"code": null,
"e": 29151,
"s": 29135,
"text": "sravankumar8128"
},
{
"code": null,
"e": 29158,
"s": 29151,
"text": "Arrays"
},
{
"code": null,
"e": 29169,
"s": 29158,
"text": "C Programs"
},
{
"code": null,
"e": 29176,
"s": 29169,
"text": "Matrix"
},
{
"code": null,
"e": 29195,
"s": 29176,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29202,
"s": 29195,
"text": "Arrays"
},
{
"code": null,
"e": 29209,
"s": 29202,
"text": "Matrix"
},
{
"code": null,
"e": 29307,
"s": 29209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29332,
"s": 29307,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 29352,
"s": 29332,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 29377,
"s": 29352,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 29415,
"s": 29377,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 29464,
"s": 29415,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 29477,
"s": 29464,
"text": "Strings in C"
},
{
"code": null,
"e": 29518,
"s": 29477,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 29556,
"s": 29518,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29597,
"s": 29556,
"text": "C Program to read contents of Whole File"
}
] |
How can we set the margin to a JButton in Java? | A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons to a Java Swing application. A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can set a margin to a JButton by using the setMargin() method of JButton class and pass Insets(int top, int left, int bottom, int right) as an argument.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonMarginTest extends JFrame {
private JButton button;
public JButtonMarginTest() {
setTitle("JButtonMargin Test");
setLayout(new BorderLayout());
button = new JButton("JButton Margin");
button.setMargin(new Insets(50, 50, 50, 50));
add(button, BorderLayout.NORTH);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JButtonMarginTest();
}
} | [
{
"code": null,
"e": 1504,
"s": 1062,
"text": "A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons to a Java Swing application. A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can set a margin to a JButton by using the setMargin() method of JButton class and pass Insets(int top, int left, int bottom, int right) as an argument."
},
{
"code": null,
"e": 2114,
"s": 1504,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class JButtonMarginTest extends JFrame {\n private JButton button;\n public JButtonMarginTest() {\n setTitle(\"JButtonMargin Test\");\n setLayout(new BorderLayout());\n button = new JButton(\"JButton Margin\");\n button.setMargin(new Insets(50, 50, 50, 50));\n add(button, BorderLayout.NORTH);\n setSize(400, 400);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JButtonMarginTest();\n }\n}"
}
] |
VueJS - Events | v-on is the attribute added to the DOM elements to listen to the events in VueJS.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<button v-on:click = "displaynumbers">Click ME</button>
<h2> Add Number 100 + 200 = {{total}}</h2>
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
num1: 100,
num2 : 200,
total : ''
},
methods : {
displaynumbers : function(event) {
console.log(event);
return this.total = this.num1+ this.num2;
}
},
});
</script>
</body>
</html>
The following code is used to assign a click event for the DOM element.
<button v-on:click = "displaynumbers">Click ME</button>
There is a shorthand for v-on, which means we can also call the event as follows −
<button @click = "displaynumbers">Click ME</button>
On the click of the button, it will call the method ‘displaynumbers’, which takes in the event and we have consoled the same in the browser as shown above.
We will now check one more event mouseover mouseout.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<div v-bind:style = "styleobj" v-on:mouseover = "changebgcolor" v-on:mouseout = "originalcolor"></div>
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
num1: 100,
num2 : 200,
total : '',
styleobj : {
width:"100px",
height:"100px",
backgroundColor:"red"
}
},
methods : {
changebgcolor : function() {
this.styleobj.backgroundColor = "green";
},
originalcolor : function() {
this.styleobj.backgroundColor = "red";
}
},
});
</script>
</body>
</html>
In the above example, we have created a div with width and height as 100px. It has been given a background color red. On mouseover, we are changing the color to green, and on mouseout we are changing the color back to red.
Hence, during mouseover, a method is called changebgcolor and once we move the mouse out of the div, a method is called originalcolor.
This is done as follows −
<div v-bind:style = "styleobj" v-on:mouseover = "changebgcolor" v-on:mouseout = "originalcolor"></div>
Two events - mouseover and mouseout - is assigned to the div as shown above. We have created a styleobj variable and given the required style to be assigned to the div. The same variable is binded to the div using v-bind:style = ”styleobj”
In changebgcolor, we are changing the color to green using the following code.
changebgcolor : function() {
this.styleobj.backgroundColor = "green";
}
Using the stylobj variable, we are changing the color to green.
Similarly, the following code is used to change it back to the original color.
originalcolor : function() {
this.styleobj.backgroundColor = "red";
}
This is what we see in the browser.
When we mouseover, the color will change to green as shown in the following screenshot.
Vue has event modifiers available on v-on attribute. Following are the modifiers available −
Allows the event to execute only once.
<button v-on:click.once = "buttonclicked">Click Once</button>
We need to add dot operator while calling the modifiers as shown in the syntax above. Let us use it in an example and understand the working of the once modifier.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<button v-on:click.once = "buttonclickedonce" v-bind:style = "styleobj">Click Once</button>
Output:{{clicknum}}
<br/><br/>
<button v-on:click = "buttonclicked" v-bind:style = "styleobj">Click Me</button>
Output:{{clicknum1}}
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
clicknum : 0,
clicknum1 :0,
styleobj: {
backgroundColor: '#2196F3!important',
cursor: 'pointer',
padding: '8px 16px',
verticalAlign: 'middle',
}
},
methods : {
buttonclickedonce : function() {
this.clicknum++;
},
buttonclicked : function() {
this.clicknum1++;
}
}
});
</script>
</body>
</html>
In the above example, we have created two butttons. The button with Click Once label has added the once modifier and the other button is without any modifier. This is the way the buttons are defined.
<button v-on:click.once = "buttonclickedonce" v-bind:style = "styleobj">Click Once</button>
<button v-on:click = "buttonclicked" v-bind:style = "styleobj">Click Me</button>
The first button calls the method “buttonclickedonce” and the second button calls the method “buttonclicked”.
buttonclickedonce : function() {
this.clicknum++;
},
buttonclicked : function() {
this.clicknum1++;
}
There are two variables defined in the clicknum and clicknum1. Both are incremented when the button is clicked. Both the variables are initialized to 0 and the display is seen in the output above.
On the click of the first button, the variable clicknum increments by 1. On the second click, the number is not incremented as the modifier prevents it from executing or performing any action item assigned on the click of the button.
On the click of the second button, the same action is carried out, i.e. the variable is incremented. On every click, the value is incremented and displayed.
Following is the output we get in the browser.
Syntax
<a href = "http://www.google.com" v-on:click.prevent = "clickme">Click Me</a>
Example
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<a href = "http://www.google.com" v-on:click = "clickme" target = "_blank" v-bind:style = "styleobj">Click Me</a>
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
clicknum : 0,
clicknum1 :0,
styleobj: {
color: '#4CAF50',
marginLeft: '20px',
fontSize: '30px'
}
},
methods : {
clickme : function() {
alert("Anchor tag is clicked");
}
}
});
</script>
</body>
</html>
Output
If we click the clickme link, it will send an alert as “Anchor tag is clicked” and it will open the link https://www.google.com in a new tab as shown in the following screenshots.
Now this works as a normal way, i.e. the link opens up as we want. In case we don’t want the link to open up, we need to add a modifier ‘prevent’ to the event as shown in the following code.
<a href = "http://www.google.com" v-on:click.prevent = "clickme" target = "_blank" v-bind:style = "styleobj">Click Me</a>
Once added, if we click on the button, it will send an alert message and will not open the link anymore. The prevent modifier prevents the link from opening and only executes the method assigned to the tag.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<a href = "http://www.google.com" v-on:click.prevent = "clickme" target = "_blank" v-bind:style = "styleobj">Click Me</a>
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
clicknum : 0,
clicknum1 :0,
styleobj: {
color: '#4CAF50',
marginLeft: '20px',
fontSize: '30px'
}
},
methods : {
clickme : function() {
alert("Anchor tag is clicked");
}
}
});
</script>
</body>
</html>
Output
On the click of the link, it will display the alert message and does not open the url anymore.
VueJS offers key modifiers based on which we can control the event handling. Consider we have a textbox and we want the method to be called only when we press Enter. We can do so by adding key modifiers to the events as follows.
<input type = "text" v-on:keyup.enter = "showinputvalue"/>
The key that we want to apply to our event is V-on.eventname.keyname (as shown above)
We can make use of multiple keynames. For example, V-on.keyup.ctrl.enter
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<input type = "text" v-on:keyup.enter = "showinputvalue" v-bind:style = "styleobj" placeholder = "Enter your name"/>
<h3> {{name}}</h3>
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
name:'',
styleobj: {
width: "30%",
padding: "12px 20px",
margin: "8px 0",
boxSizing: "border-box"
}
},
methods : {
showinputvalue : function(event) {
this.name=event.target.value;
}
}
});
</script>
</body>
</html>
Type something in the textbox and we will see it is displayed only when we press Enter.
Parent can pass data to its component using the prop attribute, however, we need to tell the parent when there are changes in the child component. For this, we can use custom events.
The parent component can listen to the child component event using v-on attribute.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<div id = "counter-event-example">
<p style = "font-size:25px;">Language displayed : <b>{{ languageclicked }}</b></p>
<button-counter
v-for = "(item, index) in languages"
v-bind:item = "item"
v-bind:index = "index"
v-on:showlanguage = "languagedisp"></button-counter>
</div>
</div>
<script type = "text/javascript">
Vue.component('button-counter', {
template: '<button v-on:click = "displayLanguage(item)"><span style = "font-size:25px;">{{ item }}</span></button>',
data: function () {
return {
counter: 0
}
},
props:['item'],
methods: {
displayLanguage: function (lng) {
console.log(lng);
this.$emit('showlanguage', lng);
}
},
});
var vm = new Vue({
el: '#databinding',
data: {
languageclicked: "",
languages : ["Java", "PHP", "C++", "C", "Javascript", "C#", "Python", "HTML"]
},
methods: {
languagedisp: function (a) {
this.languageclicked = a;
}
}
})
</script>
</body>
</html>
The above code shows the data transfer between the parent component and the child component.
The component is created using the following code.
<button-counter
v-for = "(item, index) in languages"
v-bind:item = "item"
v-bind:index = "index"
v-on:showlanguage = "languagedisp">
</button-counter>
There is a v-for attribute, which will loop with the languages array. The array has a list of languages in it. We need to send the details to the child component. The values of the array are stored in the item and the index.
v-bind:item = "item"
v-bind:index = "index"
To refer to the values of the array, we need to bind it first to a variable and the varaiable is referred using props property as follows.
Vue.component('button-counter', {
template: '<button v-on:click = "displayLanguage(item)"><span style = "font-size:25px;">{{ item }}</span></button>',
data: function () {
return {
counter: 0
}
},
props:['item'],
methods: {
displayLanguage: function (lng) {
console.log(lng);
this.$emit('showlanguage', lng);
}
},
});
The props property contains the item in an array form. We can also refer to the index as −
props:[‘item’, ‘index’]
There is also an event added to the component as follows −
<button-counter
v-for = "(item, index) in languages"
v-bind:item = "item"
v-bind:index = "index"
v-on:showlanguage = "languagedisp">
</button-counter>
The name of the event is showlanguage and it calls a method called languagedisp which is defined in the Vue instance.
In the component, the template is defined as follows −
template: '<button v-on:click = "displayLanguage(item)"><span style = "font-size:25px;">{{ item }}</span></button>',
There is a button created. The button will get created with as many count in the language array. On the click of the button, there is a method called displayLanguage and the button clicked item is passed as a param to the function. Now the component needs to send the clicked element to the parent component for display which is done as follows −
Vue.component('button-counter', {
template: '<button v-on:click = "displayLanguage(item)"><span style = "font-size:25px;">{{ item }}</span></button>',
data: function () {
return {
counter: 0
}
},
props:['item'],
methods: {
displayLanguage: function (lng) {
console.log(lng);
this.$emit('showlanguage', lng);
}
},
});
The method displayLanguage calls this.$emit(‘showlanguage’, lng);
$emit is used to call the parent component method. The method showlanguage is the event name given on the component with v-on.
<button-counter
v-for = "(item, index) in languages"
v-bind:item = "item"
v-bind:index = "index"
v-on:showlanguage = "languagedisp">
</button-counter>
We are passing a parameter, i.e. the name of the language clicked to the method of the main parent Vue instance which is defined as follows.
var vm = new Vue({
el: '#databinding',
data: {
languageclicked: "",
languages : ["Java", "PHP", "C++", "C", "Javascript", "C#", "Python", "HTML"]
},
methods: {
languagedisp: function (a) {
this.languageclicked = a;
}
}
})
Here, the emit triggers showlanguage which in turn calls languagedisp from the Vue instance methods. It assigns the language clicked value to the variable languageclicked and the same is displayed in the browser as shown in the following screenshot.
<p style = "font-size:25px;">Language displayed : <b>{{ languageclicked }}</b></p>
Following is the output we get in the browser.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2018,
"s": 1936,
"text": "v-on is the attribute added to the DOM elements to listen to the events in VueJS."
},
{
"code": null,
"e": 2787,
"s": 2018,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <button v-on:click = \"displaynumbers\">Click ME</button>\n <h2> Add Number 100 + 200 = {{total}}</h2>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n num1: 100,\n num2 : 200,\n total : ''\n },\n methods : {\n displaynumbers : function(event) {\n console.log(event);\n return this.total = this.num1+ this.num2;\n }\n },\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2859,
"s": 2787,
"text": "The following code is used to assign a click event for the DOM element."
},
{
"code": null,
"e": 2915,
"s": 2859,
"text": "<button v-on:click = \"displaynumbers\">Click ME</button>"
},
{
"code": null,
"e": 2998,
"s": 2915,
"text": "There is a shorthand for v-on, which means we can also call the event as follows −"
},
{
"code": null,
"e": 3050,
"s": 2998,
"text": "<button @click = \"displaynumbers\">Click ME</button>"
},
{
"code": null,
"e": 3206,
"s": 3050,
"text": "On the click of the button, it will call the method ‘displaynumbers’, which takes in the event and we have consoled the same in the browser as shown above."
},
{
"code": null,
"e": 3259,
"s": 3206,
"text": "We will now check one more event mouseover mouseout."
},
{
"code": null,
"e": 4249,
"s": 3259,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <div v-bind:style = \"styleobj\" v-on:mouseover = \"changebgcolor\" v-on:mouseout = \"originalcolor\"></div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n num1: 100,\n num2 : 200,\n total : '',\n styleobj : {\n width:\"100px\",\n height:\"100px\",\n backgroundColor:\"red\"\n }\n },\n methods : {\n changebgcolor : function() {\n this.styleobj.backgroundColor = \"green\";\n },\n originalcolor : function() {\n this.styleobj.backgroundColor = \"red\";\n }\n },\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4472,
"s": 4249,
"text": "In the above example, we have created a div with width and height as 100px. It has been given a background color red. On mouseover, we are changing the color to green, and on mouseout we are changing the color back to red."
},
{
"code": null,
"e": 4607,
"s": 4472,
"text": "Hence, during mouseover, a method is called changebgcolor and once we move the mouse out of the div, a method is called originalcolor."
},
{
"code": null,
"e": 4633,
"s": 4607,
"text": "This is done as follows −"
},
{
"code": null,
"e": 4736,
"s": 4633,
"text": "<div v-bind:style = \"styleobj\" v-on:mouseover = \"changebgcolor\" v-on:mouseout = \"originalcolor\"></div>"
},
{
"code": null,
"e": 4976,
"s": 4736,
"text": "Two events - mouseover and mouseout - is assigned to the div as shown above. We have created a styleobj variable and given the required style to be assigned to the div. The same variable is binded to the div using v-bind:style = ”styleobj”"
},
{
"code": null,
"e": 5055,
"s": 4976,
"text": "In changebgcolor, we are changing the color to green using the following code."
},
{
"code": null,
"e": 5130,
"s": 5055,
"text": "changebgcolor : function() {\n this.styleobj.backgroundColor = \"green\";\n}"
},
{
"code": null,
"e": 5194,
"s": 5130,
"text": "Using the stylobj variable, we are changing the color to green."
},
{
"code": null,
"e": 5273,
"s": 5194,
"text": "Similarly, the following code is used to change it back to the original color."
},
{
"code": null,
"e": 5346,
"s": 5273,
"text": "originalcolor : function() {\n this.styleobj.backgroundColor = \"red\";\n}"
},
{
"code": null,
"e": 5382,
"s": 5346,
"text": "This is what we see in the browser."
},
{
"code": null,
"e": 5470,
"s": 5382,
"text": "When we mouseover, the color will change to green as shown in the following screenshot."
},
{
"code": null,
"e": 5563,
"s": 5470,
"text": "Vue has event modifiers available on v-on attribute. Following are the modifiers available −"
},
{
"code": null,
"e": 5602,
"s": 5563,
"text": "Allows the event to execute only once."
},
{
"code": null,
"e": 5665,
"s": 5602,
"text": "<button v-on:click.once = \"buttonclicked\">Click Once</button>\n"
},
{
"code": null,
"e": 5828,
"s": 5665,
"text": "We need to add dot operator while calling the modifiers as shown in the syntax above. Let us use it in an example and understand the working of the once modifier."
},
{
"code": null,
"e": 6980,
"s": 5828,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <button v-on:click.once = \"buttonclickedonce\" v-bind:style = \"styleobj\">Click Once</button>\n Output:{{clicknum}}\n <br/><br/>\n <button v-on:click = \"buttonclicked\" v-bind:style = \"styleobj\">Click Me</button>\n Output:{{clicknum1}}\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n clicknum : 0,\n clicknum1 :0,\n styleobj: {\n backgroundColor: '#2196F3!important',\n cursor: 'pointer',\n padding: '8px 16px',\n verticalAlign: 'middle',\n }\n },\n methods : {\n buttonclickedonce : function() {\n this.clicknum++;\n },\n buttonclicked : function() {\n this.clicknum1++;\n }\n }\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 7180,
"s": 6980,
"text": "In the above example, we have created two butttons. The button with Click Once label has added the once modifier and the other button is without any modifier. This is the way the buttons are defined."
},
{
"code": null,
"e": 7354,
"s": 7180,
"text": "<button v-on:click.once = \"buttonclickedonce\" v-bind:style = \"styleobj\">Click Once</button>\n<button v-on:click = \"buttonclicked\" v-bind:style = \"styleobj\">Click Me</button>"
},
{
"code": null,
"e": 7464,
"s": 7354,
"text": "The first button calls the method “buttonclickedonce” and the second button calls the method “buttonclicked”."
},
{
"code": null,
"e": 7572,
"s": 7464,
"text": "buttonclickedonce : function() {\n this.clicknum++;\n},\nbuttonclicked : function() {\n this.clicknum1++;\n}"
},
{
"code": null,
"e": 7769,
"s": 7572,
"text": "There are two variables defined in the clicknum and clicknum1. Both are incremented when the button is clicked. Both the variables are initialized to 0 and the display is seen in the output above."
},
{
"code": null,
"e": 8003,
"s": 7769,
"text": "On the click of the first button, the variable clicknum increments by 1. On the second click, the number is not incremented as the modifier prevents it from executing or performing any action item assigned on the click of the button."
},
{
"code": null,
"e": 8160,
"s": 8003,
"text": "On the click of the second button, the same action is carried out, i.e. the variable is incremented. On every click, the value is incremented and displayed."
},
{
"code": null,
"e": 8207,
"s": 8160,
"text": "Following is the output we get in the browser."
},
{
"code": null,
"e": 8214,
"s": 8207,
"text": "Syntax"
},
{
"code": null,
"e": 8293,
"s": 8214,
"text": "<a href = \"http://www.google.com\" v-on:click.prevent = \"clickme\">Click Me</a>\n"
},
{
"code": null,
"e": 8301,
"s": 8293,
"text": "Example"
},
{
"code": null,
"e": 9146,
"s": 8301,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <a href = \"http://www.google.com\" v-on:click = \"clickme\" target = \"_blank\" v-bind:style = \"styleobj\">Click Me</a>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n clicknum : 0,\n clicknum1 :0,\n styleobj: {\n color: '#4CAF50',\n marginLeft: '20px',\n fontSize: '30px'\n }\n },\n methods : {\n clickme : function() {\n alert(\"Anchor tag is clicked\");\n }\n }\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 9153,
"s": 9146,
"text": "Output"
},
{
"code": null,
"e": 9333,
"s": 9153,
"text": "If we click the clickme link, it will send an alert as “Anchor tag is clicked” and it will open the link https://www.google.com in a new tab as shown in the following screenshots."
},
{
"code": null,
"e": 9524,
"s": 9333,
"text": "Now this works as a normal way, i.e. the link opens up as we want. In case we don’t want the link to open up, we need to add a modifier ‘prevent’ to the event as shown in the following code."
},
{
"code": null,
"e": 9646,
"s": 9524,
"text": "<a href = \"http://www.google.com\" v-on:click.prevent = \"clickme\" target = \"_blank\" v-bind:style = \"styleobj\">Click Me</a>"
},
{
"code": null,
"e": 9853,
"s": 9646,
"text": "Once added, if we click on the button, it will send an alert message and will not open the link anymore. The prevent modifier prevents the link from opening and only executes the method assigned to the tag."
},
{
"code": null,
"e": 9861,
"s": 9853,
"text": "Example"
},
{
"code": null,
"e": 10714,
"s": 9861,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <a href = \"http://www.google.com\" v-on:click.prevent = \"clickme\" target = \"_blank\" v-bind:style = \"styleobj\">Click Me</a>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n clicknum : 0,\n clicknum1 :0,\n styleobj: {\n color: '#4CAF50',\n marginLeft: '20px',\n fontSize: '30px'\n }\n },\n methods : {\n clickme : function() {\n alert(\"Anchor tag is clicked\");\n }\n }\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 10721,
"s": 10714,
"text": "Output"
},
{
"code": null,
"e": 10816,
"s": 10721,
"text": "On the click of the link, it will display the alert message and does not open the url anymore."
},
{
"code": null,
"e": 11045,
"s": 10816,
"text": "VueJS offers key modifiers based on which we can control the event handling. Consider we have a textbox and we want the method to be called only when we press Enter. We can do so by adding key modifiers to the events as follows."
},
{
"code": null,
"e": 11106,
"s": 11045,
"text": "<input type = \"text\" v-on:keyup.enter = \"showinputvalue\"/>\n"
},
{
"code": null,
"e": 11192,
"s": 11106,
"text": "The key that we want to apply to our event is V-on.eventname.keyname (as shown above)"
},
{
"code": null,
"e": 11265,
"s": 11192,
"text": "We can make use of multiple keynames. For example, V-on.keyup.ctrl.enter"
},
{
"code": null,
"e": 12157,
"s": 11265,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <input type = \"text\" v-on:keyup.enter = \"showinputvalue\" v-bind:style = \"styleobj\" placeholder = \"Enter your name\"/>\n <h3> {{name}}</h3>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n name:'',\n styleobj: {\n width: \"30%\",\n padding: \"12px 20px\",\n margin: \"8px 0\",\n boxSizing: \"border-box\"\n }\n },\n methods : {\n showinputvalue : function(event) {\n this.name=event.target.value;\n }\n }\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 12245,
"s": 12157,
"text": "Type something in the textbox and we will see it is displayed only when we press Enter."
},
{
"code": null,
"e": 12428,
"s": 12245,
"text": "Parent can pass data to its component using the prop attribute, however, we need to tell the parent when there are changes in the child component. For this, we can use custom events."
},
{
"code": null,
"e": 12511,
"s": 12428,
"text": "The parent component can listen to the child component event using v-on attribute."
},
{
"code": null,
"e": 14035,
"s": 12511,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <div id = \"counter-event-example\">\n <p style = \"font-size:25px;\">Language displayed : <b>{{ languageclicked }}</b></p>\n <button-counter\n v-for = \"(item, index) in languages\"\n v-bind:item = \"item\"\n v-bind:index = \"index\"\n v-on:showlanguage = \"languagedisp\"></button-counter>\n </div>\n </div>\n <script type = \"text/javascript\">\n Vue.component('button-counter', {\n template: '<button v-on:click = \"displayLanguage(item)\"><span style = \"font-size:25px;\">{{ item }}</span></button>',\n data: function () {\n return {\n counter: 0\n }\n },\n props:['item'],\n methods: {\n displayLanguage: function (lng) {\n console.log(lng);\n this.$emit('showlanguage', lng);\n }\n },\n });\n var vm = new Vue({\n el: '#databinding',\n data: {\n languageclicked: \"\",\n languages : [\"Java\", \"PHP\", \"C++\", \"C\", \"Javascript\", \"C#\", \"Python\", \"HTML\"]\n },\n methods: {\n languagedisp: function (a) {\n this.languageclicked = a;\n }\n }\n })\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 14128,
"s": 14035,
"text": "The above code shows the data transfer between the parent component and the child component."
},
{
"code": null,
"e": 14179,
"s": 14128,
"text": "The component is created using the following code."
},
{
"code": null,
"e": 14342,
"s": 14179,
"text": "<button-counter\n v-for = \"(item, index) in languages\"\n v-bind:item = \"item\"\n v-bind:index = \"index\"\n v-on:showlanguage = \"languagedisp\">\n</button-counter>"
},
{
"code": null,
"e": 14567,
"s": 14342,
"text": "There is a v-for attribute, which will loop with the languages array. The array has a list of languages in it. We need to send the details to the child component. The values of the array are stored in the item and the index."
},
{
"code": null,
"e": 14611,
"s": 14567,
"text": "v-bind:item = \"item\"\nv-bind:index = \"index\""
},
{
"code": null,
"e": 14750,
"s": 14611,
"text": "To refer to the values of the array, we need to bind it first to a variable and the varaiable is referred using props property as follows."
},
{
"code": null,
"e": 15136,
"s": 14750,
"text": "Vue.component('button-counter', {\n template: '<button v-on:click = \"displayLanguage(item)\"><span style = \"font-size:25px;\">{{ item }}</span></button>',\n data: function () {\n return {\n counter: 0\n }\n },\n props:['item'],\n methods: {\n displayLanguage: function (lng) {\n console.log(lng);\n this.$emit('showlanguage', lng);\n }\n },\n});"
},
{
"code": null,
"e": 15227,
"s": 15136,
"text": "The props property contains the item in an array form. We can also refer to the index as −"
},
{
"code": null,
"e": 15251,
"s": 15227,
"text": "props:[‘item’, ‘index’]"
},
{
"code": null,
"e": 15310,
"s": 15251,
"text": "There is also an event added to the component as follows −"
},
{
"code": null,
"e": 15473,
"s": 15310,
"text": "<button-counter\n v-for = \"(item, index) in languages\"\n v-bind:item = \"item\"\n v-bind:index = \"index\"\n v-on:showlanguage = \"languagedisp\">\n</button-counter>"
},
{
"code": null,
"e": 15591,
"s": 15473,
"text": "The name of the event is showlanguage and it calls a method called languagedisp which is defined in the Vue instance."
},
{
"code": null,
"e": 15646,
"s": 15591,
"text": "In the component, the template is defined as follows −"
},
{
"code": null,
"e": 15763,
"s": 15646,
"text": "template: '<button v-on:click = \"displayLanguage(item)\"><span style = \"font-size:25px;\">{{ item }}</span></button>',"
},
{
"code": null,
"e": 16110,
"s": 15763,
"text": "There is a button created. The button will get created with as many count in the language array. On the click of the button, there is a method called displayLanguage and the button clicked item is passed as a param to the function. Now the component needs to send the clicked element to the parent component for display which is done as follows −"
},
{
"code": null,
"e": 16496,
"s": 16110,
"text": "Vue.component('button-counter', {\n template: '<button v-on:click = \"displayLanguage(item)\"><span style = \"font-size:25px;\">{{ item }}</span></button>',\n data: function () {\n return {\n counter: 0\n }\n },\n props:['item'],\n methods: {\n displayLanguage: function (lng) {\n console.log(lng);\n this.$emit('showlanguage', lng);\n }\n },\n});"
},
{
"code": null,
"e": 16562,
"s": 16496,
"text": "The method displayLanguage calls this.$emit(‘showlanguage’, lng);"
},
{
"code": null,
"e": 16689,
"s": 16562,
"text": "$emit is used to call the parent component method. The method showlanguage is the event name given on the component with v-on."
},
{
"code": null,
"e": 16852,
"s": 16689,
"text": "<button-counter\n v-for = \"(item, index) in languages\"\n v-bind:item = \"item\"\n v-bind:index = \"index\"\n v-on:showlanguage = \"languagedisp\">\n</button-counter>"
},
{
"code": null,
"e": 16993,
"s": 16852,
"text": "We are passing a parameter, i.e. the name of the language clicked to the method of the main parent Vue instance which is defined as follows."
},
{
"code": null,
"e": 17263,
"s": 16993,
"text": "var vm = new Vue({\n el: '#databinding',\n data: {\n languageclicked: \"\",\n languages : [\"Java\", \"PHP\", \"C++\", \"C\", \"Javascript\", \"C#\", \"Python\", \"HTML\"]\n },\n methods: {\n languagedisp: function (a) {\n this.languageclicked = a;\n }\n }\n})"
},
{
"code": null,
"e": 17513,
"s": 17263,
"text": "Here, the emit triggers showlanguage which in turn calls languagedisp from the Vue instance methods. It assigns the language clicked value to the variable languageclicked and the same is displayed in the browser as shown in the following screenshot."
},
{
"code": null,
"e": 17596,
"s": 17513,
"text": "<p style = \"font-size:25px;\">Language displayed : <b>{{ languageclicked }}</b></p>"
},
{
"code": null,
"e": 17643,
"s": 17596,
"text": "Following is the output we get in the browser."
},
{
"code": null,
"e": 17650,
"s": 17643,
"text": " Print"
},
{
"code": null,
"e": 17661,
"s": 17650,
"text": " Add Notes"
}
] |
Visualizing multi dimensional arrays | by Nayantara Jeyaraj (Taro) | Towards Data Science | If you asked my opinion about Multidimensional arrays, 5 or 6 years ago, I would have said that they were the most simplistic concept to grasp but the most complicated to implement since the above “architectural marvel” is what pops into my mind as soon as I think of a Multidimensional Array.
That was ages ago before I discovered the most easiest way, as easy as understanding 1+1 = 2, to implement them. Well, though some of you may already be well aware and this might sound like a trivial task, there is a percentage that needs clarification in this concept like I did years ago. So buckle up, here we go.
Let’s start off with the very basics. What’s an Array?
The primitive definition of arrays simply stated that
Arrays were a storage medium that could hold a fixed number of values of a single type
While this is partially true, it not the case anymore. Considering the programming language that I’ve chosen at hand, I think we can expand this definition and modify it to new levels.
JavaScript provides the ever so useful feature of allowing arrays that can be dynamically created, meaning that the size of the array can be decided at a later time and doesn’t even have to be fixed. It can be modified, either incremented or decremented, as the number data to be stored to the array changes.
Well, we all might have noted this dynamism of creating linear one dimensional or two dimensional arrays at some point. So let’s step into creating multi dimensional arrays.
A multidimensional array, in my opinion is an array within an array. Let’s discuss the an array using a table to visualize this easily.
Imagine that you have a simple table where you need to store Student Details such as Name, Age, Grade and Subjects offered. Now, since we have to store details of many students, it might be obvious that this is already a two dimensional array where the above details will be mapped in the following manner.
Upto a certain level this table might seem to be sufficient to grab info from. But, it will be considered to be much cleaner and efficient if the last column, that saves the ‘Subjects Offered’ ,was also subdivided as shown below.
This provides us the privilege of manipulating details of these sub- disciplines of the subjects as well. So, how do we implement this?
Let’s call the array that maps the above Student Details as “studentArray”. And we’ll be creating the skeleton for this array.
var noOfStudentRecords=100;var noOfColumns = 4;var studentArray = [];for(var x = 0; x < noOfStudentRecords; x++){ studentArray[x] = []; for(var y = 0; y < noOfColumns; y++) { if(y==3) { studentArray[x][y]= new Array[3]; } }}
In the above code, we specify the third column as a new array : hence, an array within another array creating a multidimensional array.
This is a very basic explanation of creating multidimensional arrays. In more complex situations, we can split these individual subjects into further categories to host additional details, applying the same concept as above, just on a different dimension. | [
{
"code": null,
"e": 465,
"s": 171,
"text": "If you asked my opinion about Multidimensional arrays, 5 or 6 years ago, I would have said that they were the most simplistic concept to grasp but the most complicated to implement since the above “architectural marvel” is what pops into my mind as soon as I think of a Multidimensional Array."
},
{
"code": null,
"e": 782,
"s": 465,
"text": "That was ages ago before I discovered the most easiest way, as easy as understanding 1+1 = 2, to implement them. Well, though some of you may already be well aware and this might sound like a trivial task, there is a percentage that needs clarification in this concept like I did years ago. So buckle up, here we go."
},
{
"code": null,
"e": 837,
"s": 782,
"text": "Let’s start off with the very basics. What’s an Array?"
},
{
"code": null,
"e": 891,
"s": 837,
"text": "The primitive definition of arrays simply stated that"
},
{
"code": null,
"e": 978,
"s": 891,
"text": "Arrays were a storage medium that could hold a fixed number of values of a single type"
},
{
"code": null,
"e": 1163,
"s": 978,
"text": "While this is partially true, it not the case anymore. Considering the programming language that I’ve chosen at hand, I think we can expand this definition and modify it to new levels."
},
{
"code": null,
"e": 1472,
"s": 1163,
"text": "JavaScript provides the ever so useful feature of allowing arrays that can be dynamically created, meaning that the size of the array can be decided at a later time and doesn’t even have to be fixed. It can be modified, either incremented or decremented, as the number data to be stored to the array changes."
},
{
"code": null,
"e": 1646,
"s": 1472,
"text": "Well, we all might have noted this dynamism of creating linear one dimensional or two dimensional arrays at some point. So let’s step into creating multi dimensional arrays."
},
{
"code": null,
"e": 1782,
"s": 1646,
"text": "A multidimensional array, in my opinion is an array within an array. Let’s discuss the an array using a table to visualize this easily."
},
{
"code": null,
"e": 2089,
"s": 1782,
"text": "Imagine that you have a simple table where you need to store Student Details such as Name, Age, Grade and Subjects offered. Now, since we have to store details of many students, it might be obvious that this is already a two dimensional array where the above details will be mapped in the following manner."
},
{
"code": null,
"e": 2319,
"s": 2089,
"text": "Upto a certain level this table might seem to be sufficient to grab info from. But, it will be considered to be much cleaner and efficient if the last column, that saves the ‘Subjects Offered’ ,was also subdivided as shown below."
},
{
"code": null,
"e": 2455,
"s": 2319,
"text": "This provides us the privilege of manipulating details of these sub- disciplines of the subjects as well. So, how do we implement this?"
},
{
"code": null,
"e": 2582,
"s": 2455,
"text": "Let’s call the array that maps the above Student Details as “studentArray”. And we’ll be creating the skeleton for this array."
},
{
"code": null,
"e": 2851,
"s": 2582,
"text": "var noOfStudentRecords=100;var noOfColumns = 4;var studentArray = [];for(var x = 0; x < noOfStudentRecords; x++){ studentArray[x] = []; for(var y = 0; y < noOfColumns; y++) { if(y==3) { studentArray[x][y]= new Array[3]; } }}"
},
{
"code": null,
"e": 2987,
"s": 2851,
"text": "In the above code, we specify the third column as a new array : hence, an array within another array creating a multidimensional array."
}
] |
Kubernetes - Service | A service can be defined as a logical set of pods. It can be defined as an abstraction on the top of the pod which provides a single IP address and DNS name by which pods can be accessed. With Service, it is very easy to manage load balancing configuration. It helps pods to scale very easily.
A service is a REST object in Kubernetes whose definition can be posted to Kubernetes apiServer on the Kubernetes master to create a new instance.
apiVersion: v1
kind: Service
metadata:
name: Tutorial_point_service
spec:
ports:
- port: 8080
targetPort: 31999
The above configuration will create a service with the name Tutorial_point_service.
apiVersion: v1
kind: Service
metadata:
name: Tutorial_point_service
spec:
selector:
application: "My Application" -------------------> (Selector)
ports:
- port: 8080
targetPort: 31999
In this example, we have a selector; so in order to transfer traffic, we need to create an endpoint manually.
apiVersion: v1
kind: Endpoints
metadata:
name: Tutorial_point_service
subnets:
address:
"ip": "192.168.168.40" -------------------> (Selector)
ports:
- port: 8080
In the above code, we have created an endpoint which will route the traffic to the endpoint defined as “192.168.168.40:8080”.
apiVersion: v1
kind: Service
metadata:
name: Tutorial_point_service
spec:
selector:
application: “My Application” -------------------> (Selector)
ClusterIP: 10.3.0.12
ports:
-name: http
protocol: TCP
port: 80
targetPort: 31999
-name:https
Protocol: TCP
Port: 443
targetPort: 31998
ClusterIP − This helps in restricting the service within the cluster. It exposes the service within the defined Kubernetes cluster.
spec:
type: NodePort
ports:
- port: 8080
nodePort: 31999
name: NodeportService
NodePort − It will expose the service on a static port on the deployed node. A ClusterIP service, to which NodePort service will route, is automatically created. The service can be accessed from outside the cluster using the NodeIP:nodePort.
spec:
ports:
- port: 8080
nodePort: 31999
name: NodeportService
clusterIP: 10.20.30.40
Load Balancer − It uses cloud providers’ load balancer. NodePort and ClusterIP services are created automatically to which the external load balancer will route.
A full service yaml file with service type as Node Port. Try to create one yourself.
apiVersion: v1
kind: Service
metadata:
name: appname
labels:
k8s-app: appname
spec:
type: NodePort
ports:
- port: 8080
nodePort: 31999
name: omninginx
selector:
k8s-app: appname
component: nginx
env: env_name
41 Lectures
5 hours
AR Shankar
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
18 Lectures
1.5 hours
Nigel Poulton
25 Lectures
1.5 hours
Pranjal Srivastava
18 Lectures
1 hours
Pranjal Srivastava
26 Lectures
1.5 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2489,
"s": 2195,
"text": "A service can be defined as a logical set of pods. It can be defined as an abstraction on the top of the pod which provides a single IP address and DNS name by which pods can be accessed. With Service, it is very easy to manage load balancing configuration. It helps pods to scale very easily."
},
{
"code": null,
"e": 2636,
"s": 2489,
"text": "A service is a REST object in Kubernetes whose definition can be posted to Kubernetes apiServer on the Kubernetes master to create a new instance."
},
{
"code": null,
"e": 2761,
"s": 2636,
"text": "apiVersion: v1\nkind: Service\nmetadata:\n name: Tutorial_point_service\nspec:\n ports:\n - port: 8080\n targetPort: 31999\n"
},
{
"code": null,
"e": 2845,
"s": 2761,
"text": "The above configuration will create a service with the name Tutorial_point_service."
},
{
"code": null,
"e": 3051,
"s": 2845,
"text": "apiVersion: v1\nkind: Service\nmetadata:\n name: Tutorial_point_service\nspec:\n selector:\n application: \"My Application\" -------------------> (Selector)\n ports:\n - port: 8080\n targetPort: 31999\n"
},
{
"code": null,
"e": 3161,
"s": 3051,
"text": "In this example, we have a selector; so in order to transfer traffic, we need to create an endpoint manually."
},
{
"code": null,
"e": 3346,
"s": 3161,
"text": "apiVersion: v1\nkind: Endpoints\nmetadata:\n name: Tutorial_point_service\nsubnets:\n address:\n \"ip\": \"192.168.168.40\" -------------------> (Selector)\n ports:\n - port: 8080\n"
},
{
"code": null,
"e": 3472,
"s": 3346,
"text": "In the above code, we have created an endpoint which will route the traffic to the endpoint defined as “192.168.168.40:8080”."
},
{
"code": null,
"e": 3817,
"s": 3472,
"text": "apiVersion: v1\nkind: Service\nmetadata:\n name: Tutorial_point_service\nspec:\n selector:\n application: “My Application” -------------------> (Selector)\n ClusterIP: 10.3.0.12\n ports:\n -name: http\n protocol: TCP\n port: 80\n targetPort: 31999\n -name:https\n Protocol: TCP\n Port: 443\n targetPort: 31998\n"
},
{
"code": null,
"e": 3949,
"s": 3817,
"text": "ClusterIP − This helps in restricting the service within the cluster. It exposes the service within the defined Kubernetes cluster."
},
{
"code": null,
"e": 4050,
"s": 3949,
"text": "spec:\n type: NodePort\n ports:\n - port: 8080\n nodePort: 31999\n name: NodeportService\n"
},
{
"code": null,
"e": 4292,
"s": 4050,
"text": "NodePort − It will expose the service on a static port on the deployed node. A ClusterIP service, to which NodePort service will route, is automatically created. The service can be accessed from outside the cluster using the NodeIP:nodePort."
},
{
"code": null,
"e": 4404,
"s": 4292,
"text": "spec:\n ports:\n - port: 8080\n nodePort: 31999\n name: NodeportService\n clusterIP: 10.20.30.40\n"
},
{
"code": null,
"e": 4566,
"s": 4404,
"text": "Load Balancer − It uses cloud providers’ load balancer. NodePort and ClusterIP services are created automatically to which the external load balancer will route."
},
{
"code": null,
"e": 4651,
"s": 4566,
"text": "A full service yaml file with service type as Node Port. Try to create one yourself."
},
{
"code": null,
"e": 4915,
"s": 4651,
"text": "apiVersion: v1\nkind: Service\nmetadata:\n name: appname\n labels:\n k8s-app: appname\nspec:\n type: NodePort\n ports:\n - port: 8080\n nodePort: 31999\n name: omninginx\n selector:\n k8s-app: appname\n component: nginx\n env: env_name\n"
},
{
"code": null,
"e": 4948,
"s": 4915,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4960,
"s": 4948,
"text": " AR Shankar"
},
{
"code": null,
"e": 4993,
"s": 4960,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5033,
"s": 4993,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 5068,
"s": 5033,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5083,
"s": 5068,
"text": " Nigel Poulton"
},
{
"code": null,
"e": 5118,
"s": 5083,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5138,
"s": 5118,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5171,
"s": 5138,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5191,
"s": 5171,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5226,
"s": 5191,
"text": "\n 26 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5246,
"s": 5226,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5253,
"s": 5246,
"text": " Print"
},
{
"code": null,
"e": 5264,
"s": 5253,
"text": " Add Notes"
}
] |
C - Input and Output | C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to read given input and feed it to the program as per requirement.
Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data.
Here we will discuss only one input function and one putput function just to understand the meaning of input and output. Rest of the functions are given into C - Built-in Functions
This is one of the most frequently used functions in C for output. ( we will discuss what is function in subsequent chapter. ).
Try following program to understand printf() function.
#include <stdio.h>
main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;
printf("%d %s %f %c\n", dec, str, pi, ch);
}
The output of the above would be:
5 abc 3.140000 c
Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to print a float and %c is being used to print a character.
A complete syntax of printf() function is given in C - Built-in Functions
This is the function which can be used to to read an input from the command line.
Try following program to understand scanf() function.
#include <stdio.h>
main()
{
int x;
int args;
printf("Enter an integer: ");
if (( args = scanf("%d", &x)) == 0) {
printf("Error: not an integer\n");
} else {
printf("Read in %d\n", x);
}
}
Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here &indicates the address of variavle x.
This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it will display an error message.
Enter an integer: 20
Read in 20
A complete set of input output functions is given in C - Built-in Functions
Advertisements
6 Lectures
1.5 hours
Mr. Pradeep Kshetrapal
41 Lectures
5 hours
AR Shankar
11 Lectures
58 mins
Musab Zayadneh
59 Lectures
15.5 hours
Narendra P
11 Lectures
1 hours
Sagar Mehta
39 Lectures
4 hours
Vikas Yadav
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1475,
"s": 1454,
"text": "C - Programming HOME"
},
{
"code": null,
"e": 1498,
"s": 1475,
"text": "C - Basic Introduction"
},
{
"code": null,
"e": 1520,
"s": 1498,
"text": "C - Program Structure"
},
{
"code": null,
"e": 1542,
"s": 1520,
"text": "C - Reserved Keywords"
},
{
"code": null,
"e": 1562,
"s": 1542,
"text": "C - Basic Datatypes"
},
{
"code": null,
"e": 1581,
"s": 1562,
"text": "C - Variable Types"
},
{
"code": null,
"e": 1601,
"s": 1581,
"text": "C - Storage Classes"
},
{
"code": null,
"e": 1621,
"s": 1601,
"text": "C - Using Constants"
},
{
"code": null,
"e": 1640,
"s": 1621,
"text": "C - Operator Types"
},
{
"code": null,
"e": 1663,
"s": 1640,
"text": "C - Control Statements"
},
{
"code": null,
"e": 1684,
"s": 1663,
"text": "C - Input and Output"
},
{
"code": null,
"e": 1705,
"s": 1684,
"text": "C - Pointing to Data"
},
{
"code": null,
"e": 1725,
"s": 1705,
"text": "C - Using Functions"
},
{
"code": null,
"e": 1747,
"s": 1725,
"text": "C - Play with Strings"
},
{
"code": null,
"e": 1772,
"s": 1747,
"text": "C - Structured Datatypes"
},
{
"code": null,
"e": 1795,
"s": 1772,
"text": "C - Working with Files"
},
{
"code": null,
"e": 1817,
"s": 1795,
"text": "C - Bits Manipulation"
},
{
"code": null,
"e": 1836,
"s": 1817,
"text": "C - Pre-Processors"
},
{
"code": null,
"e": 1856,
"s": 1836,
"text": "C - Useful Concepts"
},
{
"code": null,
"e": 1879,
"s": 1856,
"text": "C - Built-in Functions"
},
{
"code": null,
"e": 1900,
"s": 1879,
"text": "C - Useful Resources"
},
{
"code": null,
"e": 1918,
"s": 1900,
"text": "Computer Glossary"
},
{
"code": null,
"e": 1929,
"s": 1918,
"text": "Who is Who"
},
{
"code": null,
"e": 1964,
"s": 1929,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2232,
"s": 1964,
"text": "Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to read given input and feed it to the program as per requirement."
},
{
"code": null,
"e": 2424,
"s": 2232,
"text": "Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data."
},
{
"code": null,
"e": 2605,
"s": 2424,
"text": "Here we will discuss only one input function and one putput function just to understand the meaning of input and output. Rest of the functions are given into C - Built-in Functions"
},
{
"code": null,
"e": 2733,
"s": 2605,
"text": "This is one of the most frequently used functions in C for output. ( we will discuss what is function in subsequent chapter. )."
},
{
"code": null,
"e": 2788,
"s": 2733,
"text": "Try following program to understand printf() function."
},
{
"code": null,
"e": 2940,
"s": 2788,
"text": "#include <stdio.h>\n\nmain()\n{\n int dec = 5;\n char str[] = \"abc\";\n char ch = 's';\n float pi = 3.14;\n\n printf(\"%d %s %f %c\\n\", dec, str, pi, ch);\n}\n"
},
{
"code": null,
"e": 2974,
"s": 2940,
"text": "The output of the above would be:"
},
{
"code": null,
"e": 2999,
"s": 2974,
"text": " 5 abc 3.140000 c\n"
},
{
"code": null,
"e": 3155,
"s": 2999,
"text": "Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to print a float and %c is being used to print a character."
},
{
"code": null,
"e": 3230,
"s": 3155,
"text": "A complete syntax of printf() function is given in C - Built-in Functions\n"
},
{
"code": null,
"e": 3312,
"s": 3230,
"text": "This is the function which can be used to to read an input from the command line."
},
{
"code": null,
"e": 3366,
"s": 3312,
"text": "Try following program to understand scanf() function."
},
{
"code": null,
"e": 3581,
"s": 3366,
"text": "#include <stdio.h>\n\nmain()\n{\n int x;\n int args;\n\n printf(\"Enter an integer: \");\n if (( args = scanf(\"%d\", &x)) == 0) {\n printf(\"Error: not an integer\\n\");\n } else {\n printf(\"Read in %d\\n\", x);\n }\n}\n"
},
{
"code": null,
"e": 3723,
"s": 3581,
"text": "Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here &indicates the address of variavle x."
},
{
"code": null,
"e": 3950,
"s": 3723,
"text": "This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it will display an error message."
},
{
"code": null,
"e": 3983,
"s": 3950,
"text": "Enter an integer: 20\nRead in 20\n"
},
{
"code": null,
"e": 4059,
"s": 3983,
"text": "A complete set of input output functions is given in C - Built-in Functions"
},
{
"code": null,
"e": 4076,
"s": 4059,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 4110,
"s": 4076,
"text": "\n 6 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4134,
"s": 4110,
"text": " Mr. Pradeep Kshetrapal"
},
{
"code": null,
"e": 4167,
"s": 4134,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4179,
"s": 4167,
"text": " AR Shankar"
},
{
"code": null,
"e": 4211,
"s": 4179,
"text": "\n 11 Lectures \n 58 mins\n"
},
{
"code": null,
"e": 4227,
"s": 4211,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4263,
"s": 4227,
"text": "\n 59 Lectures \n 15.5 hours \n"
},
{
"code": null,
"e": 4275,
"s": 4263,
"text": " Narendra P"
},
{
"code": null,
"e": 4308,
"s": 4275,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4321,
"s": 4308,
"text": " Sagar Mehta"
},
{
"code": null,
"e": 4354,
"s": 4321,
"text": "\n 39 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4367,
"s": 4354,
"text": " Vikas Yadav"
},
{
"code": null,
"e": 4374,
"s": 4367,
"text": " Print"
},
{
"code": null,
"e": 4385,
"s": 4374,
"text": " Add Notes"
}
] |
How to Change the Style of <a> Tag Title Attribute ? - GeeksforGeeks | 16 Apr, 2020
The style of <a> (anchor) tag title attribute is pre-defined for the browser and it may differ from one browser to the other. The webpage cannot display the changes in the tool-tip if based on the title attribute.
The option is to make a false-tool-tip using CSS properties according to the wish. For doing this, the data-title attribute must be used. The data-* attributes method is used to store custom data which is private to the page or application. There are various ways of accessing them which can be used by CSS.
Example 1: This example makes tool-tip bigger and with a different background color.
<!DOCTYPE html> <html> <head> <title> How to Change the Style of Anchor Tag Title Attribute? </title> <style> [data-title]:hover:after { visibility: visible; } [data-title]:after { content: attr(data-title); background-color: #4b9c2c; color: #ffffff; font-size: 150%; position: absolute; padding: 4px 8px 4px 8px; visibility: hidden; } </style> </head> <body style="text-align:center;"> <h1 style="color:green"> GeeksforGeeks </h1> <h3> Change the Style of Anchor Tag Title Attribute </h3> <a href="geeksforgeeks.org" data-title="GFG"> Link </a> Title with different background color and style <br> <a href="geeksforgeeks.org" title="GFG"> Link </a> Title with a normal tool-tip</body> </html>
Output:
Example 2: The following example styles the tool-tip better than the last one using some better CSS properties.
<!DOCTYPE html> <html> <head> <title> How to Change the Style of Anchor Tag Title Attribute? </title> <style> [data-title]:hover:after { opacity: 1; transition: all 0.2s ease 0.6s; visibility: visible; } [data-title]:after { content: attr(data-title); position: absolute; padding: 4px 8px 4px 8px; color: #222; border-radius: 5px; box-shadow: 0px 0px 15px #222; background-image: -webkit-linear-gradient( top, #f8f8f8, #cccccc); background-image: -moz-linear-gradient( top, #f8f8f8, #cccccc); background-image: -ms-linear-gradient( top, #f8f8f8, #cccccc); background-image: -o-linear-gradient( top, #f8f8f8, #cccccc); visibility: hidden; } </style> </head> <body style="text-align:center;"> <h1 style="color:green"> GeeksforGeeks </h1> <h3> Change the Style of Anchor Tag Title Attribute </h3> <a href="geeksforgeeks.org" data-title="GFG"> Link </a> with styled tooltip <br> <a href="geeksforgeeks.org" title="GFG"> Link </a> with normal tooltip</body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML | [
{
"code": null,
"e": 26435,
"s": 26407,
"text": "\n16 Apr, 2020"
},
{
"code": null,
"e": 26649,
"s": 26435,
"text": "The style of <a> (anchor) tag title attribute is pre-defined for the browser and it may differ from one browser to the other. The webpage cannot display the changes in the tool-tip if based on the title attribute."
},
{
"code": null,
"e": 26957,
"s": 26649,
"text": "The option is to make a false-tool-tip using CSS properties according to the wish. For doing this, the data-title attribute must be used. The data-* attributes method is used to store custom data which is private to the page or application. There are various ways of accessing them which can be used by CSS."
},
{
"code": null,
"e": 27042,
"s": 26957,
"text": "Example 1: This example makes tool-tip bigger and with a different background color."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> How to Change the Style of Anchor Tag Title Attribute? </title> <style> [data-title]:hover:after { visibility: visible; } [data-title]:after { content: attr(data-title); background-color: #4b9c2c; color: #ffffff; font-size: 150%; position: absolute; padding: 4px 8px 4px 8px; visibility: hidden; } </style> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3> Change the Style of Anchor Tag Title Attribute </h3> <a href=\"geeksforgeeks.org\" data-title=\"GFG\"> Link </a> Title with different background color and style <br> <a href=\"geeksforgeeks.org\" title=\"GFG\"> Link </a> Title with a normal tool-tip</body> </html>",
"e": 28009,
"s": 27042,
"text": null
},
{
"code": null,
"e": 28017,
"s": 28009,
"text": "Output:"
},
{
"code": null,
"e": 28129,
"s": 28017,
"text": "Example 2: The following example styles the tool-tip better than the last one using some better CSS properties."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> How to Change the Style of Anchor Tag Title Attribute? </title> <style> [data-title]:hover:after { opacity: 1; transition: all 0.2s ease 0.6s; visibility: visible; } [data-title]:after { content: attr(data-title); position: absolute; padding: 4px 8px 4px 8px; color: #222; border-radius: 5px; box-shadow: 0px 0px 15px #222; background-image: -webkit-linear-gradient( top, #f8f8f8, #cccccc); background-image: -moz-linear-gradient( top, #f8f8f8, #cccccc); background-image: -ms-linear-gradient( top, #f8f8f8, #cccccc); background-image: -o-linear-gradient( top, #f8f8f8, #cccccc); visibility: hidden; } </style> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3> Change the Style of Anchor Tag Title Attribute </h3> <a href=\"geeksforgeeks.org\" data-title=\"GFG\"> Link </a> with styled tooltip <br> <a href=\"geeksforgeeks.org\" title=\"GFG\"> Link </a> with normal tooltip</body> </html>",
"e": 29676,
"s": 28129,
"text": null
},
{
"code": null,
"e": 29684,
"s": 29676,
"text": "Output:"
},
{
"code": null,
"e": 29821,
"s": 29684,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29830,
"s": 29821,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29840,
"s": 29830,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29847,
"s": 29840,
"text": "Picked"
},
{
"code": null,
"e": 29851,
"s": 29847,
"text": "CSS"
},
{
"code": null,
"e": 29856,
"s": 29851,
"text": "HTML"
},
{
"code": null,
"e": 29873,
"s": 29856,
"text": "Web Technologies"
},
{
"code": null,
"e": 29900,
"s": 29873,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29905,
"s": 29900,
"text": "HTML"
},
{
"code": null,
"e": 30003,
"s": 29905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30058,
"s": 30003,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30095,
"s": 30058,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30159,
"s": 30095,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30198,
"s": 30159,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30235,
"s": 30198,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30295,
"s": 30235,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30348,
"s": 30295,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30409,
"s": 30348,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30433,
"s": 30409,
"text": "REST API (Introduction)"
}
] |
Annotate Text Outside of ggplot2 Plot in R - GeeksforGeeks | 03 Mar, 2021
Ggplot2 is based on the grammar of graphics, the idea that you can build every graph from the same few components: a data set, a set of geoms—visual marks that represent data points, and a coordinate system. There are many scenarios where we need to annotate outside the plot area or specific area as per client requirements. In this case, the ggplot2 library comes very handy with its sub-options to get the required output and with good customization options for data visualizations.
To add annotations in R using ggplot2, annotate() function is used.
Syntax: annotate()
Parameters:
geom : specify text
x : x axis location
y : y axis location
label : custom textual content
color : color of textual content
size : size of text
fontface : fontface of text
angle : angle of text
Import library
Create or load dataset
Create a normal plot
Add annotate() function with required parameters
Let us first see how annotations are added inside the plot, so that the difference in position of the annotations can be understood better.
Examples :
R
library(ggplot2) Dt = iris ggplot(Dt,aes(x=Species,y=Sepal.Length)) + geom_bar(stat = "summary", fun = "mean") + annotate("text", x = 1, y = 7, label = "Arbitrary text") + coord_cartesian(ylim = c(0, 8), clip = "off")
Output:
Now let us visualize with annotations outside the plot.
Example:
R
library(ggplot2) Dt = iris ggplot(Dt,aes(x=Species,y=Sepal.Length)) + geom_bar(stat = "summary", fun = "mean") + annotate("text", x = 1, y = -1, label = "text") + coord_cartesian(ylim = c(0, 8), clip = "off")
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
R - if statement
How to filter R dataframe by multiple conditions?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 27084,
"s": 26597,
"text": "Ggplot2 is based on the grammar of graphics, the idea that you can build every graph from the same few components: a data set, a set of geoms—visual marks that represent data points, and a coordinate system. There are many scenarios where we need to annotate outside the plot area or specific area as per client requirements. In this case, the ggplot2 library comes very handy with its sub-options to get the required output and with good customization options for data visualizations. "
},
{
"code": null,
"e": 27152,
"s": 27084,
"text": "To add annotations in R using ggplot2, annotate() function is used."
},
{
"code": null,
"e": 27172,
"s": 27152,
"text": "Syntax: annotate() "
},
{
"code": null,
"e": 27184,
"s": 27172,
"text": "Parameters:"
},
{
"code": null,
"e": 27204,
"s": 27184,
"text": "geom : specify text"
},
{
"code": null,
"e": 27224,
"s": 27204,
"text": "x : x axis location"
},
{
"code": null,
"e": 27244,
"s": 27224,
"text": "y : y axis location"
},
{
"code": null,
"e": 27275,
"s": 27244,
"text": "label : custom textual content"
},
{
"code": null,
"e": 27308,
"s": 27275,
"text": "color : color of textual content"
},
{
"code": null,
"e": 27328,
"s": 27308,
"text": "size : size of text"
},
{
"code": null,
"e": 27356,
"s": 27328,
"text": "fontface : fontface of text"
},
{
"code": null,
"e": 27378,
"s": 27356,
"text": "angle : angle of text"
},
{
"code": null,
"e": 27393,
"s": 27378,
"text": "Import library"
},
{
"code": null,
"e": 27416,
"s": 27393,
"text": "Create or load dataset"
},
{
"code": null,
"e": 27437,
"s": 27416,
"text": "Create a normal plot"
},
{
"code": null,
"e": 27486,
"s": 27437,
"text": "Add annotate() function with required parameters"
},
{
"code": null,
"e": 27626,
"s": 27486,
"text": "Let us first see how annotations are added inside the plot, so that the difference in position of the annotations can be understood better."
},
{
"code": null,
"e": 27638,
"s": 27626,
"text": "Examples : "
},
{
"code": null,
"e": 27640,
"s": 27638,
"text": "R"
},
{
"code": "library(ggplot2) Dt = iris ggplot(Dt,aes(x=Species,y=Sepal.Length)) + geom_bar(stat = \"summary\", fun = \"mean\") + annotate(\"text\", x = 1, y = 7, label = \"Arbitrary text\") + coord_cartesian(ylim = c(0, 8), clip = \"off\")",
"e": 27862,
"s": 27640,
"text": null
},
{
"code": null,
"e": 27870,
"s": 27862,
"text": "Output:"
},
{
"code": null,
"e": 27926,
"s": 27870,
"text": "Now let us visualize with annotations outside the plot."
},
{
"code": null,
"e": 27935,
"s": 27926,
"text": "Example:"
},
{
"code": null,
"e": 27937,
"s": 27935,
"text": "R"
},
{
"code": "library(ggplot2) Dt = iris ggplot(Dt,aes(x=Species,y=Sepal.Length)) + geom_bar(stat = \"summary\", fun = \"mean\") + annotate(\"text\", x = 1, y = -1, label = \"text\") + coord_cartesian(ylim = c(0, 8), clip = \"off\")",
"e": 28151,
"s": 27937,
"text": null
},
{
"code": null,
"e": 28159,
"s": 28151,
"text": "Output:"
},
{
"code": null,
"e": 28166,
"s": 28159,
"text": "Picked"
},
{
"code": null,
"e": 28175,
"s": 28166,
"text": "R-ggplot"
},
{
"code": null,
"e": 28186,
"s": 28175,
"text": "R Language"
},
{
"code": null,
"e": 28284,
"s": 28186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28336,
"s": 28284,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28371,
"s": 28336,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28429,
"s": 28371,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28467,
"s": 28429,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28510,
"s": 28467,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28527,
"s": 28510,
"text": "R - if statement"
},
{
"code": null,
"e": 28577,
"s": 28527,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 28626,
"s": 28577,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28663,
"s": 28626,
"text": "How to import an Excel File into R ?"
}
] |
Using Python and Selenium to get coordinates from street addresses | by Khalid El Mouloudi | Towards Data Science | This is a step by step article on how to use Python and Selenium to scrape coordinates data (Latitude and Longitude values) from Google Maps based on street addresses.
In this case example, I’m going to work with an official dataset containing the street addresses of all Australian charities and nonprofits. At the end, I’ll proceed to map all the charities and nonprofits in the city of Melbourne using Folium, to demonstrate what can be done with the newly acquired coordinates data.
To follow along, you can download the Jupyter Notebook from my GitHub repository.
We’ll need the Selenium python package to perform the data scraping. If you don’t have it yet, you can install it using pip: pip install selenium .
We’ll also need a WebDriver in order to interact with the browser, so you have to go here and download it to your machine (make sure it’s compatible with your current Chrome version).
Now let’s do the import :
from selenium import webdriver
Let’s also get tqdm, an essential progressbar python package. It is very useful to estimate how much time the web scraping part of your code will take (i’m using tqdm_notebook because I’m working in a Jupyter Notebook) :
from tqdm import tqdm_notebook as tqdmn
In addition to that, we’ll need Pandas to read and manipulate the dataset :
import pandas as pd
Finally, we’ll get Folium to map coordinates data on a map (it can be installed using pip install folium):
import folium
I’ll be working in a Jupyter Notebook (you can download it here). All these steps still apply if you’re working in a python IDE instead.
Australia is ranked 4th worldwide by the CAF World Giving Index in its 10th edition that covers the last 10 years. By visiting the ACNC’s website, you’ll quickly notice how easy they make it for researchers to access all the data about charities and nonprofits in Australia.
The dataset we’ll be using can be downloaded here (along with a useful user notes document explaining the variables ):
ACNC Charity Register dataset [Excel file XLSX | 7.7 Mb | 74155 rows and 60 columns as of 23/01/2020]
The dataset presents many interesting aspects about the charities and nonprofits in Australia: unique identifier, legal name, address (for correspondence), registration date, size, purpose, beneficiaries and more (read the user notes for more info).
Here, we’re mainly interested in the street address features which span several columns: Address_Line_1, Address_Line_2, Address_Line_3, Town_City, State, Postcode and Country. Also, for simplicity, we will only look into charities and nonprofits in the city of Melbourne.
First, let’s read in the dataset we previously downloaded from the ACNC website using Pandas :
Make sure to supply the path where the Excel file resides on your machine. The keep_default_na parameter is set to False so we’ll get empty values instead of NaN when certain values are missing. This will be useful later when we’ll combine all the street address variables into one variable.
Now, let’s make a new dataframe mel as a copy of acnc after filtering it by the variable Town_City to only select the charities and nonprofits in the city of Melbourne :
mel = acnc[acnc.Town_City.str.contains('melbourne', case=False)][['ABN', 'Charity_Legal_Name', 'Address_Line_1', 'Address_Line_2', 'Address_Line_3', 'Town_City', 'State', 'Postcode', 'Country', 'Date_Organisation_Established', 'Charity_Size']].copy()
I did two things here: I filtered the acnc dataframe by the Town_City variable, and then I only selected 11 useful columns out of the 60 we initially had. copy() makes sure we made a proper copy of the filtered acnc dataframe.
I didn’t use acnc[acnc.Town_City == 'Melbourne'] here because I suspected it may have been written in different ways. To make sure this was necessary :
mel.Town_City.value_counts()
As we can see above, the column contained different ways of indicating that a charity is indeed situated in Melbourne, some of which using suburbs or even very specific places in the city like The University of Melbourne. By using acnc.Town_City.str.contains('melbourne', case=False) , we insured all of the above charities are accounted for (otherwise we would only get the 1779 ones correctly labeled).
Let’s see how our new mel dataframe looks like :
mel.head()
And now, let’s add a new column Full_Address containing the full address :
mel['Full_Address'] = mel['Address_Line_1'].str.cat( mel[['Address_Line_2', 'Address_Line_3', 'Town_City']], sep=' ')
str.cat() works here because all of these columns are of type object or string.
Here’s an example of the very first full address in mel :
mel.Full_Address.iloc[0]Output:'G Se 11 431 St Kilda Rd Melbourne'
One more thing: some of these full addresses only contain the Post Office Box number (mentioned as GPO Box or Po Box). These addresses are completely useless to us because they don’t refer to an existing place. Here’s an example :
mel[mel.Full_Address.str.contains('po box', case=False)].Full_Address.iloc[0]Output:'GPO Box 2307 Melbourne VIC 3001 AUSTRALIA'
We need to remove these records (or rows) before proceeding :
mel = mel[~mel.Full_Address.str.contains('po box', case=False)].copy()
One last thing: some addresses contain the character / which can break any URL. We need to substitute any slash with a space :
mel.Full_Address = mel.Full_Address.str.replace('/', ' ')
Before any web scraping job, it is essential to explore the website you want to extract data from. In our case, it’s Google Maps.
First, let’s study how searching for a full address using the search bar inside Google Maps affects the URL of the result page. For this, I’ll go with the fictitious address Grinch house mount crumpit whoville because I want Google Maps to return no results :
As you can see above, we get www.google.com/maps/search/followed by the address we searched for. In other words, if we want to search for an address XYZ within Google Maps, all we have to do is use the URL www.google.com/maps/search/XYZ, without having to interact with the search bar itself.
The idea here is to generate a new column within mel where we combine www.google.com/maps/search/ with every Full_Address we have in our dataframe mel, and then have Selenium iterate over them visiting the URLs one after the other.
Let’s create that new Url column :
mel['Url'] = ['https://www.google.com/maps/search/' + i for i in mel['Full_Address'] ]
Now that we have a column containing all the URLs we want to crawl, let’s take a look at the address G Se 11 431 St Kilda Rd Melbourne for example :
www.google.com/maps/search/G Se 11 431 St Kilda Rd Melbourne
The above link gives us :
The above address corresponds to the charity Australian Nurses Memorial Centre. Let’s search for it on Google Maps by name :
We get the exact same spot, but not the same coordinates in the URL. That’s because the coordinates in the URL are linked to how the map is centered and not to the marker (they change if you zoom in or out). That’s why we’re going to extract the coordinates directly from the source code of the page itself.
To view the source code, right click on a blank space within the page (outside of the map) and choose View Page Source (CTRL+U or Command+U in Mac). Now search for -37.8 or 144.9 within the source page :
You’ll find the coordinates we are seeking in many places throughout the hot mess that is the source code. But they are mostly useful to us if they are comprised within an HTML tag we can target. Luckily, there is one meta tag we can make useful here :
For now, let’s note that it’s a meta tag with an attribute content containing the URL we want to extract, and an attribute itemprop with the value image which can be used to identify and target this particular meta tag.
Now all we have to do is use Selenium to visit each URL in mel.Url and target this meta tag in order to extract the value of its attribute content.
Here is the code we’ll use to extract the URLs containing the coordinates from Google Maps :
Line 1: we make an empty list called Url_With_Coordinates, which we will fill later on with (you guessed it) the URLs we want to extract ;
Lines 3 to 5 : prefs to run the Webdriver without javascript and images. This way the code will take much less time to load webpages. Obviously, this isn’t a good choice if what you want to extract relies on javascript. By removing 'images':2, 'javascript':2, the web pages will load images and javascript normally ;
Line 7: make sure to specify where you put the chromedriver.exe file in your machine. In my case I put it in the C drive for simplicity. Note that backlashes \ in the path need to be doubled \\ for the path to be recognized ;
Line 9: this for loop is iterating over the mel.Url series. The tqdmn() wrapping our iterable adds a progress bar right after the cell is executed. Its parameter leave=False makes sure the bar goes away once the operation is finished ;
Line 10: for each URL in mel.Url, the webdriver opens that URL (for the first URL you’ll see a chrome window open, and then you’ll notice it going from URL to URL until mel.Url is finished) ;
Line 11: first, we search for our meta tag using driver.find_element_by_css_selector and we identify the tag by meta[itemprop=image]. After that, we extract the value of the attribute content using .get_attribute('content'). The result of this operation (the URL containing the coordinates) is then added to the Url_With_Coordinates list using append().
Line 13: we close the webdriver (chrome window) after the script is finished (this is a good practice).
Here’s the script and the tqdm progress bar in action (or tqdmn because I’m using the tqdm_notebook submodule) :
NB 1: the next time you run the notebook, you don’t have to rerun the web scraping code all over again because we have saved the result in a CSV file called Url_With_Coordinates.csv. Let's read in that file instead :
import csvwith open('Url_With_Coordinates.csv', 'r') as f: reader = csv.reader(f, delimiter=',') for i in reader: Url_With_Coordinates = i break
NB 2: in your tests, you don’t want to make the for loop iterate over thousands of addresses only for it to throw you an error at the end. You need to test it first on a couple of values before properly executing the script. In our case, the test code will be like this to only go over the first 10 values of mel.Url :
for url in tqdmn(mel.Url[:10], leave=False): driver.get(url) ......
Now let’s see what the Url_With_Coordinates list looks like :
Let’s add this list as a column in our mel dataframe :
mel['Url_With_Coordinates'] = Url_With_Coordinates
But how are we supposed to extract just the coordinates from these URLs? Here’s a visual explanation on how to use Python’s split() method for this purpose :
Which translates in code to the following (this code won’t run because url is not defined, it’s just to show how the above solution would work):
url.split('?center=')[1].split('&zoom=')[0].split('%2C')Output:[-37.8386737, 144.97706]
Now using the code above, we’re going to add two new columns to our mel dataframe: lat for latitudes and long for longitudes :
mel['lat'] = [ url.split('?center=')[1].split('&zoom=')[0].split('%2C')[0] for url in mel['Url_With_Coordinates'] ]mel['long'] = [url.split('?center=')[1].split('&zoom=')[0].split('%2C')[1] for url in mel['Url_With_Coordinates'] ]
Most likely, the above code gave you an error list index out of range :
What this error means is that the split() method didn't work as intended with some URLs in the column Url_With_Coordinates. Perhaps some URLs didn't have the keywords we used for the split() method. Let's look for the URLs that lack &zoom= for example :
mel[~mel.Url_With_Coordinates.str.contains('&zoom=')]
As we can see here, we have 5 instances where the extracted URL starts with //www.gstatic.com/images ... (hence the error we got) :
list(mel[~mel.Url_With_Coordinates.str.contains('&zoom=')].Url_With_Coordinates)Output:['//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png', '//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png', '//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png', '//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png', '//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png']
For simplicity, and because 5 isn’t a big number, we’ll remove these instances from mel :
mel = mel[mel.Url_With_Coordinates.str.contains('&zoom=')].copy()
Now, let’s rerun the code that adds two columns lat and long to our mel dataframe :
mel['lat'] = [ url.split('?center=')[1].split('&zoom=')[0].split('%2C')[0] for url in mel['Url_With_Coordinates'] ]mel['long'] = [url.split('?center=')[1].split('&zoom=')[0].split('%2C')[1] for url in mel['Url_With_Coordinates'] ]
It worked! Here’s how our mel dataframe looks like, where each charity or nonprofit gets it latitude and longitude values (some columns here are masked) :
mel.head()
Let’s map these coordinates to see how accurate they can be.
Color coding (charity size depends on annual income) :
Red: Large charities (1 Million AUD or more) ;
Purple: Medium charities (between 250.000 AUD and 1 Million AUD) ;
Orange: Small charities (less than 250.000 AUD);
Grey: no data.
Here’s the code we’ll use to map these coordinates :
I’m not going into great detail on how to use Folium, but I’ll just clarify some points here :
I used CartoDB positron for this map because it provides very low contrast against the colored markers (it makes them more visible). Using the default tiles OpenStreetMap makes it difficult to see the markers ;
I changed the size of the marker based on the size of the charity using the parameter icon_size=(..,..) of folium.CustomIcon. The reason behind this is to prevent charities that reside in the same building from masking each other. Because Large markers are drawn first, smaller markers are drawn on top of them so that even overlapping charities can still be distinguished ;
I used custom markers (hosted on imgur) because the default one tends to slow navigation down a lot since we have around 2000 markers on the map. For custom markers, you can provide a URL to the image you want to use, or the path to the image file on your machine ;
If you click on a marker, it gives you the name of the charity and its address, so you can verify if the positioning is correct ;
In the code above, I could have used just mel_map instead of mel_map.save('mel_map.html') followed by IFrame(src='mel_map.html', width='100%', height=500), but when the number of markers is big, it's better to save the map as an HTML file and then open it using IFrame() (otherwise you'll get a blank map).
This is a very legitimate question. Obviously, the best way to get coordinates out of street addresses is from a reputable API like Google Maps’s or Bing’s, but these options can cost money.
The accuracy of this method is heavily influenced by the precision and correctness of the street addresses provided. For instance, in our example above, you’ll notice one marker thrown away in the middle of the Indian Ocean. Upon examination, the address 65 Macarae Road Melbourne is actually supposed to be 65 Mcrae Road Melbourne, hence the error.
To empirically test our method, we are going to use a dataset containing both the street addresses and the coordinates of thousands of businesses in Washington DC. We’ll proceed to take a random sample of 500 business addresses and then we’ll use our method to generate coordinates out of them. After that, we’ll compare them to the actual coordinates listed in the dataset. The dataset we’ll use for our test can be downloaded here :
Basic Business License in Last 30 Days: opendata.dc.gov dataset, 6418 records (as of 26/01/2020), 2.64 Mb
And the results are in (the test details are available in the Jupyter Notebook) :
As we can see above, the generated coordinates are very close to the actual coordinates in this random sample of 500 businesses in Washington DC. I made the orange marker smaller than the red one so they’ll both be visible when they overlap perfectly (that’s why it looks like the orange markers have a red border when zooming out). | [
{
"code": null,
"e": 215,
"s": 47,
"text": "This is a step by step article on how to use Python and Selenium to scrape coordinates data (Latitude and Longitude values) from Google Maps based on street addresses."
},
{
"code": null,
"e": 534,
"s": 215,
"text": "In this case example, I’m going to work with an official dataset containing the street addresses of all Australian charities and nonprofits. At the end, I’ll proceed to map all the charities and nonprofits in the city of Melbourne using Folium, to demonstrate what can be done with the newly acquired coordinates data."
},
{
"code": null,
"e": 616,
"s": 534,
"text": "To follow along, you can download the Jupyter Notebook from my GitHub repository."
},
{
"code": null,
"e": 764,
"s": 616,
"text": "We’ll need the Selenium python package to perform the data scraping. If you don’t have it yet, you can install it using pip: pip install selenium ."
},
{
"code": null,
"e": 948,
"s": 764,
"text": "We’ll also need a WebDriver in order to interact with the browser, so you have to go here and download it to your machine (make sure it’s compatible with your current Chrome version)."
},
{
"code": null,
"e": 974,
"s": 948,
"text": "Now let’s do the import :"
},
{
"code": null,
"e": 1005,
"s": 974,
"text": "from selenium import webdriver"
},
{
"code": null,
"e": 1226,
"s": 1005,
"text": "Let’s also get tqdm, an essential progressbar python package. It is very useful to estimate how much time the web scraping part of your code will take (i’m using tqdm_notebook because I’m working in a Jupyter Notebook) :"
},
{
"code": null,
"e": 1266,
"s": 1226,
"text": "from tqdm import tqdm_notebook as tqdmn"
},
{
"code": null,
"e": 1342,
"s": 1266,
"text": "In addition to that, we’ll need Pandas to read and manipulate the dataset :"
},
{
"code": null,
"e": 1362,
"s": 1342,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1469,
"s": 1362,
"text": "Finally, we’ll get Folium to map coordinates data on a map (it can be installed using pip install folium):"
},
{
"code": null,
"e": 1483,
"s": 1469,
"text": "import folium"
},
{
"code": null,
"e": 1620,
"s": 1483,
"text": "I’ll be working in a Jupyter Notebook (you can download it here). All these steps still apply if you’re working in a python IDE instead."
},
{
"code": null,
"e": 1895,
"s": 1620,
"text": "Australia is ranked 4th worldwide by the CAF World Giving Index in its 10th edition that covers the last 10 years. By visiting the ACNC’s website, you’ll quickly notice how easy they make it for researchers to access all the data about charities and nonprofits in Australia."
},
{
"code": null,
"e": 2014,
"s": 1895,
"text": "The dataset we’ll be using can be downloaded here (along with a useful user notes document explaining the variables ):"
},
{
"code": null,
"e": 2116,
"s": 2014,
"text": "ACNC Charity Register dataset [Excel file XLSX | 7.7 Mb | 74155 rows and 60 columns as of 23/01/2020]"
},
{
"code": null,
"e": 2366,
"s": 2116,
"text": "The dataset presents many interesting aspects about the charities and nonprofits in Australia: unique identifier, legal name, address (for correspondence), registration date, size, purpose, beneficiaries and more (read the user notes for more info)."
},
{
"code": null,
"e": 2639,
"s": 2366,
"text": "Here, we’re mainly interested in the street address features which span several columns: Address_Line_1, Address_Line_2, Address_Line_3, Town_City, State, Postcode and Country. Also, for simplicity, we will only look into charities and nonprofits in the city of Melbourne."
},
{
"code": null,
"e": 2734,
"s": 2639,
"text": "First, let’s read in the dataset we previously downloaded from the ACNC website using Pandas :"
},
{
"code": null,
"e": 3026,
"s": 2734,
"text": "Make sure to supply the path where the Excel file resides on your machine. The keep_default_na parameter is set to False so we’ll get empty values instead of NaN when certain values are missing. This will be useful later when we’ll combine all the street address variables into one variable."
},
{
"code": null,
"e": 3196,
"s": 3026,
"text": "Now, let’s make a new dataframe mel as a copy of acnc after filtering it by the variable Town_City to only select the charities and nonprofits in the city of Melbourne :"
},
{
"code": null,
"e": 3447,
"s": 3196,
"text": "mel = acnc[acnc.Town_City.str.contains('melbourne', case=False)][['ABN', 'Charity_Legal_Name', 'Address_Line_1', 'Address_Line_2', 'Address_Line_3', 'Town_City', 'State', 'Postcode', 'Country', 'Date_Organisation_Established', 'Charity_Size']].copy()"
},
{
"code": null,
"e": 3674,
"s": 3447,
"text": "I did two things here: I filtered the acnc dataframe by the Town_City variable, and then I only selected 11 useful columns out of the 60 we initially had. copy() makes sure we made a proper copy of the filtered acnc dataframe."
},
{
"code": null,
"e": 3826,
"s": 3674,
"text": "I didn’t use acnc[acnc.Town_City == 'Melbourne'] here because I suspected it may have been written in different ways. To make sure this was necessary :"
},
{
"code": null,
"e": 3855,
"s": 3826,
"text": "mel.Town_City.value_counts()"
},
{
"code": null,
"e": 4260,
"s": 3855,
"text": "As we can see above, the column contained different ways of indicating that a charity is indeed situated in Melbourne, some of which using suburbs or even very specific places in the city like The University of Melbourne. By using acnc.Town_City.str.contains('melbourne', case=False) , we insured all of the above charities are accounted for (otherwise we would only get the 1779 ones correctly labeled)."
},
{
"code": null,
"e": 4309,
"s": 4260,
"text": "Let’s see how our new mel dataframe looks like :"
},
{
"code": null,
"e": 4320,
"s": 4309,
"text": "mel.head()"
},
{
"code": null,
"e": 4395,
"s": 4320,
"text": "And now, let’s add a new column Full_Address containing the full address :"
},
{
"code": null,
"e": 4513,
"s": 4395,
"text": "mel['Full_Address'] = mel['Address_Line_1'].str.cat( mel[['Address_Line_2', 'Address_Line_3', 'Town_City']], sep=' ')"
},
{
"code": null,
"e": 4593,
"s": 4513,
"text": "str.cat() works here because all of these columns are of type object or string."
},
{
"code": null,
"e": 4651,
"s": 4593,
"text": "Here’s an example of the very first full address in mel :"
},
{
"code": null,
"e": 4720,
"s": 4651,
"text": "mel.Full_Address.iloc[0]Output:'G Se 11 431 St Kilda Rd Melbourne'"
},
{
"code": null,
"e": 4951,
"s": 4720,
"text": "One more thing: some of these full addresses only contain the Post Office Box number (mentioned as GPO Box or Po Box). These addresses are completely useless to us because they don’t refer to an existing place. Here’s an example :"
},
{
"code": null,
"e": 5081,
"s": 4951,
"text": "mel[mel.Full_Address.str.contains('po box', case=False)].Full_Address.iloc[0]Output:'GPO Box 2307 Melbourne VIC 3001 AUSTRALIA'"
},
{
"code": null,
"e": 5143,
"s": 5081,
"text": "We need to remove these records (or rows) before proceeding :"
},
{
"code": null,
"e": 5214,
"s": 5143,
"text": "mel = mel[~mel.Full_Address.str.contains('po box', case=False)].copy()"
},
{
"code": null,
"e": 5341,
"s": 5214,
"text": "One last thing: some addresses contain the character / which can break any URL. We need to substitute any slash with a space :"
},
{
"code": null,
"e": 5399,
"s": 5341,
"text": "mel.Full_Address = mel.Full_Address.str.replace('/', ' ')"
},
{
"code": null,
"e": 5529,
"s": 5399,
"text": "Before any web scraping job, it is essential to explore the website you want to extract data from. In our case, it’s Google Maps."
},
{
"code": null,
"e": 5789,
"s": 5529,
"text": "First, let’s study how searching for a full address using the search bar inside Google Maps affects the URL of the result page. For this, I’ll go with the fictitious address Grinch house mount crumpit whoville because I want Google Maps to return no results :"
},
{
"code": null,
"e": 6082,
"s": 5789,
"text": "As you can see above, we get www.google.com/maps/search/followed by the address we searched for. In other words, if we want to search for an address XYZ within Google Maps, all we have to do is use the URL www.google.com/maps/search/XYZ, without having to interact with the search bar itself."
},
{
"code": null,
"e": 6314,
"s": 6082,
"text": "The idea here is to generate a new column within mel where we combine www.google.com/maps/search/ with every Full_Address we have in our dataframe mel, and then have Selenium iterate over them visiting the URLs one after the other."
},
{
"code": null,
"e": 6349,
"s": 6314,
"text": "Let’s create that new Url column :"
},
{
"code": null,
"e": 6436,
"s": 6349,
"text": "mel['Url'] = ['https://www.google.com/maps/search/' + i for i in mel['Full_Address'] ]"
},
{
"code": null,
"e": 6585,
"s": 6436,
"text": "Now that we have a column containing all the URLs we want to crawl, let’s take a look at the address G Se 11 431 St Kilda Rd Melbourne for example :"
},
{
"code": null,
"e": 6646,
"s": 6585,
"text": "www.google.com/maps/search/G Se 11 431 St Kilda Rd Melbourne"
},
{
"code": null,
"e": 6672,
"s": 6646,
"text": "The above link gives us :"
},
{
"code": null,
"e": 6797,
"s": 6672,
"text": "The above address corresponds to the charity Australian Nurses Memorial Centre. Let’s search for it on Google Maps by name :"
},
{
"code": null,
"e": 7105,
"s": 6797,
"text": "We get the exact same spot, but not the same coordinates in the URL. That’s because the coordinates in the URL are linked to how the map is centered and not to the marker (they change if you zoom in or out). That’s why we’re going to extract the coordinates directly from the source code of the page itself."
},
{
"code": null,
"e": 7309,
"s": 7105,
"text": "To view the source code, right click on a blank space within the page (outside of the map) and choose View Page Source (CTRL+U or Command+U in Mac). Now search for -37.8 or 144.9 within the source page :"
},
{
"code": null,
"e": 7562,
"s": 7309,
"text": "You’ll find the coordinates we are seeking in many places throughout the hot mess that is the source code. But they are mostly useful to us if they are comprised within an HTML tag we can target. Luckily, there is one meta tag we can make useful here :"
},
{
"code": null,
"e": 7782,
"s": 7562,
"text": "For now, let’s note that it’s a meta tag with an attribute content containing the URL we want to extract, and an attribute itemprop with the value image which can be used to identify and target this particular meta tag."
},
{
"code": null,
"e": 7930,
"s": 7782,
"text": "Now all we have to do is use Selenium to visit each URL in mel.Url and target this meta tag in order to extract the value of its attribute content."
},
{
"code": null,
"e": 8023,
"s": 7930,
"text": "Here is the code we’ll use to extract the URLs containing the coordinates from Google Maps :"
},
{
"code": null,
"e": 8162,
"s": 8023,
"text": "Line 1: we make an empty list called Url_With_Coordinates, which we will fill later on with (you guessed it) the URLs we want to extract ;"
},
{
"code": null,
"e": 8479,
"s": 8162,
"text": "Lines 3 to 5 : prefs to run the Webdriver without javascript and images. This way the code will take much less time to load webpages. Obviously, this isn’t a good choice if what you want to extract relies on javascript. By removing 'images':2, 'javascript':2, the web pages will load images and javascript normally ;"
},
{
"code": null,
"e": 8705,
"s": 8479,
"text": "Line 7: make sure to specify where you put the chromedriver.exe file in your machine. In my case I put it in the C drive for simplicity. Note that backlashes \\ in the path need to be doubled \\\\ for the path to be recognized ;"
},
{
"code": null,
"e": 8941,
"s": 8705,
"text": "Line 9: this for loop is iterating over the mel.Url series. The tqdmn() wrapping our iterable adds a progress bar right after the cell is executed. Its parameter leave=False makes sure the bar goes away once the operation is finished ;"
},
{
"code": null,
"e": 9133,
"s": 8941,
"text": "Line 10: for each URL in mel.Url, the webdriver opens that URL (for the first URL you’ll see a chrome window open, and then you’ll notice it going from URL to URL until mel.Url is finished) ;"
},
{
"code": null,
"e": 9487,
"s": 9133,
"text": "Line 11: first, we search for our meta tag using driver.find_element_by_css_selector and we identify the tag by meta[itemprop=image]. After that, we extract the value of the attribute content using .get_attribute('content'). The result of this operation (the URL containing the coordinates) is then added to the Url_With_Coordinates list using append()."
},
{
"code": null,
"e": 9591,
"s": 9487,
"text": "Line 13: we close the webdriver (chrome window) after the script is finished (this is a good practice)."
},
{
"code": null,
"e": 9704,
"s": 9591,
"text": "Here’s the script and the tqdm progress bar in action (or tqdmn because I’m using the tqdm_notebook submodule) :"
},
{
"code": null,
"e": 9921,
"s": 9704,
"text": "NB 1: the next time you run the notebook, you don’t have to rerun the web scraping code all over again because we have saved the result in a CSV file called Url_With_Coordinates.csv. Let's read in that file instead :"
},
{
"code": null,
"e": 10086,
"s": 9921,
"text": "import csvwith open('Url_With_Coordinates.csv', 'r') as f: reader = csv.reader(f, delimiter=',') for i in reader: Url_With_Coordinates = i break"
},
{
"code": null,
"e": 10405,
"s": 10086,
"text": "NB 2: in your tests, you don’t want to make the for loop iterate over thousands of addresses only for it to throw you an error at the end. You need to test it first on a couple of values before properly executing the script. In our case, the test code will be like this to only go over the first 10 values of mel.Url :"
},
{
"code": null,
"e": 10479,
"s": 10405,
"text": "for url in tqdmn(mel.Url[:10], leave=False): driver.get(url) ......"
},
{
"code": null,
"e": 10541,
"s": 10479,
"text": "Now let’s see what the Url_With_Coordinates list looks like :"
},
{
"code": null,
"e": 10596,
"s": 10541,
"text": "Let’s add this list as a column in our mel dataframe :"
},
{
"code": null,
"e": 10647,
"s": 10596,
"text": "mel['Url_With_Coordinates'] = Url_With_Coordinates"
},
{
"code": null,
"e": 10805,
"s": 10647,
"text": "But how are we supposed to extract just the coordinates from these URLs? Here’s a visual explanation on how to use Python’s split() method for this purpose :"
},
{
"code": null,
"e": 10950,
"s": 10805,
"text": "Which translates in code to the following (this code won’t run because url is not defined, it’s just to show how the above solution would work):"
},
{
"code": null,
"e": 11038,
"s": 10950,
"text": "url.split('?center=')[1].split('&zoom=')[0].split('%2C')Output:[-37.8386737, 144.97706]"
},
{
"code": null,
"e": 11165,
"s": 11038,
"text": "Now using the code above, we’re going to add two new columns to our mel dataframe: lat for latitudes and long for longitudes :"
},
{
"code": null,
"e": 11396,
"s": 11165,
"text": "mel['lat'] = [ url.split('?center=')[1].split('&zoom=')[0].split('%2C')[0] for url in mel['Url_With_Coordinates'] ]mel['long'] = [url.split('?center=')[1].split('&zoom=')[0].split('%2C')[1] for url in mel['Url_With_Coordinates'] ]"
},
{
"code": null,
"e": 11468,
"s": 11396,
"text": "Most likely, the above code gave you an error list index out of range :"
},
{
"code": null,
"e": 11722,
"s": 11468,
"text": "What this error means is that the split() method didn't work as intended with some URLs in the column Url_With_Coordinates. Perhaps some URLs didn't have the keywords we used for the split() method. Let's look for the URLs that lack &zoom= for example :"
},
{
"code": null,
"e": 11776,
"s": 11722,
"text": "mel[~mel.Url_With_Coordinates.str.contains('&zoom=')]"
},
{
"code": null,
"e": 11908,
"s": 11776,
"text": "As we can see here, we have 5 instances where the extracted URL starts with //www.gstatic.com/images ... (hence the error we got) :"
},
{
"code": null,
"e": 12341,
"s": 11908,
"text": "list(mel[~mel.Url_With_Coordinates.str.contains('&zoom=')].Url_With_Coordinates)Output:['//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png', '//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png', '//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png', '//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png', '//www.gstatic.com/images/branding/product/1x/maps_round_512dp.png']"
},
{
"code": null,
"e": 12431,
"s": 12341,
"text": "For simplicity, and because 5 isn’t a big number, we’ll remove these instances from mel :"
},
{
"code": null,
"e": 12497,
"s": 12431,
"text": "mel = mel[mel.Url_With_Coordinates.str.contains('&zoom=')].copy()"
},
{
"code": null,
"e": 12581,
"s": 12497,
"text": "Now, let’s rerun the code that adds two columns lat and long to our mel dataframe :"
},
{
"code": null,
"e": 12812,
"s": 12581,
"text": "mel['lat'] = [ url.split('?center=')[1].split('&zoom=')[0].split('%2C')[0] for url in mel['Url_With_Coordinates'] ]mel['long'] = [url.split('?center=')[1].split('&zoom=')[0].split('%2C')[1] for url in mel['Url_With_Coordinates'] ]"
},
{
"code": null,
"e": 12967,
"s": 12812,
"text": "It worked! Here’s how our mel dataframe looks like, where each charity or nonprofit gets it latitude and longitude values (some columns here are masked) :"
},
{
"code": null,
"e": 12978,
"s": 12967,
"text": "mel.head()"
},
{
"code": null,
"e": 13039,
"s": 12978,
"text": "Let’s map these coordinates to see how accurate they can be."
},
{
"code": null,
"e": 13094,
"s": 13039,
"text": "Color coding (charity size depends on annual income) :"
},
{
"code": null,
"e": 13141,
"s": 13094,
"text": "Red: Large charities (1 Million AUD or more) ;"
},
{
"code": null,
"e": 13208,
"s": 13141,
"text": "Purple: Medium charities (between 250.000 AUD and 1 Million AUD) ;"
},
{
"code": null,
"e": 13257,
"s": 13208,
"text": "Orange: Small charities (less than 250.000 AUD);"
},
{
"code": null,
"e": 13272,
"s": 13257,
"text": "Grey: no data."
},
{
"code": null,
"e": 13325,
"s": 13272,
"text": "Here’s the code we’ll use to map these coordinates :"
},
{
"code": null,
"e": 13420,
"s": 13325,
"text": "I’m not going into great detail on how to use Folium, but I’ll just clarify some points here :"
},
{
"code": null,
"e": 13631,
"s": 13420,
"text": "I used CartoDB positron for this map because it provides very low contrast against the colored markers (it makes them more visible). Using the default tiles OpenStreetMap makes it difficult to see the markers ;"
},
{
"code": null,
"e": 14006,
"s": 13631,
"text": "I changed the size of the marker based on the size of the charity using the parameter icon_size=(..,..) of folium.CustomIcon. The reason behind this is to prevent charities that reside in the same building from masking each other. Because Large markers are drawn first, smaller markers are drawn on top of them so that even overlapping charities can still be distinguished ;"
},
{
"code": null,
"e": 14272,
"s": 14006,
"text": "I used custom markers (hosted on imgur) because the default one tends to slow navigation down a lot since we have around 2000 markers on the map. For custom markers, you can provide a URL to the image you want to use, or the path to the image file on your machine ;"
},
{
"code": null,
"e": 14402,
"s": 14272,
"text": "If you click on a marker, it gives you the name of the charity and its address, so you can verify if the positioning is correct ;"
},
{
"code": null,
"e": 14709,
"s": 14402,
"text": "In the code above, I could have used just mel_map instead of mel_map.save('mel_map.html') followed by IFrame(src='mel_map.html', width='100%', height=500), but when the number of markers is big, it's better to save the map as an HTML file and then open it using IFrame() (otherwise you'll get a blank map)."
},
{
"code": null,
"e": 14900,
"s": 14709,
"text": "This is a very legitimate question. Obviously, the best way to get coordinates out of street addresses is from a reputable API like Google Maps’s or Bing’s, but these options can cost money."
},
{
"code": null,
"e": 15250,
"s": 14900,
"text": "The accuracy of this method is heavily influenced by the precision and correctness of the street addresses provided. For instance, in our example above, you’ll notice one marker thrown away in the middle of the Indian Ocean. Upon examination, the address 65 Macarae Road Melbourne is actually supposed to be 65 Mcrae Road Melbourne, hence the error."
},
{
"code": null,
"e": 15685,
"s": 15250,
"text": "To empirically test our method, we are going to use a dataset containing both the street addresses and the coordinates of thousands of businesses in Washington DC. We’ll proceed to take a random sample of 500 business addresses and then we’ll use our method to generate coordinates out of them. After that, we’ll compare them to the actual coordinates listed in the dataset. The dataset we’ll use for our test can be downloaded here :"
},
{
"code": null,
"e": 15791,
"s": 15685,
"text": "Basic Business License in Last 30 Days: opendata.dc.gov dataset, 6418 records (as of 26/01/2020), 2.64 Mb"
},
{
"code": null,
"e": 15873,
"s": 15791,
"text": "And the results are in (the test details are available in the Jupyter Notebook) :"
}
] |
C# | Math Class Fields with Examples - GeeksforGeeks | 13 Jan, 2022
In C#, the Math class provides the constants and the static methods for logarithmic, trigonometric, and other mathematical functions. Math class has two fields as follows:
Math.E Field
Math.PI Field
This field represents the natural logarithmic base, specified by the constant, e.
Syntax:
public const double E
Program 1: To illustrate the Math.E field in Math class
C#
// C# program to demonstrate the// Constant values of Math.E functionusing System; class GFG { // Main method static void Main() { // To find E constant values double e = Math.E; // Print result Console.WriteLine("Math.E = " + e); }}
Math.E = 2.71828182845905
Program 2: Let’s see an example to compare Math.E with the value calculated from a power series.
C#
// C# program to demonstrate the to// find the values of Math.E fieldusing System; class GFG { // Main Method public static void Main() { // Initialize the data double fact = 1.0; double PS = 0.0; // for loop run until the absolute // values condition satisfied for (int n = 0; n < 10 && Math.Abs(Math.E - PS) > 1.0E-15; n++) { // Calculate the factorial if (n > 0) // update factorial fact *= (double)n; // Calculate the power series. PS += 1.0 / fact; // Display the power series result Console.WriteLine(PS); Console.WriteLine(Math.E - PS); } }}
1
1.71828182845905
2
0.718281828459045
2.5
0.218281828459045
2.66666666666667
0.0516151617923786
2.70833333333333
0.00994849512571205
2.71666666666667
0.00161516179237875
2.71805555555556
0.000226272903489644
2.71825396825397
2.7860205076724E-05
2.71827876984127
3.05861777505356E-06
2.71828152557319
3.02885852843104E-07
It represents the ratio of the circumference of a circle to its diameter, specified by the constant, PI(π).
Syntax:
public const double PI
Program 1: To illustrate the Math.PI field in Math class
C#
// C# program to demonstrate the// Constant values of Math.PI functionusing System; class GFG{ // Main method static void Main() { // To find PI constant values double pi_value = Math.PI; // Print result Console.WriteLine("Math.PI = " + pi_value); }}
Math.PI = 3.14159265358979
Program 2: To demonstrate the multiplication of different data types with Math.PI constant value.
C#
// C# program to demonstrate the// Constant values of Math.PI functionusing System; class GFG{ // Main method static void Main() { // Multiply int ,float,negative number with // Math.PI and display result Console.WriteLine(1 * Math.PI ); Console.WriteLine(2 * Math.PI ); Console.WriteLine(1.5 * Math.PI ); Console.WriteLine(-3.10 * Math.PI ); }}
3.14159265358979
6.28318530717959
4.71238898038469
-9.73893722612836
Program 3: Let’s Demonstrate the access of PI and find the Volume of the cylinder.
C#
// C# program to demonstrate the// Constant values of Math.PI functionusing System; class GFG { // Main method static void Main() { // input radius value double radius = 6; // input length value double length = 9; // calculate the area using PI double area = radius * radius * Math.PI; // Calculate volume double volume = area * length; // print area and volume of cylinder Console.WriteLine("Area of cylinder is : " + area); Console.WriteLine("Volume of cylinder is : " + volume); }}
Area of cylinder is : 113.097335529233
Volume of cylinder is : 1017.87601976309
References:
https://msdn.microsoft.com/en-us/library/system.math.e(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.math.pi(v=vs.110).aspx
surinderdawra388
CSharp-Math
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | Class and Object
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework | [
{
"code": null,
"e": 25887,
"s": 25859,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 26060,
"s": 25887,
"text": "In C#, the Math class provides the constants and the static methods for logarithmic, trigonometric, and other mathematical functions. Math class has two fields as follows: "
},
{
"code": null,
"e": 26073,
"s": 26060,
"text": "Math.E Field"
},
{
"code": null,
"e": 26087,
"s": 26073,
"text": "Math.PI Field"
},
{
"code": null,
"e": 26169,
"s": 26087,
"text": "This field represents the natural logarithmic base, specified by the constant, e."
},
{
"code": null,
"e": 26179,
"s": 26169,
"text": "Syntax: "
},
{
"code": null,
"e": 26201,
"s": 26179,
"text": "public const double E"
},
{
"code": null,
"e": 26258,
"s": 26201,
"text": "Program 1: To illustrate the Math.E field in Math class "
},
{
"code": null,
"e": 26261,
"s": 26258,
"text": "C#"
},
{
"code": "// C# program to demonstrate the// Constant values of Math.E functionusing System; class GFG { // Main method static void Main() { // To find E constant values double e = Math.E; // Print result Console.WriteLine(\"Math.E = \" + e); }}",
"e": 26547,
"s": 26261,
"text": null
},
{
"code": null,
"e": 26574,
"s": 26547,
"text": "Math.E = 2.71828182845905"
},
{
"code": null,
"e": 26673,
"s": 26576,
"text": "Program 2: Let’s see an example to compare Math.E with the value calculated from a power series."
},
{
"code": null,
"e": 26676,
"s": 26673,
"text": "C#"
},
{
"code": "// C# program to demonstrate the to// find the values of Math.E fieldusing System; class GFG { // Main Method public static void Main() { // Initialize the data double fact = 1.0; double PS = 0.0; // for loop run until the absolute // values condition satisfied for (int n = 0; n < 10 && Math.Abs(Math.E - PS) > 1.0E-15; n++) { // Calculate the factorial if (n > 0) // update factorial fact *= (double)n; // Calculate the power series. PS += 1.0 / fact; // Display the power series result Console.WriteLine(PS); Console.WriteLine(Math.E - PS); } }}",
"e": 27458,
"s": 26676,
"text": null
},
{
"code": null,
"e": 27780,
"s": 27458,
"text": "1\n1.71828182845905\n2\n0.718281828459045\n2.5\n0.218281828459045\n2.66666666666667\n0.0516151617923786\n2.70833333333333\n0.00994849512571205\n2.71666666666667\n0.00161516179237875\n2.71805555555556\n0.000226272903489644\n2.71825396825397\n2.7860205076724E-05\n2.71827876984127\n3.05861777505356E-06\n2.71828152557319\n3.02885852843104E-07"
},
{
"code": null,
"e": 27890,
"s": 27782,
"text": "It represents the ratio of the circumference of a circle to its diameter, specified by the constant, PI(π)."
},
{
"code": null,
"e": 27900,
"s": 27890,
"text": "Syntax: "
},
{
"code": null,
"e": 27923,
"s": 27900,
"text": "public const double PI"
},
{
"code": null,
"e": 27981,
"s": 27923,
"text": "Program 1: To illustrate the Math.PI field in Math class "
},
{
"code": null,
"e": 27984,
"s": 27981,
"text": "C#"
},
{
"code": "// C# program to demonstrate the// Constant values of Math.PI functionusing System; class GFG{ // Main method static void Main() { // To find PI constant values double pi_value = Math.PI; // Print result Console.WriteLine(\"Math.PI = \" + pi_value); }}",
"e": 28285,
"s": 27984,
"text": null
},
{
"code": null,
"e": 28312,
"s": 28285,
"text": "Math.PI = 3.14159265358979"
},
{
"code": null,
"e": 28413,
"s": 28314,
"text": "Program 2: To demonstrate the multiplication of different data types with Math.PI constant value. "
},
{
"code": null,
"e": 28416,
"s": 28413,
"text": "C#"
},
{
"code": "// C# program to demonstrate the// Constant values of Math.PI functionusing System; class GFG{ // Main method static void Main() { // Multiply int ,float,negative number with // Math.PI and display result Console.WriteLine(1 * Math.PI ); Console.WriteLine(2 * Math.PI ); Console.WriteLine(1.5 * Math.PI ); Console.WriteLine(-3.10 * Math.PI ); }}",
"e": 28853,
"s": 28416,
"text": null
},
{
"code": null,
"e": 28922,
"s": 28853,
"text": "3.14159265358979\n6.28318530717959\n4.71238898038469\n-9.73893722612836"
},
{
"code": null,
"e": 29007,
"s": 28924,
"text": "Program 3: Let’s Demonstrate the access of PI and find the Volume of the cylinder."
},
{
"code": null,
"e": 29010,
"s": 29007,
"text": "C#"
},
{
"code": "// C# program to demonstrate the// Constant values of Math.PI functionusing System; class GFG { // Main method static void Main() { // input radius value double radius = 6; // input length value double length = 9; // calculate the area using PI double area = radius * radius * Math.PI; // Calculate volume double volume = area * length; // print area and volume of cylinder Console.WriteLine(\"Area of cylinder is : \" + area); Console.WriteLine(\"Volume of cylinder is : \" + volume); }}",
"e": 29689,
"s": 29010,
"text": null
},
{
"code": null,
"e": 29769,
"s": 29689,
"text": "Area of cylinder is : 113.097335529233\nVolume of cylinder is : 1017.87601976309"
},
{
"code": null,
"e": 29784,
"s": 29771,
"text": "References: "
},
{
"code": null,
"e": 29854,
"s": 29784,
"text": "https://msdn.microsoft.com/en-us/library/system.math.e(v=vs.110).aspx"
},
{
"code": null,
"e": 29925,
"s": 29854,
"text": "https://msdn.microsoft.com/en-us/library/system.math.pi(v=vs.110).aspx"
},
{
"code": null,
"e": 29944,
"s": 29927,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29956,
"s": 29944,
"text": "CSharp-Math"
},
{
"code": null,
"e": 29959,
"s": 29956,
"text": "C#"
},
{
"code": null,
"e": 30057,
"s": 29959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30085,
"s": 30057,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30100,
"s": 30085,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30123,
"s": 30100,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 30145,
"s": 30123,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 30191,
"s": 30145,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30214,
"s": 30191,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30236,
"s": 30214,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 30258,
"s": 30236,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 30298,
"s": 30258,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
] |
BeautifulSoup - Append to the contents of tag - GeeksforGeeks | 25 Feb, 2021
Prerequisites: Beautifulsoup
Beautifulsoup is a Python library used to extract the contents from the webpages. It is used in extracting the contents from HTML and XML structures. To use this library, we need to install it first. Here we are going to append the text to the existing contents of tag. We will do this with the help of the BeautifulSoup library.
Approach
Import module
Open HTML file
Read contents
Append content to the required tag
Save changes to the file
Function used:
Append function of the Beautifulsoup module is used to append content to desired tags.
Syntax:
append(“<string>”
File Used:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Append </title></head><body> <h1>Append to the </h1> <p>We are going to append to the contents using </p> <a href="https://www.geeksforgeeks.org/">Geeks For </a></body></html>
Python Code:
Python3
# Python program to append to the contents of tag # Importing libraryfrom bs4 import BeautifulSoup # Opening and reading the html filefile = open("gfg.html", "r")contents = file.read() soup = BeautifulSoup(contents, "lxml") # Appending to the contents of 'title' tag in html fileprint("Current content in title tag is:-")print(soup.title)soup.title.append("Using BS")print("Content after appending is:-")print(soup.title) print("\n") # Appending to the contents of 'h1' tag in html fileprint("Current content in heading h1 tag is:-")print(soup.h1)soup.h1.append("contents of tag")print("Content after appending is:-")print(soup.h1) print("\n") # Appending to the contents of 'p' tag in html fileprint("Current content in paragraph p tag is:-")print(soup.p)soup.p.append("BeautifulSoup library")print("Content after appending is:-")print(soup.p) print("\n") # Appending to the contents of 'a' tag in html fileprint("Current content in anchor a tag is:-")print(soup.a)soup.a.append("Geeks Website")print("Content after appending is:-")print(soup.a) # Code to save the changes in 'output.html' filesavechanges = soup.prettify("utf-8")with open("output.html", "wb") as file: file.write(savechanges)
Output:
output.html file
Picked
Python BeautifulSoup
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 Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 24321,
"s": 24292,
"text": "Prerequisites: Beautifulsoup"
},
{
"code": null,
"e": 24651,
"s": 24321,
"text": "Beautifulsoup is a Python library used to extract the contents from the webpages. It is used in extracting the contents from HTML and XML structures. To use this library, we need to install it first. Here we are going to append the text to the existing contents of tag. We will do this with the help of the BeautifulSoup library."
},
{
"code": null,
"e": 24660,
"s": 24651,
"text": "Approach"
},
{
"code": null,
"e": 24674,
"s": 24660,
"text": "Import module"
},
{
"code": null,
"e": 24689,
"s": 24674,
"text": "Open HTML file"
},
{
"code": null,
"e": 24703,
"s": 24689,
"text": "Read contents"
},
{
"code": null,
"e": 24738,
"s": 24703,
"text": "Append content to the required tag"
},
{
"code": null,
"e": 24763,
"s": 24738,
"text": "Save changes to the file"
},
{
"code": null,
"e": 24778,
"s": 24763,
"text": "Function used:"
},
{
"code": null,
"e": 24865,
"s": 24778,
"text": "Append function of the Beautifulsoup module is used to append content to desired tags."
},
{
"code": null,
"e": 24873,
"s": 24865,
"text": "Syntax:"
},
{
"code": null,
"e": 24891,
"s": 24873,
"text": "append(“<string>”"
},
{
"code": null,
"e": 24902,
"s": 24891,
"text": "File Used:"
},
{
"code": null,
"e": 24907,
"s": 24902,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Append </title></head><body> <h1>Append to the </h1> <p>We are going to append to the contents using </p> <a href=\"https://www.geeksforgeeks.org/\">Geeks For </a></body></html>",
"e": 25301,
"s": 24907,
"text": null
},
{
"code": null,
"e": 25315,
"s": 25301,
"text": "Python Code: "
},
{
"code": null,
"e": 25323,
"s": 25315,
"text": "Python3"
},
{
"code": "# Python program to append to the contents of tag # Importing libraryfrom bs4 import BeautifulSoup # Opening and reading the html filefile = open(\"gfg.html\", \"r\")contents = file.read() soup = BeautifulSoup(contents, \"lxml\") # Appending to the contents of 'title' tag in html fileprint(\"Current content in title tag is:-\")print(soup.title)soup.title.append(\"Using BS\")print(\"Content after appending is:-\")print(soup.title) print(\"\\n\") # Appending to the contents of 'h1' tag in html fileprint(\"Current content in heading h1 tag is:-\")print(soup.h1)soup.h1.append(\"contents of tag\")print(\"Content after appending is:-\")print(soup.h1) print(\"\\n\") # Appending to the contents of 'p' tag in html fileprint(\"Current content in paragraph p tag is:-\")print(soup.p)soup.p.append(\"BeautifulSoup library\")print(\"Content after appending is:-\")print(soup.p) print(\"\\n\") # Appending to the contents of 'a' tag in html fileprint(\"Current content in anchor a tag is:-\")print(soup.a)soup.a.append(\"Geeks Website\")print(\"Content after appending is:-\")print(soup.a) # Code to save the changes in 'output.html' filesavechanges = soup.prettify(\"utf-8\")with open(\"output.html\", \"wb\") as file: file.write(savechanges)",
"e": 26532,
"s": 25323,
"text": null
},
{
"code": null,
"e": 26540,
"s": 26532,
"text": "Output:"
},
{
"code": null,
"e": 26557,
"s": 26540,
"text": "output.html file"
},
{
"code": null,
"e": 26564,
"s": 26557,
"text": "Picked"
},
{
"code": null,
"e": 26585,
"s": 26564,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 26592,
"s": 26585,
"text": "Python"
},
{
"code": null,
"e": 26690,
"s": 26592,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26722,
"s": 26690,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26764,
"s": 26722,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26820,
"s": 26764,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26862,
"s": 26820,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26893,
"s": 26862,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26915,
"s": 26893,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26970,
"s": 26915,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27009,
"s": 26970,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27038,
"s": 27009,
"text": "Create a directory in Python"
}
] |
Python | Operators | Question 1 - GeeksforGeeks | 28 Jun, 2021
What is the output of the following code :
print 9//2
(A) 4.5(B) 4.0(C) 4(D) ErrorAnswer: (C)Explanation: The ‘//’ operator in Python returns the integer part of the floating number.Quiz of this QuestionPlease comment below if you find anything wrong in the above post
amartyaghoshgfg
Operators
Python-Operators
Python-Quizzes
Operators
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python-Quizzes | Python Dictionary Quiz | Question 23
Python-Quizzes | Python Tuples Quiz | Question 10
Python | Miscellaneous | Question 4
Python | Output Type | Question 3
Python-Quizzes | Python List Quiz | Question 22
Why do people prefer Selenium with Python?
Python-Quizzes | Python String Quiz | Question 4
Python | Miscellaneous | Question 3
Python | Animated Banner showing 'GeeksForGeeks'
Python | Miscellaneous | Question 6 | [
{
"code": null,
"e": 24093,
"s": 24065,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24136,
"s": 24093,
"text": "What is the output of the following code :"
},
{
"code": "print 9//2",
"e": 24147,
"s": 24136,
"text": null
},
{
"code": null,
"e": 24362,
"s": 24147,
"text": "(A) 4.5(B) 4.0(C) 4(D) ErrorAnswer: (C)Explanation: The ‘//’ operator in Python returns the integer part of the floating number.Quiz of this QuestionPlease comment below if you find anything wrong in the above post"
},
{
"code": null,
"e": 24378,
"s": 24362,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 24388,
"s": 24378,
"text": "Operators"
},
{
"code": null,
"e": 24405,
"s": 24388,
"text": "Python-Operators"
},
{
"code": null,
"e": 24420,
"s": 24405,
"text": "Python-Quizzes"
},
{
"code": null,
"e": 24430,
"s": 24420,
"text": "Operators"
},
{
"code": null,
"e": 24528,
"s": 24430,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24537,
"s": 24528,
"text": "Comments"
},
{
"code": null,
"e": 24550,
"s": 24537,
"text": "Old Comments"
},
{
"code": null,
"e": 24604,
"s": 24550,
"text": "Python-Quizzes | Python Dictionary Quiz | Question 23"
},
{
"code": null,
"e": 24654,
"s": 24604,
"text": "Python-Quizzes | Python Tuples Quiz | Question 10"
},
{
"code": null,
"e": 24690,
"s": 24654,
"text": "Python | Miscellaneous | Question 4"
},
{
"code": null,
"e": 24724,
"s": 24690,
"text": "Python | Output Type | Question 3"
},
{
"code": null,
"e": 24772,
"s": 24724,
"text": "Python-Quizzes | Python List Quiz | Question 22"
},
{
"code": null,
"e": 24815,
"s": 24772,
"text": "Why do people prefer Selenium with Python?"
},
{
"code": null,
"e": 24864,
"s": 24815,
"text": "Python-Quizzes | Python String Quiz | Question 4"
},
{
"code": null,
"e": 24900,
"s": 24864,
"text": "Python | Miscellaneous | Question 3"
},
{
"code": null,
"e": 24949,
"s": 24900,
"text": "Python | Animated Banner showing 'GeeksForGeeks'"
}
] |
Serverless Model Hosting with Docker, AWS Lambda and API Gateway | by Jonathan Readshaw | Towards Data Science | Previously AWS Lambda deployment packages were limited to a maximum unzipped size of 250MB including requirements. This proved to be an obstacle when attempting to host Machine Learning models using the service, as common ML libraries and complex models led to deployment packages far larger than the 250MB limit.
However in December 2020 AWS announced support for packaging and deployment of Lambda functions as Docker Images. Critically in the context of Machine Learning, these images can be up to 10GB in size. This means that large dependencies (e.g. Tensorflow) and medium-sized models can be included in the image and hence model predictions can be served using Lambda.
In this article we’ll work through an example build and deployment for model hosting on Lambda. All of the relevant code used can be found here.
Architecture Overview
The solution can be broken down into three components:
Docker Image: The docker image contains our dependencies, trained model pipeline and function code. AWS provides189097 a base image for various runtimes that can be built upon to ensure compatibility with the service.Lambda Function: Serverless resource that runs the function code in the Docker image based on incoming events/requests.API Gateway Endpoint: Used as a trigger for the Lambda function and the entry point for client requests. When prediction requests are received at the endpoint, the Lambda function is triggered with the request body included in the event sent to the function. The value(s) returned by the function are then returned to the client as a response.
Docker Image: The docker image contains our dependencies, trained model pipeline and function code. AWS provides189097 a base image for various runtimes that can be built upon to ensure compatibility with the service.
Lambda Function: Serverless resource that runs the function code in the Docker image based on incoming events/requests.
API Gateway Endpoint: Used as a trigger for the Lambda function and the entry point for client requests. When prediction requests are received at the endpoint, the Lambda function is triggered with the request body included in the event sent to the function. The value(s) returned by the function are then returned to the client as a response.
Model
In this example our model will be a simple KNN implementation trained on the Iris classification dataset. Training won’t be covered in this post however the outcome is a scikit-learn Pipeline object consisting of the following objects:
1. StandardScaler: Standardises inputs based on the mean and standard deviation of the training samples.
2. KNeighborsClassifier: The actual pretrained model. Trained with K = 5.
The pipeline is saved using scikit-learn’s Joblib implementation to ‘model_pipeline.joblib’.
Function Code
Let’s start by considering the function code that will be used by Lambda to handle prediction request events (predict\app.py).
Lambda_handler has the required arguments for functions used by lambda. The pipeline object is loaded outside of the handler in order to avoid loading this on every invocation. Lambda will keep containers alive for a period until there are no events, so loading the model once on creation means it can be reused whilst the container is kept alive by Lambda.
The handler function itself is pretty simple; the required inputs are extracted from the event body and used to generate a prediction. The prediction is the returned as part of the JSON response. The response from the function will be returned to the client by API Gateway. A few checks are made to ensure the inputs are as expected, and any prediction errors are caught and logged.
Docker Image
The Dockerfile is structured as follows:
1. Pull AWS’ base Python 3.6 image
2. Copy required files from local directory to the root of the image
3. Install requirements
4. Run handler function
Deployment
To manage deployment and AWS resources we will use AWS Serverless Application Manager (SAM) CLI. Instructions to install SAM and its dependencies can be found here.
To use SAM for build and deployment a template file must be configured. This is used to specify the required AWS resources and associated configuration.
For this project the SAM template contains the following:
Miscellaneous info such as stack name, and global configuration for Lambda timeout.
MLPredictionFunction Resource: This is the Lambda function we want to deploy. This section contains the bulk of the required config:
Properties: here we specific that the function will be defined using a Docker Image (PackageType: Image) and that the function will be triggered via API Gateway (Type: API). The API path route name and type are also defined here.
Metadata contains the tag that will be used for built images and the location/name of the Dockerfile used for building the image.
Outputs lists all of the required resources that will be created by SAM. In this case it is the API Gateway endpoint, Lambda function and associated IAM role that SAM needs.
Running the command below builds the application image locally using the defined SAM template:
!sam build
If successful the function can be invoked locally with a sample event using the following command (see repo for example event):
!sam local invoke -e events/event.json
Once the function has been tested locally the image needs to be pushed to AWS ECR. First create a new repository:
!aws ecr create-repository --repository-name ml-deploy-sam
You will need to log in to ECR’s managed Docker service before the image can be pushed:
!aws ecr get-login-password --region <region> | docker login --username AWS \ --password-stdin <account id>.dkr.ecr.<region>.amazonaws.com
Now you can deploy your application using:
!sam deploy -g
This will run the deployment in “guided” mode, where you will need to confirm the name of the application, AWS region and the image repository created earlier. Accepting the default options for the remaining settings should be fine in most instances.
The deployment process will then begin and AWS resources will be provisioned. Once complete, each resource will be displayed in the console.
Image updates: to deploy an updated model or function code, you can simply rebuild the image locally and re-run the deploy command. SAM will detect which aspects of the application have changed and update the relevant resources accordingly.
Cold Start: Each time Lambda spins up a container using our function code the model will be loaded before processing can start. This leads to a cold start scenario where the first request will be significantly slower than those that follow. One method to combat this is to periodically trigger the function using CloudWatch such that a container is always ready with the model loaded.
Multiple Functions: It is possible to deploy multiple Lambda functions to be served by a single API. This could be useful if you have multiple models to serve, or if you want to have a separate pre-processing/validation endpoint. To configure this you can simply include the additional functions in the SAM template resources. | [
{
"code": null,
"e": 486,
"s": 172,
"text": "Previously AWS Lambda deployment packages were limited to a maximum unzipped size of 250MB including requirements. This proved to be an obstacle when attempting to host Machine Learning models using the service, as common ML libraries and complex models led to deployment packages far larger than the 250MB limit."
},
{
"code": null,
"e": 849,
"s": 486,
"text": "However in December 2020 AWS announced support for packaging and deployment of Lambda functions as Docker Images. Critically in the context of Machine Learning, these images can be up to 10GB in size. This means that large dependencies (e.g. Tensorflow) and medium-sized models can be included in the image and hence model predictions can be served using Lambda."
},
{
"code": null,
"e": 994,
"s": 849,
"text": "In this article we’ll work through an example build and deployment for model hosting on Lambda. All of the relevant code used can be found here."
},
{
"code": null,
"e": 1016,
"s": 994,
"text": "Architecture Overview"
},
{
"code": null,
"e": 1071,
"s": 1016,
"text": "The solution can be broken down into three components:"
},
{
"code": null,
"e": 1751,
"s": 1071,
"text": "Docker Image: The docker image contains our dependencies, trained model pipeline and function code. AWS provides189097 a base image for various runtimes that can be built upon to ensure compatibility with the service.Lambda Function: Serverless resource that runs the function code in the Docker image based on incoming events/requests.API Gateway Endpoint: Used as a trigger for the Lambda function and the entry point for client requests. When prediction requests are received at the endpoint, the Lambda function is triggered with the request body included in the event sent to the function. The value(s) returned by the function are then returned to the client as a response."
},
{
"code": null,
"e": 1969,
"s": 1751,
"text": "Docker Image: The docker image contains our dependencies, trained model pipeline and function code. AWS provides189097 a base image for various runtimes that can be built upon to ensure compatibility with the service."
},
{
"code": null,
"e": 2089,
"s": 1969,
"text": "Lambda Function: Serverless resource that runs the function code in the Docker image based on incoming events/requests."
},
{
"code": null,
"e": 2433,
"s": 2089,
"text": "API Gateway Endpoint: Used as a trigger for the Lambda function and the entry point for client requests. When prediction requests are received at the endpoint, the Lambda function is triggered with the request body included in the event sent to the function. The value(s) returned by the function are then returned to the client as a response."
},
{
"code": null,
"e": 2439,
"s": 2433,
"text": "Model"
},
{
"code": null,
"e": 2675,
"s": 2439,
"text": "In this example our model will be a simple KNN implementation trained on the Iris classification dataset. Training won’t be covered in this post however the outcome is a scikit-learn Pipeline object consisting of the following objects:"
},
{
"code": null,
"e": 2780,
"s": 2675,
"text": "1. StandardScaler: Standardises inputs based on the mean and standard deviation of the training samples."
},
{
"code": null,
"e": 2854,
"s": 2780,
"text": "2. KNeighborsClassifier: The actual pretrained model. Trained with K = 5."
},
{
"code": null,
"e": 2947,
"s": 2854,
"text": "The pipeline is saved using scikit-learn’s Joblib implementation to ‘model_pipeline.joblib’."
},
{
"code": null,
"e": 2961,
"s": 2947,
"text": "Function Code"
},
{
"code": null,
"e": 3088,
"s": 2961,
"text": "Let’s start by considering the function code that will be used by Lambda to handle prediction request events (predict\\app.py)."
},
{
"code": null,
"e": 3446,
"s": 3088,
"text": "Lambda_handler has the required arguments for functions used by lambda. The pipeline object is loaded outside of the handler in order to avoid loading this on every invocation. Lambda will keep containers alive for a period until there are no events, so loading the model once on creation means it can be reused whilst the container is kept alive by Lambda."
},
{
"code": null,
"e": 3829,
"s": 3446,
"text": "The handler function itself is pretty simple; the required inputs are extracted from the event body and used to generate a prediction. The prediction is the returned as part of the JSON response. The response from the function will be returned to the client by API Gateway. A few checks are made to ensure the inputs are as expected, and any prediction errors are caught and logged."
},
{
"code": null,
"e": 3842,
"s": 3829,
"text": "Docker Image"
},
{
"code": null,
"e": 3883,
"s": 3842,
"text": "The Dockerfile is structured as follows:"
},
{
"code": null,
"e": 3918,
"s": 3883,
"text": "1. Pull AWS’ base Python 3.6 image"
},
{
"code": null,
"e": 3987,
"s": 3918,
"text": "2. Copy required files from local directory to the root of the image"
},
{
"code": null,
"e": 4011,
"s": 3987,
"text": "3. Install requirements"
},
{
"code": null,
"e": 4035,
"s": 4011,
"text": "4. Run handler function"
},
{
"code": null,
"e": 4046,
"s": 4035,
"text": "Deployment"
},
{
"code": null,
"e": 4211,
"s": 4046,
"text": "To manage deployment and AWS resources we will use AWS Serverless Application Manager (SAM) CLI. Instructions to install SAM and its dependencies can be found here."
},
{
"code": null,
"e": 4364,
"s": 4211,
"text": "To use SAM for build and deployment a template file must be configured. This is used to specify the required AWS resources and associated configuration."
},
{
"code": null,
"e": 4422,
"s": 4364,
"text": "For this project the SAM template contains the following:"
},
{
"code": null,
"e": 4506,
"s": 4422,
"text": "Miscellaneous info such as stack name, and global configuration for Lambda timeout."
},
{
"code": null,
"e": 4639,
"s": 4506,
"text": "MLPredictionFunction Resource: This is the Lambda function we want to deploy. This section contains the bulk of the required config:"
},
{
"code": null,
"e": 4869,
"s": 4639,
"text": "Properties: here we specific that the function will be defined using a Docker Image (PackageType: Image) and that the function will be triggered via API Gateway (Type: API). The API path route name and type are also defined here."
},
{
"code": null,
"e": 4999,
"s": 4869,
"text": "Metadata contains the tag that will be used for built images and the location/name of the Dockerfile used for building the image."
},
{
"code": null,
"e": 5173,
"s": 4999,
"text": "Outputs lists all of the required resources that will be created by SAM. In this case it is the API Gateway endpoint, Lambda function and associated IAM role that SAM needs."
},
{
"code": null,
"e": 5268,
"s": 5173,
"text": "Running the command below builds the application image locally using the defined SAM template:"
},
{
"code": null,
"e": 5279,
"s": 5268,
"text": "!sam build"
},
{
"code": null,
"e": 5407,
"s": 5279,
"text": "If successful the function can be invoked locally with a sample event using the following command (see repo for example event):"
},
{
"code": null,
"e": 5446,
"s": 5407,
"text": "!sam local invoke -e events/event.json"
},
{
"code": null,
"e": 5560,
"s": 5446,
"text": "Once the function has been tested locally the image needs to be pushed to AWS ECR. First create a new repository:"
},
{
"code": null,
"e": 5619,
"s": 5560,
"text": "!aws ecr create-repository --repository-name ml-deploy-sam"
},
{
"code": null,
"e": 5707,
"s": 5619,
"text": "You will need to log in to ECR’s managed Docker service before the image can be pushed:"
},
{
"code": null,
"e": 5846,
"s": 5707,
"text": "!aws ecr get-login-password --region <region> | docker login --username AWS \\ --password-stdin <account id>.dkr.ecr.<region>.amazonaws.com"
},
{
"code": null,
"e": 5889,
"s": 5846,
"text": "Now you can deploy your application using:"
},
{
"code": null,
"e": 5904,
"s": 5889,
"text": "!sam deploy -g"
},
{
"code": null,
"e": 6155,
"s": 5904,
"text": "This will run the deployment in “guided” mode, where you will need to confirm the name of the application, AWS region and the image repository created earlier. Accepting the default options for the remaining settings should be fine in most instances."
},
{
"code": null,
"e": 6296,
"s": 6155,
"text": "The deployment process will then begin and AWS resources will be provisioned. Once complete, each resource will be displayed in the console."
},
{
"code": null,
"e": 6537,
"s": 6296,
"text": "Image updates: to deploy an updated model or function code, you can simply rebuild the image locally and re-run the deploy command. SAM will detect which aspects of the application have changed and update the relevant resources accordingly."
},
{
"code": null,
"e": 6922,
"s": 6537,
"text": "Cold Start: Each time Lambda spins up a container using our function code the model will be loaded before processing can start. This leads to a cold start scenario where the first request will be significantly slower than those that follow. One method to combat this is to periodically trigger the function using CloudWatch such that a container is always ready with the model loaded."
}
] |
Create Battery Notifier for Laptop using Python - GeeksforGeeks | 09 Mar, 2021
Laptop or P.C battery charging is always a tension. We often forget to charge our laptop and seem to check the battery. This article demonstrates how to create a simple Battery Notifier application using Python. A battery notifier is a simple application that produces a notification message in the form of a pop-up message on the desktop. With Python, we can do so with the help of psutil library and plyer library.
psutil(python system and process utilities): It is a cross-platform for retrieving information on running processes and system utilization in python
pip install psutil
plyer: Plyer module is used to access the features of the hardware. This module does not comes built-in with Python. We need to install it externally. To install this module type the below command in the terminal.
pip install plyer
Approach:
Step 1) Import the notification class from the plyer module
from plyer import notification
Step 2) After that you just need to call the notify method of this class.
Syntax: notify(title=”, message=”, app_name=”, app_icon=”, timeout=10, ticker=”, toast=False)
Parameters:
title (str) – Title of the notification
message (str) – Message of the notification
app_name (str) – Name of the app launching this notification
app_icon (str) – Icon to be displayed along with the message
timeout (int) – time to display the message for, defaults to 10
ticker (str) – text to display on status bar as the notification arrives
toast (bool) – simple Android message instead of full notification
Step 3) Add the sleep function to show that notification again.
Below is the implementation.
Python3
import psutilfrom plyer import notificationimport time # from psutil we will import the# sensors_battery class and with# that we have the battery remainingwhile(True): battery = psutil.sensors_battery() percent = battery.percent notification.notify( title="Battery Percentage", message=str(percent)+"% Battery remaining", timeout=10 ) # after every 60 mins it will show the # battery percentage time.sleep(60*60) continue
Output:
Note: The time in the sleep function has been reduced to record the output window.
abhigoya
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 24816,
"s": 24788,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 25234,
"s": 24816,
"text": "Laptop or P.C battery charging is always a tension. We often forget to charge our laptop and seem to check the battery. This article demonstrates how to create a simple Battery Notifier application using Python. A battery notifier is a simple application that produces a notification message in the form of a pop-up message on the desktop. With Python, we can do so with the help of psutil library and plyer library."
},
{
"code": null,
"e": 25383,
"s": 25234,
"text": "psutil(python system and process utilities): It is a cross-platform for retrieving information on running processes and system utilization in python"
},
{
"code": null,
"e": 25402,
"s": 25383,
"text": "pip install psutil"
},
{
"code": null,
"e": 25616,
"s": 25402,
"text": "plyer: Plyer module is used to access the features of the hardware. This module does not comes built-in with Python. We need to install it externally. To install this module type the below command in the terminal."
},
{
"code": null,
"e": 25634,
"s": 25616,
"text": "pip install plyer"
},
{
"code": null,
"e": 25644,
"s": 25634,
"text": "Approach:"
},
{
"code": null,
"e": 25704,
"s": 25644,
"text": "Step 1) Import the notification class from the plyer module"
},
{
"code": null,
"e": 25735,
"s": 25704,
"text": "from plyer import notification"
},
{
"code": null,
"e": 25809,
"s": 25735,
"text": "Step 2) After that you just need to call the notify method of this class."
},
{
"code": null,
"e": 25903,
"s": 25809,
"text": "Syntax: notify(title=”, message=”, app_name=”, app_icon=”, timeout=10, ticker=”, toast=False)"
},
{
"code": null,
"e": 25915,
"s": 25903,
"text": "Parameters:"
},
{
"code": null,
"e": 25955,
"s": 25915,
"text": "title (str) – Title of the notification"
},
{
"code": null,
"e": 25999,
"s": 25955,
"text": "message (str) – Message of the notification"
},
{
"code": null,
"e": 26060,
"s": 25999,
"text": "app_name (str) – Name of the app launching this notification"
},
{
"code": null,
"e": 26121,
"s": 26060,
"text": "app_icon (str) – Icon to be displayed along with the message"
},
{
"code": null,
"e": 26185,
"s": 26121,
"text": "timeout (int) – time to display the message for, defaults to 10"
},
{
"code": null,
"e": 26258,
"s": 26185,
"text": "ticker (str) – text to display on status bar as the notification arrives"
},
{
"code": null,
"e": 26325,
"s": 26258,
"text": "toast (bool) – simple Android message instead of full notification"
},
{
"code": null,
"e": 26389,
"s": 26325,
"text": "Step 3) Add the sleep function to show that notification again."
},
{
"code": null,
"e": 26418,
"s": 26389,
"text": "Below is the implementation."
},
{
"code": null,
"e": 26426,
"s": 26418,
"text": "Python3"
},
{
"code": "import psutilfrom plyer import notificationimport time # from psutil we will import the# sensors_battery class and with# that we have the battery remainingwhile(True): battery = psutil.sensors_battery() percent = battery.percent notification.notify( title=\"Battery Percentage\", message=str(percent)+\"% Battery remaining\", timeout=10 ) # after every 60 mins it will show the # battery percentage time.sleep(60*60) continue",
"e": 26910,
"s": 26426,
"text": null
},
{
"code": null,
"e": 26921,
"s": 26913,
"text": "Output:"
},
{
"code": null,
"e": 27007,
"s": 26923,
"text": "Note: The time in the sleep function has been reduced to record the output window. "
},
{
"code": null,
"e": 27016,
"s": 27007,
"text": "abhigoya"
},
{
"code": null,
"e": 27031,
"s": 27016,
"text": "python-utility"
},
{
"code": null,
"e": 27038,
"s": 27031,
"text": "Python"
},
{
"code": null,
"e": 27136,
"s": 27038,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27154,
"s": 27136,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27176,
"s": 27154,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27208,
"s": 27176,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27250,
"s": 27208,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27276,
"s": 27250,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27313,
"s": 27276,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27342,
"s": 27313,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27384,
"s": 27342,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27409,
"s": 27384,
"text": "sum() function in Python"
}
] |
How to simulate scanf() method using Python? | Python does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf()format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions.
To extract the filename and numbers from a string like
/usr/sbin/sendmail - 0 errors, 4 warnings
you would use a scanf() format like
%s - %d errors, %d warnings
The equivalent regular expression would be
(\S+) - (\d+) errors, (\d+) warnings | [
{
"code": null,
"e": 1338,
"s": 1062,
"text": "Python does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf()format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions."
},
{
"code": null,
"e": 1393,
"s": 1338,
"text": "To extract the filename and numbers from a string like"
},
{
"code": null,
"e": 1435,
"s": 1393,
"text": "/usr/sbin/sendmail - 0 errors, 4 warnings"
},
{
"code": null,
"e": 1471,
"s": 1435,
"text": "you would use a scanf() format like"
},
{
"code": null,
"e": 1499,
"s": 1471,
"text": "%s - %d errors, %d warnings"
},
{
"code": null,
"e": 1542,
"s": 1499,
"text": "The equivalent regular expression would be"
},
{
"code": null,
"e": 1579,
"s": 1542,
"text": "(\\S+) - (\\d+) errors, (\\d+) warnings"
}
] |
Chef - Roles | Roles in Chef are a logical way of grouping nodes. Typical cases are to have roles for web servers, database servers, and so on. One can set custom run list for all the nodes and override attribute value within roles.
vipin@laptop:~/chef-repo $ subl roles/web_servers.rb
name "web_servers"
description "This role contains nodes, which act as web servers"
run_list "recipe[ntp]"
default_attributes 'ntp' => {
'ntpdate' => {
'disable' => true
}
}
Once we have the role created, we need to upload to the Chef server.
vipin@laptop:~/chef-repo $ knife role from file web_servers.rb
Now, we need to assign a role to a node called server.
vipin@laptop:~/chef-repo $ knife node edit server
"run_list": [
"role[web_servers]"
]
Saving updated run_list on node server
user@server:~$ sudo chef-client
...TRUNCATED OUTPUT...
[2013-07-25T13:28:24+00:00] INFO: Run List is [role[web_servers]]
[2013-07-25T13:28:24+00:00] INFO: Run List expands to [ntp]
...TRUNCATED OUTPUT...
Define a role in a Ruby file inside the roles folder of Chef repository.
Define a role in a Ruby file inside the roles folder of Chef repository.
A role consists of a name and a description attribute.
A role consists of a name and a description attribute.
A role consists of role-specific run list and role-specific attribute settings.
A role consists of role-specific run list and role-specific attribute settings.
Every node that has a role in its run list will have the role’s run list exacted into its own.
Every node that has a role in its run list will have the role’s run list exacted into its own.
All the recipes in the role’s run list will be executed on the node.
All the recipes in the role’s run list will be executed on the node.
The role will be uploaded to Chef server using the knife role from file command.
The role will be uploaded to Chef server using the knife role from file command.
The role will be added to the node run list.
The role will be added to the node run list.
Running Chef client on a node having the role in its run list will execute all the recipes listed in the role.
Running Chef client on a node having the role in its run list will execute all the recipes listed in the role.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2598,
"s": 2380,
"text": "Roles in Chef are a logical way of grouping nodes. Typical cases are to have roles for web servers, database servers, and so on. One can set custom run list for all the nodes and override attribute value within roles."
},
{
"code": null,
"e": 2845,
"s": 2598,
"text": "vipin@laptop:~/chef-repo $ subl roles/web_servers.rb \nname \"web_servers\" \ndescription \"This role contains nodes, which act as web servers\" \nrun_list \"recipe[ntp]\" \ndefault_attributes 'ntp' => { \n 'ntpdate' => { \n 'disable' => true \n } \n}"
},
{
"code": null,
"e": 2914,
"s": 2845,
"text": "Once we have the role created, we need to upload to the Chef server."
},
{
"code": null,
"e": 2979,
"s": 2914,
"text": "vipin@laptop:~/chef-repo $ knife role from file web_servers.rb \n"
},
{
"code": null,
"e": 3034,
"s": 2979,
"text": "Now, we need to assign a role to a node called server."
},
{
"code": null,
"e": 3167,
"s": 3034,
"text": "vipin@laptop:~/chef-repo $ knife node edit server \n\"run_list\": [ \n \"role[web_servers]\" \n] \nSaving updated run_list on node server "
},
{
"code": null,
"e": 3377,
"s": 3167,
"text": "user@server:~$ sudo chef-client \n...TRUNCATED OUTPUT... \n[2013-07-25T13:28:24+00:00] INFO: Run List is [role[web_servers]] \n[2013-07-25T13:28:24+00:00] INFO: Run List expands to [ntp] \n...TRUNCATED OUTPUT... \n"
},
{
"code": null,
"e": 3450,
"s": 3377,
"text": "Define a role in a Ruby file inside the roles folder of Chef repository."
},
{
"code": null,
"e": 3523,
"s": 3450,
"text": "Define a role in a Ruby file inside the roles folder of Chef repository."
},
{
"code": null,
"e": 3578,
"s": 3523,
"text": "A role consists of a name and a description attribute."
},
{
"code": null,
"e": 3633,
"s": 3578,
"text": "A role consists of a name and a description attribute."
},
{
"code": null,
"e": 3713,
"s": 3633,
"text": "A role consists of role-specific run list and role-specific attribute settings."
},
{
"code": null,
"e": 3793,
"s": 3713,
"text": "A role consists of role-specific run list and role-specific attribute settings."
},
{
"code": null,
"e": 3888,
"s": 3793,
"text": "Every node that has a role in its run list will have the role’s run list exacted into its own."
},
{
"code": null,
"e": 3983,
"s": 3888,
"text": "Every node that has a role in its run list will have the role’s run list exacted into its own."
},
{
"code": null,
"e": 4052,
"s": 3983,
"text": "All the recipes in the role’s run list will be executed on the node."
},
{
"code": null,
"e": 4121,
"s": 4052,
"text": "All the recipes in the role’s run list will be executed on the node."
},
{
"code": null,
"e": 4202,
"s": 4121,
"text": "The role will be uploaded to Chef server using the knife role from file command."
},
{
"code": null,
"e": 4283,
"s": 4202,
"text": "The role will be uploaded to Chef server using the knife role from file command."
},
{
"code": null,
"e": 4328,
"s": 4283,
"text": "The role will be added to the node run list."
},
{
"code": null,
"e": 4373,
"s": 4328,
"text": "The role will be added to the node run list."
},
{
"code": null,
"e": 4484,
"s": 4373,
"text": "Running Chef client on a node having the role in its run list will execute all the recipes listed in the role."
},
{
"code": null,
"e": 4595,
"s": 4484,
"text": "Running Chef client on a node having the role in its run list will execute all the recipes listed in the role."
},
{
"code": null,
"e": 4602,
"s": 4595,
"text": " Print"
},
{
"code": null,
"e": 4613,
"s": 4602,
"text": " Add Notes"
}
] |
Storing value from a MySQL SELECT statement to a variable? | Let us first create a table −
mysql> create table DemoTable631 (
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentName varchar(100)
);
Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable631(StudentName) values('John Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable631(StudentName) values('Adam Smith');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable631(StudentName) values('David Miller');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable631;
This will produce the following output −
+-----------+--------------+
| StudentId | StudentName |
+-----------+--------------+
| 1 | John Smith |
| 2 | Adam Smith |
| 3 | David Miller |
+-----------+--------------+
3 rows in set (0.00 sec)
Following is the query to store value from select to a variable −
mysql> set @fullName=(select StudentName from DemoTable631 where StudentId=2);
Query OK, 0 rows affected (0.00 sec)
Now you can display the value of a variable −
mysql> select @fullName;
This will produce the following output −
+------------+
| @fullName |
+------------+
| Adam Smith |
+------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1245,
"s": 1092,
"text": "mysql> create table DemoTable631 (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentName varchar(100)\n);\nQuery OK, 0 rows affected (0.83 sec)"
},
{
"code": null,
"e": 1301,
"s": 1245,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1612,
"s": 1301,
"text": "mysql> insert into DemoTable631(StudentName) values('John Smith');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable631(StudentName) values('Adam Smith');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable631(StudentName) values('David Miller');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1672,
"s": 1612,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1706,
"s": 1672,
"text": "mysql> select *from DemoTable631;"
},
{
"code": null,
"e": 1747,
"s": 1706,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1975,
"s": 1747,
"text": "+-----------+--------------+\n| StudentId | StudentName |\n+-----------+--------------+\n| 1 | John Smith |\n| 2 | Adam Smith |\n| 3 | David Miller |\n+-----------+--------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2041,
"s": 1975,
"text": "Following is the query to store value from select to a variable −"
},
{
"code": null,
"e": 2157,
"s": 2041,
"text": "mysql> set @fullName=(select StudentName from DemoTable631 where StudentId=2);\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2203,
"s": 2157,
"text": "Now you can display the value of a variable −"
},
{
"code": null,
"e": 2228,
"s": 2203,
"text": "mysql> select @fullName;"
},
{
"code": null,
"e": 2269,
"s": 2228,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2368,
"s": 2269,
"text": "+------------+\n| @fullName |\n+------------+\n| Adam Smith |\n+------------+\n1 row in set (0.00 sec)"
}
] |
Count of elements of an array present in every row of NxM matrix in C++ | We are given an array of integer type elements and a matrix or 2-D array of given row and column size and the task is to calculate the count of elements of an array that are present in each row of a matrix.
Input
int arr = { 2, 4, 6} and int matrix[row][col] = { { 2, 4, 6 }, {3, 4, 6}, {6, 2, 1}}
Output
Elements of array in row 1 are: 3
Elements of array in row 2 are: 2
Elements of array in row 3 are: 2
Explanation
we are having array containing 2, 4 and 6 as elements and now we will check the occurrences of 3 elements in every row of matrix by matching the elements of an array with the elements of a matrix, like, 2, 4 and 6 all are present in first row of matrix so the count of elements for row 1 is 3, similarly, count of elements for row 2 is 2 as only 4 and 6 are there and count of elements for row 3 is 2 as only 2 and 6 are there.
Input
int arr = { 1, 3} and int matrix[row][col] = { { 1, 4, 6 }, {3, 1, 6}, {6, 2, 4}}
Output
Elements of array in row 1 are: 1
Elements of array in row 2 are: 2
Elements of array in row 3 are: 0
Explanation
we are having array containing 1 and 3 as elements and now we will check the occurrences of 2 elements in every row of matrix by matching the elements of an array with theelements of a matrix, like, only 1 is present in first row of matrix so the count of elements for row 1 is 1, similarly, count of elements for row 2 is 2 as 1 and 3 both are there and count of elements for row 3 is 0 as none of 1 and 3 are there.
There can be multiple approaches to solve the given problem i.e. naive approach and efficient approach. So let’s first look at the naive approach.
Input an array of integer elements and matrix of row and column size
Input an array of integer elements and matrix of row and column size
Calculate the size of an array and pass the array, matrix and size of array to the function for further processing
Calculate the size of an array and pass the array, matrix and size of array to the function for further processing
Take a temporary variable count to store the count of elements present in the matrix row.
Take a temporary variable count to store the count of elements present in the matrix row.
Start loop FOR from 0 till the row size of a matrix
Start loop FOR from 0 till the row size of a matrix
Inside the loop, start FOR from 0 till the size of an array
Inside the loop, start FOR from 0 till the size of an array
Set a temp with arr[k]
Set a temp with arr[k]
Start another loop FOR from 0 till the column size of a matrix
Start another loop FOR from 0 till the column size of a matrix
Inside the loops, check IF temp = matrix[i][j] then increment the count by 1
Inside the loops, check IF temp = matrix[i][j] then increment the count by 1
Set count to 0 to refresh it after the change of every row
Set count to 0 to refresh it after the change of every row
Print the value of count before change of every row.
Print the value of count before change of every row.
Input an array of integer elements and matrix of row and column size
Input an array of integer elements and matrix of row and column size
Calculate the size of an array and pass the array, matrix and size of array to the function for further processing
Calculate the size of an array and pass the array, matrix and size of array to the function for further processing
Start loop FOR from 0 till the row size of a matrix
Start loop FOR from 0 till the row size of a matrix
Create a variable of type unordered_map
Create a variable of type unordered_map
Start another loop FOR from 0 till the column size of a matrix
Start another loop FOR from 0 till the column size of a matrix
Set an unordered map with matrix[i][j] as 1
Set an unordered map with matrix[i][j] as 1
Take a temporary variable count to store the count of elements present in the matrix row.
Take a temporary variable count to store the count of elements present in the matrix row.
Inside the loop, start FOR from 0 till the size of an array
Inside the loop, start FOR from 0 till the size of an array
Check IF um[arr[j]]==1 then increment the count by 1
Check IF um[arr[j]]==1 then increment the count by 1
Print the value of count before change of every row.
Print the value of count before change of every row.
Live Demo
#include<bits/stdc++.h>
using namespace std;
#define row 3
#define col 3
void arr_matrix(int matrix[row][col], int arr[], int size){
int count = 0;
//for matrix row
for(int i=0; i<row; i++){
//for array
for(int k=0 ; k<size ; k++){
int temp = arr[k];
//for matrix col
for(int j = 0; j<col; j++){
if(temp == matrix[i][j]){
count++;
}
}
}
cout<<"Elements of array in row "<< i + 1 <<" are: " << count << endl;
count = 0;
}
}
int main(){
int matrix[row][col] = { { 2, 4, 6 }, {3, 4, 6}, {6, 2, 1}};
int arr[] = { 2, 4, 6};
int size = sizeof(arr) / sizeof(arr[0]);
arr_matrix(matrix, arr, size);
}
If we run the above code it will generate the following output −
Elements of array in row 1 are: 3
Elements of array in row 2 are: 2
Elements of array in row 3 are: 2
Live Demo
#include <bits/stdc++.h>
using namespace std;
#define row 3
#define col 3
void arr_matrix(int matrix[row][col], int arr[], int size){
for (int i = 0; i < row; i++){
unordered_map<int, int> um;
for (int j = 0; j < col; j++){
um[matrix[i][j]] = 1;
}
int count = 0;
for (int j = 0; j < size; j++) {
if (um[arr[j]])
count++;
}
cout<<"Elements of array in row "<< i + 1 <<" are: " << count << endl;
}
}
int main(){
int matrix[row][col] = { { 2, 4, 6 }, {3, 4, 6}, {6, 2, 1}};
int arr[] = { 2, 4, 6};
int size = sizeof(arr) / sizeof(arr[0]);
arr_matrix(matrix, arr, size);
}
If we run the above code it will generate the following output −
Elements of array in row 1 are: 3
Elements of array in row 2 are: 2
Elements of array in row 3 are: 2 | [
{
"code": null,
"e": 1269,
"s": 1062,
"text": "We are given an array of integer type elements and a matrix or 2-D array of given row and column size and the task is to calculate the count of elements of an array that are present in each row of a matrix."
},
{
"code": null,
"e": 1276,
"s": 1269,
"text": "Input "
},
{
"code": null,
"e": 1361,
"s": 1276,
"text": "int arr = { 2, 4, 6} and int matrix[row][col] = { { 2, 4, 6 }, {3, 4, 6}, {6, 2, 1}}"
},
{
"code": null,
"e": 1369,
"s": 1361,
"text": "Output "
},
{
"code": null,
"e": 1471,
"s": 1369,
"text": "Elements of array in row 1 are: 3\nElements of array in row 2 are: 2\nElements of array in row 3 are: 2"
},
{
"code": null,
"e": 1484,
"s": 1471,
"text": "Explanation "
},
{
"code": null,
"e": 1912,
"s": 1484,
"text": "we are having array containing 2, 4 and 6 as elements and now we will check the occurrences of 3 elements in every row of matrix by matching the elements of an array with the elements of a matrix, like, 2, 4 and 6 all are present in first row of matrix so the count of elements for row 1 is 3, similarly, count of elements for row 2 is 2 as only 4 and 6 are there and count of elements for row 3 is 2 as only 2 and 6 are there."
},
{
"code": null,
"e": 1919,
"s": 1912,
"text": "Input "
},
{
"code": null,
"e": 2001,
"s": 1919,
"text": "int arr = { 1, 3} and int matrix[row][col] = { { 1, 4, 6 }, {3, 1, 6}, {6, 2, 4}}"
},
{
"code": null,
"e": 2009,
"s": 2001,
"text": "Output "
},
{
"code": null,
"e": 2111,
"s": 2009,
"text": "Elements of array in row 1 are: 1\nElements of array in row 2 are: 2\nElements of array in row 3 are: 0"
},
{
"code": null,
"e": 2124,
"s": 2111,
"text": "Explanation "
},
{
"code": null,
"e": 2542,
"s": 2124,
"text": "we are having array containing 1 and 3 as elements and now we will check the occurrences of 2 elements in every row of matrix by matching the elements of an array with theelements of a matrix, like, only 1 is present in first row of matrix so the count of elements for row 1 is 1, similarly, count of elements for row 2 is 2 as 1 and 3 both are there and count of elements for row 3 is 0 as none of 1 and 3 are there."
},
{
"code": null,
"e": 2689,
"s": 2542,
"text": "There can be multiple approaches to solve the given problem i.e. naive approach and efficient approach. So let’s first look at the naive approach."
},
{
"code": null,
"e": 2758,
"s": 2689,
"text": "Input an array of integer elements and matrix of row and column size"
},
{
"code": null,
"e": 2827,
"s": 2758,
"text": "Input an array of integer elements and matrix of row and column size"
},
{
"code": null,
"e": 2942,
"s": 2827,
"text": "Calculate the size of an array and pass the array, matrix and size of array to the function for further processing"
},
{
"code": null,
"e": 3057,
"s": 2942,
"text": "Calculate the size of an array and pass the array, matrix and size of array to the function for further processing"
},
{
"code": null,
"e": 3147,
"s": 3057,
"text": "Take a temporary variable count to store the count of elements present in the matrix row."
},
{
"code": null,
"e": 3237,
"s": 3147,
"text": "Take a temporary variable count to store the count of elements present in the matrix row."
},
{
"code": null,
"e": 3289,
"s": 3237,
"text": "Start loop FOR from 0 till the row size of a matrix"
},
{
"code": null,
"e": 3341,
"s": 3289,
"text": "Start loop FOR from 0 till the row size of a matrix"
},
{
"code": null,
"e": 3401,
"s": 3341,
"text": "Inside the loop, start FOR from 0 till the size of an array"
},
{
"code": null,
"e": 3461,
"s": 3401,
"text": "Inside the loop, start FOR from 0 till the size of an array"
},
{
"code": null,
"e": 3484,
"s": 3461,
"text": "Set a temp with arr[k]"
},
{
"code": null,
"e": 3507,
"s": 3484,
"text": "Set a temp with arr[k]"
},
{
"code": null,
"e": 3570,
"s": 3507,
"text": "Start another loop FOR from 0 till the column size of a matrix"
},
{
"code": null,
"e": 3633,
"s": 3570,
"text": "Start another loop FOR from 0 till the column size of a matrix"
},
{
"code": null,
"e": 3710,
"s": 3633,
"text": "Inside the loops, check IF temp = matrix[i][j] then increment the count by 1"
},
{
"code": null,
"e": 3787,
"s": 3710,
"text": "Inside the loops, check IF temp = matrix[i][j] then increment the count by 1"
},
{
"code": null,
"e": 3846,
"s": 3787,
"text": "Set count to 0 to refresh it after the change of every row"
},
{
"code": null,
"e": 3905,
"s": 3846,
"text": "Set count to 0 to refresh it after the change of every row"
},
{
"code": null,
"e": 3958,
"s": 3905,
"text": "Print the value of count before change of every row."
},
{
"code": null,
"e": 4011,
"s": 3958,
"text": "Print the value of count before change of every row."
},
{
"code": null,
"e": 4080,
"s": 4011,
"text": "Input an array of integer elements and matrix of row and column size"
},
{
"code": null,
"e": 4149,
"s": 4080,
"text": "Input an array of integer elements and matrix of row and column size"
},
{
"code": null,
"e": 4264,
"s": 4149,
"text": "Calculate the size of an array and pass the array, matrix and size of array to the function for further processing"
},
{
"code": null,
"e": 4379,
"s": 4264,
"text": "Calculate the size of an array and pass the array, matrix and size of array to the function for further processing"
},
{
"code": null,
"e": 4431,
"s": 4379,
"text": "Start loop FOR from 0 till the row size of a matrix"
},
{
"code": null,
"e": 4483,
"s": 4431,
"text": "Start loop FOR from 0 till the row size of a matrix"
},
{
"code": null,
"e": 4523,
"s": 4483,
"text": "Create a variable of type unordered_map"
},
{
"code": null,
"e": 4563,
"s": 4523,
"text": "Create a variable of type unordered_map"
},
{
"code": null,
"e": 4626,
"s": 4563,
"text": "Start another loop FOR from 0 till the column size of a matrix"
},
{
"code": null,
"e": 4689,
"s": 4626,
"text": "Start another loop FOR from 0 till the column size of a matrix"
},
{
"code": null,
"e": 4733,
"s": 4689,
"text": "Set an unordered map with matrix[i][j] as 1"
},
{
"code": null,
"e": 4777,
"s": 4733,
"text": "Set an unordered map with matrix[i][j] as 1"
},
{
"code": null,
"e": 4867,
"s": 4777,
"text": "Take a temporary variable count to store the count of elements present in the matrix row."
},
{
"code": null,
"e": 4957,
"s": 4867,
"text": "Take a temporary variable count to store the count of elements present in the matrix row."
},
{
"code": null,
"e": 5017,
"s": 4957,
"text": "Inside the loop, start FOR from 0 till the size of an array"
},
{
"code": null,
"e": 5077,
"s": 5017,
"text": "Inside the loop, start FOR from 0 till the size of an array"
},
{
"code": null,
"e": 5130,
"s": 5077,
"text": "Check IF um[arr[j]]==1 then increment the count by 1"
},
{
"code": null,
"e": 5183,
"s": 5130,
"text": "Check IF um[arr[j]]==1 then increment the count by 1"
},
{
"code": null,
"e": 5236,
"s": 5183,
"text": "Print the value of count before change of every row."
},
{
"code": null,
"e": 5289,
"s": 5236,
"text": "Print the value of count before change of every row."
},
{
"code": null,
"e": 5300,
"s": 5289,
"text": " Live Demo"
},
{
"code": null,
"e": 6023,
"s": 5300,
"text": "#include<bits/stdc++.h>\nusing namespace std;\n#define row 3\n#define col 3\nvoid arr_matrix(int matrix[row][col], int arr[], int size){\n int count = 0;\n //for matrix row\n for(int i=0; i<row; i++){\n //for array\n for(int k=0 ; k<size ; k++){\n int temp = arr[k];\n //for matrix col\n for(int j = 0; j<col; j++){\n if(temp == matrix[i][j]){\n count++;\n }\n }\n }\n cout<<\"Elements of array in row \"<< i + 1 <<\" are: \" << count << endl;\n count = 0;\n }\n}\nint main(){\n int matrix[row][col] = { { 2, 4, 6 }, {3, 4, 6}, {6, 2, 1}};\n int arr[] = { 2, 4, 6};\n int size = sizeof(arr) / sizeof(arr[0]);\n arr_matrix(matrix, arr, size);\n}"
},
{
"code": null,
"e": 6088,
"s": 6023,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 6190,
"s": 6088,
"text": "Elements of array in row 1 are: 3\nElements of array in row 2 are: 2\nElements of array in row 3 are: 2"
},
{
"code": null,
"e": 6201,
"s": 6190,
"text": " Live Demo"
},
{
"code": null,
"e": 6860,
"s": 6201,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n#define row 3\n#define col 3\nvoid arr_matrix(int matrix[row][col], int arr[], int size){\n for (int i = 0; i < row; i++){\n unordered_map<int, int> um;\n for (int j = 0; j < col; j++){\n um[matrix[i][j]] = 1;\n }\n int count = 0;\n for (int j = 0; j < size; j++) {\n if (um[arr[j]])\n count++;\n }\n cout<<\"Elements of array in row \"<< i + 1 <<\" are: \" << count << endl;\n }\n}\nint main(){\n int matrix[row][col] = { { 2, 4, 6 }, {3, 4, 6}, {6, 2, 1}};\n int arr[] = { 2, 4, 6};\n int size = sizeof(arr) / sizeof(arr[0]);\n arr_matrix(matrix, arr, size);\n}"
},
{
"code": null,
"e": 6925,
"s": 6860,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 7027,
"s": 6925,
"text": "Elements of array in row 1 are: 3\nElements of array in row 2 are: 2\nElements of array in row 3 are: 2"
}
] |
Subsets and Splits